aframe-master.js 2.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485
  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":69,"xtend":72}],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":70,"xtend":72}],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":71}],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":67}],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. // Polyfills
  5593. if (Number.EPSILON === undefined) {
  5594. Number.EPSILON = Math.pow(2, -52);
  5595. }
  5596. if (Number.isInteger === undefined) {
  5597. // Missing in IE
  5598. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  5599. Number.isInteger = function (value) {
  5600. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  5601. };
  5602. } //
  5603. if (Math.sign === undefined) {
  5604. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  5605. Math.sign = function (x) {
  5606. return x < 0 ? -1 : x > 0 ? 1 : +x;
  5607. };
  5608. }
  5609. if ('name' in Function.prototype === false) {
  5610. // Missing in IE
  5611. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  5612. Object.defineProperty(Function.prototype, 'name', {
  5613. get: function get() {
  5614. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  5615. }
  5616. });
  5617. }
  5618. if (Object.assign === undefined) {
  5619. // Missing in IE
  5620. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  5621. Object.assign = function (target) {
  5622. if (target === undefined || target === null) {
  5623. throw new TypeError('Cannot convert undefined or null to object');
  5624. }
  5625. var output = Object(target);
  5626. for (var index = 1; index < arguments.length; index++) {
  5627. var source = arguments[index];
  5628. if (source !== undefined && source !== null) {
  5629. for (var nextKey in source) {
  5630. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  5631. output[nextKey] = source[nextKey];
  5632. }
  5633. }
  5634. }
  5635. }
  5636. return output;
  5637. };
  5638. }
  5639. /**
  5640. * Copyright (c) 2014-present, Facebook, Inc.
  5641. *
  5642. * This source code is licensed under the MIT license found in the
  5643. * LICENSE file in the root directory of this source tree.
  5644. */
  5645. var runtime = function (exports) {
  5646. var Op = Object.prototype;
  5647. var hasOwn = Op.hasOwnProperty;
  5648. var undefined$1; // More compressible than void 0.
  5649. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  5650. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  5651. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  5652. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  5653. function define(obj, key, value) {
  5654. Object.defineProperty(obj, key, {
  5655. value: value,
  5656. enumerable: true,
  5657. configurable: true,
  5658. writable: true
  5659. });
  5660. return obj[key];
  5661. }
  5662. try {
  5663. // IE 8 has a broken Object.defineProperty that only works on DOM objects.
  5664. define({}, "");
  5665. } catch (err) {
  5666. define = function define(obj, key, value) {
  5667. return obj[key] = value;
  5668. };
  5669. }
  5670. function wrap(innerFn, outerFn, self, tryLocsList) {
  5671. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  5672. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  5673. var generator = Object.create(protoGenerator.prototype);
  5674. var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
  5675. // .throw, and .return methods.
  5676. generator._invoke = makeInvokeMethod(innerFn, self, context);
  5677. return generator;
  5678. }
  5679. exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
  5680. // record like context.tryEntries[i].completion. This interface could
  5681. // have been (and was previously) designed to take a closure to be
  5682. // invoked without arguments, but in all the cases we care about we
  5683. // already have an existing method we want to call, so there's no need
  5684. // to create a new function object. We can even get away with assuming
  5685. // the method takes exactly one argument, since that happens to be true
  5686. // in every case, so we don't have to touch the arguments object. The
  5687. // only additional allocation required is the completion record, which
  5688. // has a stable shape and so hopefully should be cheap to allocate.
  5689. function tryCatch(fn, obj, arg) {
  5690. try {
  5691. return {
  5692. type: "normal",
  5693. arg: fn.call(obj, arg)
  5694. };
  5695. } catch (err) {
  5696. return {
  5697. type: "throw",
  5698. arg: err
  5699. };
  5700. }
  5701. }
  5702. var GenStateSuspendedStart = "suspendedStart";
  5703. var GenStateSuspendedYield = "suspendedYield";
  5704. var GenStateExecuting = "executing";
  5705. var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
  5706. // breaking out of the dispatch switch statement.
  5707. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
  5708. // .constructor.prototype properties for functions that return Generator
  5709. // objects. For full spec compliance, you may wish to configure your
  5710. // minifier not to mangle the names of these two functions.
  5711. function Generator() {}
  5712. function GeneratorFunction() {}
  5713. function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
  5714. // don't natively support it.
  5715. var IteratorPrototype = {};
  5716. IteratorPrototype[iteratorSymbol] = function () {
  5717. return this;
  5718. };
  5719. var getProto = Object.getPrototypeOf;
  5720. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  5721. if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  5722. // This environment has a native %IteratorPrototype%; use it instead
  5723. // of the polyfill.
  5724. IteratorPrototype = NativeIteratorPrototype;
  5725. }
  5726. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  5727. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  5728. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  5729. GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the
  5730. // Iterator interface in terms of a single ._invoke method.
  5731. function defineIteratorMethods(prototype) {
  5732. ["next", "throw", "return"].forEach(function (method) {
  5733. define(prototype, method, function (arg) {
  5734. return this._invoke(method, arg);
  5735. });
  5736. });
  5737. }
  5738. exports.isGeneratorFunction = function (genFun) {
  5739. var ctor = typeof genFun === "function" && genFun.constructor;
  5740. return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
  5741. // do is to check its .name property.
  5742. (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
  5743. };
  5744. exports.mark = function (genFun) {
  5745. if (Object.setPrototypeOf) {
  5746. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  5747. } else {
  5748. genFun.__proto__ = GeneratorFunctionPrototype;
  5749. define(genFun, toStringTagSymbol, "GeneratorFunction");
  5750. }
  5751. genFun.prototype = Object.create(Gp);
  5752. return genFun;
  5753. }; // Within the body of any async function, `await x` is transformed to
  5754. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  5755. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  5756. // meant to be awaited.
  5757. exports.awrap = function (arg) {
  5758. return {
  5759. __await: arg
  5760. };
  5761. };
  5762. function AsyncIterator(generator, PromiseImpl) {
  5763. function invoke(method, arg, resolve, reject) {
  5764. var record = tryCatch(generator[method], generator, arg);
  5765. if (record.type === "throw") {
  5766. reject(record.arg);
  5767. } else {
  5768. var result = record.arg;
  5769. var value = result.value;
  5770. if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
  5771. return PromiseImpl.resolve(value.__await).then(function (value) {
  5772. invoke("next", value, resolve, reject);
  5773. }, function (err) {
  5774. invoke("throw", err, resolve, reject);
  5775. });
  5776. }
  5777. return PromiseImpl.resolve(value).then(function (unwrapped) {
  5778. // When a yielded Promise is resolved, its final value becomes
  5779. // the .value of the Promise<{value,done}> result for the
  5780. // current iteration.
  5781. result.value = unwrapped;
  5782. resolve(result);
  5783. }, function (error) {
  5784. // If a rejected Promise was yielded, throw the rejection back
  5785. // into the async generator function so it can be handled there.
  5786. return invoke("throw", error, resolve, reject);
  5787. });
  5788. }
  5789. }
  5790. var previousPromise;
  5791. function enqueue(method, arg) {
  5792. function callInvokeWithMethodAndArg() {
  5793. return new PromiseImpl(function (resolve, reject) {
  5794. invoke(method, arg, resolve, reject);
  5795. });
  5796. }
  5797. return previousPromise = // If enqueue has been called before, then we want to wait until
  5798. // all previous Promises have been resolved before calling invoke,
  5799. // so that results are always delivered in the correct order. If
  5800. // enqueue has not been called before, then it is important to
  5801. // call invoke immediately, without waiting on a callback to fire,
  5802. // so that the async generator function has the opportunity to do
  5803. // any necessary setup in a predictable way. This predictability
  5804. // is why the Promise constructor synchronously invokes its
  5805. // executor callback, and why async functions synchronously
  5806. // execute code before the first await. Since we implement simple
  5807. // async functions in terms of async generators, it is especially
  5808. // important to get this right, even though it requires care.
  5809. previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
  5810. // invocations of the iterator.
  5811. callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  5812. } // Define the unified helper method that is used to implement .next,
  5813. // .throw, and .return (see defineIteratorMethods).
  5814. this._invoke = enqueue;
  5815. }
  5816. defineIteratorMethods(AsyncIterator.prototype);
  5817. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  5818. return this;
  5819. };
  5820. exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
  5821. // AsyncIterator objects; they just return a Promise for the value of
  5822. // the final result produced by the iterator.
  5823. exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  5824. if (PromiseImpl === void 0) PromiseImpl = Promise;
  5825. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  5826. return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
  5827. : iter.next().then(function (result) {
  5828. return result.done ? result.value : iter.next();
  5829. });
  5830. };
  5831. function makeInvokeMethod(innerFn, self, context) {
  5832. var state = GenStateSuspendedStart;
  5833. return function invoke(method, arg) {
  5834. if (state === GenStateExecuting) {
  5835. throw new Error("Generator is already running");
  5836. }
  5837. if (state === GenStateCompleted) {
  5838. if (method === "throw") {
  5839. throw arg;
  5840. } // Be forgiving, per 25.3.3.3.3 of the spec:
  5841. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  5842. return doneResult();
  5843. }
  5844. context.method = method;
  5845. context.arg = arg;
  5846. while (true) {
  5847. var delegate = context.delegate;
  5848. if (delegate) {
  5849. var delegateResult = maybeInvokeDelegate(delegate, context);
  5850. if (delegateResult) {
  5851. if (delegateResult === ContinueSentinel) continue;
  5852. return delegateResult;
  5853. }
  5854. }
  5855. if (context.method === "next") {
  5856. // Setting context._sent for legacy support of Babel's
  5857. // function.sent implementation.
  5858. context.sent = context._sent = context.arg;
  5859. } else if (context.method === "throw") {
  5860. if (state === GenStateSuspendedStart) {
  5861. state = GenStateCompleted;
  5862. throw context.arg;
  5863. }
  5864. context.dispatchException(context.arg);
  5865. } else if (context.method === "return") {
  5866. context.abrupt("return", context.arg);
  5867. }
  5868. state = GenStateExecuting;
  5869. var record = tryCatch(innerFn, self, context);
  5870. if (record.type === "normal") {
  5871. // If an exception is thrown from innerFn, we leave state ===
  5872. // GenStateExecuting and loop back for another invocation.
  5873. state = context.done ? GenStateCompleted : GenStateSuspendedYield;
  5874. if (record.arg === ContinueSentinel) {
  5875. continue;
  5876. }
  5877. return {
  5878. value: record.arg,
  5879. done: context.done
  5880. };
  5881. } else if (record.type === "throw") {
  5882. state = GenStateCompleted; // Dispatch the exception by looping back around to the
  5883. // context.dispatchException(context.arg) call above.
  5884. context.method = "throw";
  5885. context.arg = record.arg;
  5886. }
  5887. }
  5888. };
  5889. } // Call delegate.iterator[context.method](context.arg) and handle the
  5890. // result, either by returning a { value, done } result from the
  5891. // delegate iterator, or by modifying context.method and context.arg,
  5892. // setting context.delegate to null, and returning the ContinueSentinel.
  5893. function maybeInvokeDelegate(delegate, context) {
  5894. var method = delegate.iterator[context.method];
  5895. if (method === undefined$1) {
  5896. // A .throw or .return when the delegate iterator has no .throw
  5897. // method always terminates the yield* loop.
  5898. context.delegate = null;
  5899. if (context.method === "throw") {
  5900. // Note: ["return"] must be used for ES3 parsing compatibility.
  5901. if (delegate.iterator["return"]) {
  5902. // If the delegate iterator has a return method, give it a
  5903. // chance to clean up.
  5904. context.method = "return";
  5905. context.arg = undefined$1;
  5906. maybeInvokeDelegate(delegate, context);
  5907. if (context.method === "throw") {
  5908. // If maybeInvokeDelegate(context) changed context.method from
  5909. // "return" to "throw", let that override the TypeError below.
  5910. return ContinueSentinel;
  5911. }
  5912. }
  5913. context.method = "throw";
  5914. context.arg = new TypeError("The iterator does not provide a 'throw' method");
  5915. }
  5916. return ContinueSentinel;
  5917. }
  5918. var record = tryCatch(method, delegate.iterator, context.arg);
  5919. if (record.type === "throw") {
  5920. context.method = "throw";
  5921. context.arg = record.arg;
  5922. context.delegate = null;
  5923. return ContinueSentinel;
  5924. }
  5925. var info = record.arg;
  5926. if (!info) {
  5927. context.method = "throw";
  5928. context.arg = new TypeError("iterator result is not an object");
  5929. context.delegate = null;
  5930. return ContinueSentinel;
  5931. }
  5932. if (info.done) {
  5933. // Assign the result of the finished delegate to the temporary
  5934. // variable specified by delegate.resultName (see delegateYield).
  5935. context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
  5936. context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
  5937. // exception, let the outer generator proceed normally. If
  5938. // context.method was "next", forget context.arg since it has been
  5939. // "consumed" by the delegate iterator. If context.method was
  5940. // "return", allow the original .return call to continue in the
  5941. // outer generator.
  5942. if (context.method !== "return") {
  5943. context.method = "next";
  5944. context.arg = undefined$1;
  5945. }
  5946. } else {
  5947. // Re-yield the result returned by the delegate method.
  5948. return info;
  5949. } // The delegate iterator is finished, so forget it and continue with
  5950. // the outer generator.
  5951. context.delegate = null;
  5952. return ContinueSentinel;
  5953. } // Define Generator.prototype.{next,throw,return} in terms of the
  5954. // unified ._invoke helper method.
  5955. defineIteratorMethods(Gp);
  5956. define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the
  5957. // @@iterator function is called on it. Some browsers' implementations of the
  5958. // iterator prototype chain incorrectly implement this, causing the Generator
  5959. // object to not be returned from this call. This ensures that doesn't happen.
  5960. // See https://github.com/facebook/regenerator/issues/274 for more details.
  5961. Gp[iteratorSymbol] = function () {
  5962. return this;
  5963. };
  5964. Gp.toString = function () {
  5965. return "[object Generator]";
  5966. };
  5967. function pushTryEntry(locs) {
  5968. var entry = {
  5969. tryLoc: locs[0]
  5970. };
  5971. if (1 in locs) {
  5972. entry.catchLoc = locs[1];
  5973. }
  5974. if (2 in locs) {
  5975. entry.finallyLoc = locs[2];
  5976. entry.afterLoc = locs[3];
  5977. }
  5978. this.tryEntries.push(entry);
  5979. }
  5980. function resetTryEntry(entry) {
  5981. var record = entry.completion || {};
  5982. record.type = "normal";
  5983. delete record.arg;
  5984. entry.completion = record;
  5985. }
  5986. function Context(tryLocsList) {
  5987. // The root entry object (effectively a try statement without a catch
  5988. // or a finally block) gives us a place to store values thrown from
  5989. // locations where there is no enclosing try statement.
  5990. this.tryEntries = [{
  5991. tryLoc: "root"
  5992. }];
  5993. tryLocsList.forEach(pushTryEntry, this);
  5994. this.reset(true);
  5995. }
  5996. exports.keys = function (object) {
  5997. var keys = [];
  5998. for (var key in object) {
  5999. keys.push(key);
  6000. }
  6001. keys.reverse(); // Rather than returning an object with a next method, we keep
  6002. // things simple and return the next function itself.
  6003. return function next() {
  6004. while (keys.length) {
  6005. var key = keys.pop();
  6006. if (key in object) {
  6007. next.value = key;
  6008. next.done = false;
  6009. return next;
  6010. }
  6011. } // To avoid creating an additional object, we just hang the .value
  6012. // and .done properties off the next function object itself. This
  6013. // also ensures that the minifier will not anonymize the function.
  6014. next.done = true;
  6015. return next;
  6016. };
  6017. };
  6018. function values(iterable) {
  6019. if (iterable) {
  6020. var iteratorMethod = iterable[iteratorSymbol];
  6021. if (iteratorMethod) {
  6022. return iteratorMethod.call(iterable);
  6023. }
  6024. if (typeof iterable.next === "function") {
  6025. return iterable;
  6026. }
  6027. if (!isNaN(iterable.length)) {
  6028. var i = -1,
  6029. next = function next() {
  6030. while (++i < iterable.length) {
  6031. if (hasOwn.call(iterable, i)) {
  6032. next.value = iterable[i];
  6033. next.done = false;
  6034. return next;
  6035. }
  6036. }
  6037. next.value = undefined$1;
  6038. next.done = true;
  6039. return next;
  6040. };
  6041. return next.next = next;
  6042. }
  6043. } // Return an iterator with no values.
  6044. return {
  6045. next: doneResult
  6046. };
  6047. }
  6048. exports.values = values;
  6049. function doneResult() {
  6050. return {
  6051. value: undefined$1,
  6052. done: true
  6053. };
  6054. }
  6055. Context.prototype = {
  6056. constructor: Context,
  6057. reset: function reset(skipTempReset) {
  6058. this.prev = 0;
  6059. this.next = 0; // Resetting context._sent for legacy support of Babel's
  6060. // function.sent implementation.
  6061. this.sent = this._sent = undefined$1;
  6062. this.done = false;
  6063. this.delegate = null;
  6064. this.method = "next";
  6065. this.arg = undefined$1;
  6066. this.tryEntries.forEach(resetTryEntry);
  6067. if (!skipTempReset) {
  6068. for (var name in this) {
  6069. // Not sure about the optimal order of these conditions:
  6070. if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
  6071. this[name] = undefined$1;
  6072. }
  6073. }
  6074. }
  6075. },
  6076. stop: function stop() {
  6077. this.done = true;
  6078. var rootEntry = this.tryEntries[0];
  6079. var rootRecord = rootEntry.completion;
  6080. if (rootRecord.type === "throw") {
  6081. throw rootRecord.arg;
  6082. }
  6083. return this.rval;
  6084. },
  6085. dispatchException: function dispatchException(exception) {
  6086. if (this.done) {
  6087. throw exception;
  6088. }
  6089. var context = this;
  6090. function handle(loc, caught) {
  6091. record.type = "throw";
  6092. record.arg = exception;
  6093. context.next = loc;
  6094. if (caught) {
  6095. // If the dispatched exception was caught by a catch block,
  6096. // then let that catch block handle the exception normally.
  6097. context.method = "next";
  6098. context.arg = undefined$1;
  6099. }
  6100. return !!caught;
  6101. }
  6102. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6103. var entry = this.tryEntries[i];
  6104. var record = entry.completion;
  6105. if (entry.tryLoc === "root") {
  6106. // Exception thrown outside of any try block that could handle
  6107. // it, so set the completion value of the entire function to
  6108. // throw the exception.
  6109. return handle("end");
  6110. }
  6111. if (entry.tryLoc <= this.prev) {
  6112. var hasCatch = hasOwn.call(entry, "catchLoc");
  6113. var hasFinally = hasOwn.call(entry, "finallyLoc");
  6114. if (hasCatch && hasFinally) {
  6115. if (this.prev < entry.catchLoc) {
  6116. return handle(entry.catchLoc, true);
  6117. } else if (this.prev < entry.finallyLoc) {
  6118. return handle(entry.finallyLoc);
  6119. }
  6120. } else if (hasCatch) {
  6121. if (this.prev < entry.catchLoc) {
  6122. return handle(entry.catchLoc, true);
  6123. }
  6124. } else if (hasFinally) {
  6125. if (this.prev < entry.finallyLoc) {
  6126. return handle(entry.finallyLoc);
  6127. }
  6128. } else {
  6129. throw new Error("try statement without catch or finally");
  6130. }
  6131. }
  6132. }
  6133. },
  6134. abrupt: function abrupt(type, arg) {
  6135. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6136. var entry = this.tryEntries[i];
  6137. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  6138. var finallyEntry = entry;
  6139. break;
  6140. }
  6141. }
  6142. if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
  6143. // Ignore the finally entry if control is not jumping to a
  6144. // location outside the try/catch block.
  6145. finallyEntry = null;
  6146. }
  6147. var record = finallyEntry ? finallyEntry.completion : {};
  6148. record.type = type;
  6149. record.arg = arg;
  6150. if (finallyEntry) {
  6151. this.method = "next";
  6152. this.next = finallyEntry.finallyLoc;
  6153. return ContinueSentinel;
  6154. }
  6155. return this.complete(record);
  6156. },
  6157. complete: function complete(record, afterLoc) {
  6158. if (record.type === "throw") {
  6159. throw record.arg;
  6160. }
  6161. if (record.type === "break" || record.type === "continue") {
  6162. this.next = record.arg;
  6163. } else if (record.type === "return") {
  6164. this.rval = this.arg = record.arg;
  6165. this.method = "return";
  6166. this.next = "end";
  6167. } else if (record.type === "normal" && afterLoc) {
  6168. this.next = afterLoc;
  6169. }
  6170. return ContinueSentinel;
  6171. },
  6172. finish: function finish(finallyLoc) {
  6173. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6174. var entry = this.tryEntries[i];
  6175. if (entry.finallyLoc === finallyLoc) {
  6176. this.complete(entry.completion, entry.afterLoc);
  6177. resetTryEntry(entry);
  6178. return ContinueSentinel;
  6179. }
  6180. }
  6181. },
  6182. "catch": function _catch(tryLoc) {
  6183. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6184. var entry = this.tryEntries[i];
  6185. if (entry.tryLoc === tryLoc) {
  6186. var record = entry.completion;
  6187. if (record.type === "throw") {
  6188. var thrown = record.arg;
  6189. resetTryEntry(entry);
  6190. }
  6191. return thrown;
  6192. }
  6193. } // The context.catch method must only be called with a location
  6194. // argument that corresponds to a known catch block.
  6195. throw new Error("illegal catch attempt");
  6196. },
  6197. delegateYield: function delegateYield(iterable, resultName, nextLoc) {
  6198. this.delegate = {
  6199. iterator: values(iterable),
  6200. resultName: resultName,
  6201. nextLoc: nextLoc
  6202. };
  6203. if (this.method === "next") {
  6204. // Deliberately forget the last sent value so that we don't
  6205. // accidentally pass it on to the delegate.
  6206. this.arg = undefined$1;
  6207. }
  6208. return ContinueSentinel;
  6209. }
  6210. }; // Regardless of whether this script is executing as a CommonJS module
  6211. // or not, return the runtime object so that we can declare the variable
  6212. // regeneratorRuntime in the outer scope, which allows this module to be
  6213. // injected easily by `bin/regenerator --include-runtime script.js`.
  6214. return exports;
  6215. }( // If this script is executing as a CommonJS module, use module.exports
  6216. // as the regeneratorRuntime namespace. Otherwise create a new empty
  6217. // object. Either way, the resulting object will be used to initialize
  6218. // the regeneratorRuntime variable at the top of this file.
  6219. typeof module === "object" ? module.exports : {});
  6220. try {
  6221. regeneratorRuntime = runtime;
  6222. } catch (accidentalStrictMode) {
  6223. // This module should not be running in strict mode, so the above
  6224. // assignment should always work unless something is misconfigured. Just
  6225. // in case runtime.js accidentally runs in strict mode, we can escape
  6226. // strict mode using a global Function call. This could conceivably fail
  6227. // if a Content Security Policy forbids using Function, but in that case
  6228. // the proper solution is to fix the accidental strict mode problem. If
  6229. // you've misconfigured your bundler to force strict mode and applied a
  6230. // CSP to forbid Function, and you're not willing to fix either of those
  6231. // problems, please detail your unique predicament in a GitHub issue.
  6232. Function("r", "regeneratorRuntime = r")(runtime);
  6233. }
  6234. var REVISION = '125';
  6235. var MOUSE = {
  6236. LEFT: 0,
  6237. MIDDLE: 1,
  6238. RIGHT: 2,
  6239. ROTATE: 0,
  6240. DOLLY: 1,
  6241. PAN: 2
  6242. };
  6243. var TOUCH = {
  6244. ROTATE: 0,
  6245. PAN: 1,
  6246. DOLLY_PAN: 2,
  6247. DOLLY_ROTATE: 3
  6248. };
  6249. var CullFaceNone = 0;
  6250. var CullFaceBack = 1;
  6251. var CullFaceFront = 2;
  6252. var CullFaceFrontBack = 3;
  6253. var BasicShadowMap = 0;
  6254. var PCFShadowMap = 1;
  6255. var PCFSoftShadowMap = 2;
  6256. var VSMShadowMap = 3;
  6257. var FrontSide = 0;
  6258. var BackSide = 1;
  6259. var DoubleSide = 2;
  6260. var FlatShading = 1;
  6261. var SmoothShading = 2;
  6262. var NoBlending = 0;
  6263. var NormalBlending = 1;
  6264. var AdditiveBlending = 2;
  6265. var SubtractiveBlending = 3;
  6266. var MultiplyBlending = 4;
  6267. var CustomBlending = 5;
  6268. var AddEquation = 100;
  6269. var SubtractEquation = 101;
  6270. var ReverseSubtractEquation = 102;
  6271. var MinEquation = 103;
  6272. var MaxEquation = 104;
  6273. var ZeroFactor = 200;
  6274. var OneFactor = 201;
  6275. var SrcColorFactor = 202;
  6276. var OneMinusSrcColorFactor = 203;
  6277. var SrcAlphaFactor = 204;
  6278. var OneMinusSrcAlphaFactor = 205;
  6279. var DstAlphaFactor = 206;
  6280. var OneMinusDstAlphaFactor = 207;
  6281. var DstColorFactor = 208;
  6282. var OneMinusDstColorFactor = 209;
  6283. var SrcAlphaSaturateFactor = 210;
  6284. var NeverDepth = 0;
  6285. var AlwaysDepth = 1;
  6286. var LessDepth = 2;
  6287. var LessEqualDepth = 3;
  6288. var EqualDepth = 4;
  6289. var GreaterEqualDepth = 5;
  6290. var GreaterDepth = 6;
  6291. var NotEqualDepth = 7;
  6292. var MultiplyOperation = 0;
  6293. var MixOperation = 1;
  6294. var AddOperation = 2;
  6295. var NoToneMapping = 0;
  6296. var LinearToneMapping = 1;
  6297. var ReinhardToneMapping = 2;
  6298. var CineonToneMapping = 3;
  6299. var ACESFilmicToneMapping = 4;
  6300. var CustomToneMapping = 5;
  6301. var UVMapping = 300;
  6302. var CubeReflectionMapping = 301;
  6303. var CubeRefractionMapping = 302;
  6304. var EquirectangularReflectionMapping = 303;
  6305. var EquirectangularRefractionMapping = 304;
  6306. var CubeUVReflectionMapping = 306;
  6307. var CubeUVRefractionMapping = 307;
  6308. var RepeatWrapping = 1000;
  6309. var ClampToEdgeWrapping = 1001;
  6310. var MirroredRepeatWrapping = 1002;
  6311. var NearestFilter = 1003;
  6312. var NearestMipmapNearestFilter = 1004;
  6313. var NearestMipMapNearestFilter = 1004;
  6314. var NearestMipmapLinearFilter = 1005;
  6315. var NearestMipMapLinearFilter = 1005;
  6316. var LinearFilter = 1006;
  6317. var LinearMipmapNearestFilter = 1007;
  6318. var LinearMipMapNearestFilter = 1007;
  6319. var LinearMipmapLinearFilter = 1008;
  6320. var LinearMipMapLinearFilter = 1008;
  6321. var UnsignedByteType = 1009;
  6322. var ByteType = 1010;
  6323. var ShortType = 1011;
  6324. var UnsignedShortType = 1012;
  6325. var IntType = 1013;
  6326. var UnsignedIntType = 1014;
  6327. var FloatType = 1015;
  6328. var HalfFloatType = 1016;
  6329. var UnsignedShort4444Type = 1017;
  6330. var UnsignedShort5551Type = 1018;
  6331. var UnsignedShort565Type = 1019;
  6332. var UnsignedInt248Type = 1020;
  6333. var AlphaFormat = 1021;
  6334. var RGBFormat = 1022;
  6335. var RGBAFormat = 1023;
  6336. var LuminanceFormat = 1024;
  6337. var LuminanceAlphaFormat = 1025;
  6338. var RGBEFormat = RGBAFormat;
  6339. var DepthFormat = 1026;
  6340. var DepthStencilFormat = 1027;
  6341. var RedFormat = 1028;
  6342. var RedIntegerFormat = 1029;
  6343. var RGFormat = 1030;
  6344. var RGIntegerFormat = 1031;
  6345. var RGBIntegerFormat = 1032;
  6346. var RGBAIntegerFormat = 1033;
  6347. var RGB_S3TC_DXT1_Format = 33776;
  6348. var RGBA_S3TC_DXT1_Format = 33777;
  6349. var RGBA_S3TC_DXT3_Format = 33778;
  6350. var RGBA_S3TC_DXT5_Format = 33779;
  6351. var RGB_PVRTC_4BPPV1_Format = 35840;
  6352. var RGB_PVRTC_2BPPV1_Format = 35841;
  6353. var RGBA_PVRTC_4BPPV1_Format = 35842;
  6354. var RGBA_PVRTC_2BPPV1_Format = 35843;
  6355. var RGB_ETC1_Format = 36196;
  6356. var RGB_ETC2_Format = 37492;
  6357. var RGBA_ETC2_EAC_Format = 37496;
  6358. var RGBA_ASTC_4x4_Format = 37808;
  6359. var RGBA_ASTC_5x4_Format = 37809;
  6360. var RGBA_ASTC_5x5_Format = 37810;
  6361. var RGBA_ASTC_6x5_Format = 37811;
  6362. var RGBA_ASTC_6x6_Format = 37812;
  6363. var RGBA_ASTC_8x5_Format = 37813;
  6364. var RGBA_ASTC_8x6_Format = 37814;
  6365. var RGBA_ASTC_8x8_Format = 37815;
  6366. var RGBA_ASTC_10x5_Format = 37816;
  6367. var RGBA_ASTC_10x6_Format = 37817;
  6368. var RGBA_ASTC_10x8_Format = 37818;
  6369. var RGBA_ASTC_10x10_Format = 37819;
  6370. var RGBA_ASTC_12x10_Format = 37820;
  6371. var RGBA_ASTC_12x12_Format = 37821;
  6372. var RGBA_BPTC_Format = 36492;
  6373. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  6374. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  6375. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  6376. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  6377. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  6378. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  6379. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  6380. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  6381. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  6382. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  6383. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  6384. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  6385. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  6386. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  6387. var LoopOnce = 2200;
  6388. var LoopRepeat = 2201;
  6389. var LoopPingPong = 2202;
  6390. var InterpolateDiscrete = 2300;
  6391. var InterpolateLinear = 2301;
  6392. var InterpolateSmooth = 2302;
  6393. var ZeroCurvatureEnding = 2400;
  6394. var ZeroSlopeEnding = 2401;
  6395. var WrapAroundEnding = 2402;
  6396. var NormalAnimationBlendMode = 2500;
  6397. var AdditiveAnimationBlendMode = 2501;
  6398. var TrianglesDrawMode = 0;
  6399. var TriangleStripDrawMode = 1;
  6400. var TriangleFanDrawMode = 2;
  6401. var LinearEncoding = 3000;
  6402. var sRGBEncoding = 3001;
  6403. var GammaEncoding = 3007;
  6404. var RGBEEncoding = 3002;
  6405. var LogLuvEncoding = 3003;
  6406. var RGBM7Encoding = 3004;
  6407. var RGBM16Encoding = 3005;
  6408. var RGBDEncoding = 3006;
  6409. var BasicDepthPacking = 3200;
  6410. var RGBADepthPacking = 3201;
  6411. var TangentSpaceNormalMap = 0;
  6412. var ObjectSpaceNormalMap = 1;
  6413. var ZeroStencilOp = 0;
  6414. var KeepStencilOp = 7680;
  6415. var ReplaceStencilOp = 7681;
  6416. var IncrementStencilOp = 7682;
  6417. var DecrementStencilOp = 7683;
  6418. var IncrementWrapStencilOp = 34055;
  6419. var DecrementWrapStencilOp = 34056;
  6420. var InvertStencilOp = 5386;
  6421. var NeverStencilFunc = 512;
  6422. var LessStencilFunc = 513;
  6423. var EqualStencilFunc = 514;
  6424. var LessEqualStencilFunc = 515;
  6425. var GreaterStencilFunc = 516;
  6426. var NotEqualStencilFunc = 517;
  6427. var GreaterEqualStencilFunc = 518;
  6428. var AlwaysStencilFunc = 519;
  6429. var StaticDrawUsage = 35044;
  6430. var DynamicDrawUsage = 35048;
  6431. var StreamDrawUsage = 35040;
  6432. var StaticReadUsage = 35045;
  6433. var DynamicReadUsage = 35049;
  6434. var StreamReadUsage = 35041;
  6435. var StaticCopyUsage = 35046;
  6436. var DynamicCopyUsage = 35050;
  6437. var StreamCopyUsage = 35042;
  6438. var GLSL1 = '100';
  6439. var GLSL3 = '300 es';
  6440. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  6441. try {
  6442. var info = gen[key](arg);
  6443. var value = info.value;
  6444. } catch (error) {
  6445. reject(error);
  6446. return;
  6447. }
  6448. if (info.done) {
  6449. resolve(value);
  6450. } else {
  6451. Promise.resolve(value).then(_next, _throw);
  6452. }
  6453. }
  6454. function _asyncToGenerator(fn) {
  6455. return function () {
  6456. var self = this,
  6457. args = arguments;
  6458. return new Promise(function (resolve, reject) {
  6459. var gen = fn.apply(self, args);
  6460. function _next(value) {
  6461. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  6462. }
  6463. function _throw(err) {
  6464. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  6465. }
  6466. _next(undefined);
  6467. });
  6468. };
  6469. }
  6470. function _defineProperties(target, props) {
  6471. for (var i = 0; i < props.length; i++) {
  6472. var descriptor = props[i];
  6473. descriptor.enumerable = descriptor.enumerable || false;
  6474. descriptor.configurable = true;
  6475. if ("value" in descriptor) descriptor.writable = true;
  6476. Object.defineProperty(target, descriptor.key, descriptor);
  6477. }
  6478. }
  6479. function _createClass(Constructor, protoProps, staticProps) {
  6480. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  6481. if (staticProps) _defineProperties(Constructor, staticProps);
  6482. return Constructor;
  6483. }
  6484. function _inheritsLoose(subClass, superClass) {
  6485. subClass.prototype = Object.create(superClass.prototype);
  6486. subClass.prototype.constructor = subClass;
  6487. subClass.__proto__ = superClass;
  6488. }
  6489. function _assertThisInitialized(self) {
  6490. if (self === void 0) {
  6491. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  6492. }
  6493. return self;
  6494. }
  6495. function _unsupportedIterableToArray(o, minLen) {
  6496. if (!o) return;
  6497. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  6498. var n = Object.prototype.toString.call(o).slice(8, -1);
  6499. if (n === "Object" && o.constructor) n = o.constructor.name;
  6500. if (n === "Map" || n === "Set") return Array.from(o);
  6501. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  6502. }
  6503. function _arrayLikeToArray(arr, len) {
  6504. if (len == null || len > arr.length) len = arr.length;
  6505. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  6506. return arr2;
  6507. }
  6508. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  6509. var it;
  6510. if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
  6511. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  6512. if (it) o = it;
  6513. var i = 0;
  6514. return function () {
  6515. if (i >= o.length) return {
  6516. done: true
  6517. };
  6518. return {
  6519. done: false,
  6520. value: o[i++]
  6521. };
  6522. };
  6523. }
  6524. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  6525. }
  6526. it = o[Symbol.iterator]();
  6527. return it.next.bind(it);
  6528. }
  6529. /**
  6530. * https://github.com/mrdoob/eventdispatcher.js/
  6531. */
  6532. function EventDispatcher() {}
  6533. Object.assign(EventDispatcher.prototype, {
  6534. addEventListener: function addEventListener(type, listener) {
  6535. if (this._listeners === undefined) this._listeners = {};
  6536. var listeners = this._listeners;
  6537. if (listeners[type] === undefined) {
  6538. listeners[type] = [];
  6539. }
  6540. if (listeners[type].indexOf(listener) === -1) {
  6541. listeners[type].push(listener);
  6542. }
  6543. },
  6544. hasEventListener: function hasEventListener(type, listener) {
  6545. if (this._listeners === undefined) return false;
  6546. var listeners = this._listeners;
  6547. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  6548. },
  6549. removeEventListener: function removeEventListener(type, listener) {
  6550. if (this._listeners === undefined) return;
  6551. var listeners = this._listeners;
  6552. var listenerArray = listeners[type];
  6553. if (listenerArray !== undefined) {
  6554. var index = listenerArray.indexOf(listener);
  6555. if (index !== -1) {
  6556. listenerArray.splice(index, 1);
  6557. }
  6558. }
  6559. },
  6560. dispatchEvent: function dispatchEvent(event) {
  6561. if (this._listeners === undefined) return;
  6562. var listeners = this._listeners;
  6563. var listenerArray = listeners[event.type];
  6564. if (listenerArray !== undefined) {
  6565. event.target = this; // Make a copy, in case listeners are removed while iterating.
  6566. var array = listenerArray.slice(0);
  6567. for (var i = 0, l = array.length; i < l; i++) {
  6568. array[i].call(this, event);
  6569. }
  6570. }
  6571. }
  6572. });
  6573. var _lut = [];
  6574. for (var i = 0; i < 256; i++) {
  6575. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  6576. }
  6577. var _seed = 1234567;
  6578. var MathUtils = {
  6579. DEG2RAD: Math.PI / 180,
  6580. RAD2DEG: 180 / Math.PI,
  6581. generateUUID: function generateUUID() {
  6582. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  6583. var d0 = Math.random() * 0xffffffff | 0;
  6584. var d1 = Math.random() * 0xffffffff | 0;
  6585. var d2 = Math.random() * 0xffffffff | 0;
  6586. var d3 = Math.random() * 0xffffffff | 0;
  6587. 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.
  6588. return uuid.toUpperCase();
  6589. },
  6590. clamp: function clamp(value, min, max) {
  6591. return Math.max(min, Math.min(max, value));
  6592. },
  6593. // compute euclidian modulo of m % n
  6594. // https://en.wikipedia.org/wiki/Modulo_operation
  6595. euclideanModulo: function euclideanModulo(n, m) {
  6596. return (n % m + m) % m;
  6597. },
  6598. // Linear mapping from range <a1, a2> to range <b1, b2>
  6599. mapLinear: function mapLinear(x, a1, a2, b1, b2) {
  6600. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  6601. },
  6602. // https://en.wikipedia.org/wiki/Linear_interpolation
  6603. lerp: function lerp(x, y, t) {
  6604. return (1 - t) * x + t * y;
  6605. },
  6606. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  6607. damp: function damp(x, y, lambda, dt) {
  6608. return MathUtils.lerp(x, y, 1 - Math.exp(-lambda * dt));
  6609. },
  6610. // https://www.desmos.com/calculator/vcsjnyz7x4
  6611. pingpong: function pingpong(x, length) {
  6612. if (length === void 0) {
  6613. length = 1;
  6614. }
  6615. return length - Math.abs(MathUtils.euclideanModulo(x, length * 2) - length);
  6616. },
  6617. // http://en.wikipedia.org/wiki/Smoothstep
  6618. smoothstep: function smoothstep(x, min, max) {
  6619. if (x <= min) return 0;
  6620. if (x >= max) return 1;
  6621. x = (x - min) / (max - min);
  6622. return x * x * (3 - 2 * x);
  6623. },
  6624. smootherstep: function smootherstep(x, min, max) {
  6625. if (x <= min) return 0;
  6626. if (x >= max) return 1;
  6627. x = (x - min) / (max - min);
  6628. return x * x * x * (x * (x * 6 - 15) + 10);
  6629. },
  6630. // Random integer from <low, high> interval
  6631. randInt: function randInt(low, high) {
  6632. return low + Math.floor(Math.random() * (high - low + 1));
  6633. },
  6634. // Random float from <low, high> interval
  6635. randFloat: function randFloat(low, high) {
  6636. return low + Math.random() * (high - low);
  6637. },
  6638. // Random float from <-range/2, range/2> interval
  6639. randFloatSpread: function randFloatSpread(range) {
  6640. return range * (0.5 - Math.random());
  6641. },
  6642. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  6643. seededRandom: function seededRandom(s) {
  6644. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  6645. _seed = _seed * 16807 % 2147483647;
  6646. return (_seed - 1) / 2147483646;
  6647. },
  6648. degToRad: function degToRad(degrees) {
  6649. return degrees * MathUtils.DEG2RAD;
  6650. },
  6651. radToDeg: function radToDeg(radians) {
  6652. return radians * MathUtils.RAD2DEG;
  6653. },
  6654. isPowerOfTwo: function isPowerOfTwo(value) {
  6655. return (value & value - 1) === 0 && value !== 0;
  6656. },
  6657. ceilPowerOfTwo: function ceilPowerOfTwo(value) {
  6658. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  6659. },
  6660. floorPowerOfTwo: function floorPowerOfTwo(value) {
  6661. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  6662. },
  6663. setQuaternionFromProperEuler: function setQuaternionFromProperEuler(q, a, b, c, order) {
  6664. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  6665. // rotations are applied to the axes in the order specified by 'order'
  6666. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  6667. // angles are in radians
  6668. var cos = Math.cos;
  6669. var sin = Math.sin;
  6670. var c2 = cos(b / 2);
  6671. var s2 = sin(b / 2);
  6672. var c13 = cos((a + c) / 2);
  6673. var s13 = sin((a + c) / 2);
  6674. var c1_3 = cos((a - c) / 2);
  6675. var s1_3 = sin((a - c) / 2);
  6676. var c3_1 = cos((c - a) / 2);
  6677. var s3_1 = sin((c - a) / 2);
  6678. switch (order) {
  6679. case 'XYX':
  6680. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  6681. break;
  6682. case 'YZY':
  6683. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  6684. break;
  6685. case 'ZXZ':
  6686. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  6687. break;
  6688. case 'XZX':
  6689. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  6690. break;
  6691. case 'YXY':
  6692. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  6693. break;
  6694. case 'ZYZ':
  6695. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  6696. break;
  6697. default:
  6698. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  6699. }
  6700. }
  6701. };
  6702. var Vector2 = /*#__PURE__*/function () {
  6703. function Vector2(x, y) {
  6704. if (x === void 0) {
  6705. x = 0;
  6706. }
  6707. if (y === void 0) {
  6708. y = 0;
  6709. }
  6710. Object.defineProperty(this, 'isVector2', {
  6711. value: true
  6712. });
  6713. this.x = x;
  6714. this.y = y;
  6715. }
  6716. var _proto = Vector2.prototype;
  6717. _proto.set = function set(x, y) {
  6718. this.x = x;
  6719. this.y = y;
  6720. return this;
  6721. };
  6722. _proto.setScalar = function setScalar(scalar) {
  6723. this.x = scalar;
  6724. this.y = scalar;
  6725. return this;
  6726. };
  6727. _proto.setX = function setX(x) {
  6728. this.x = x;
  6729. return this;
  6730. };
  6731. _proto.setY = function setY(y) {
  6732. this.y = y;
  6733. return this;
  6734. };
  6735. _proto.setComponent = function setComponent(index, value) {
  6736. switch (index) {
  6737. case 0:
  6738. this.x = value;
  6739. break;
  6740. case 1:
  6741. this.y = value;
  6742. break;
  6743. default:
  6744. throw new Error('index is out of range: ' + index);
  6745. }
  6746. return this;
  6747. };
  6748. _proto.getComponent = function getComponent(index) {
  6749. switch (index) {
  6750. case 0:
  6751. return this.x;
  6752. case 1:
  6753. return this.y;
  6754. default:
  6755. throw new Error('index is out of range: ' + index);
  6756. }
  6757. };
  6758. _proto.clone = function clone() {
  6759. return new this.constructor(this.x, this.y);
  6760. };
  6761. _proto.copy = function copy(v) {
  6762. this.x = v.x;
  6763. this.y = v.y;
  6764. return this;
  6765. };
  6766. _proto.add = function add(v, w) {
  6767. if (w !== undefined) {
  6768. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6769. return this.addVectors(v, w);
  6770. }
  6771. this.x += v.x;
  6772. this.y += v.y;
  6773. return this;
  6774. };
  6775. _proto.addScalar = function addScalar(s) {
  6776. this.x += s;
  6777. this.y += s;
  6778. return this;
  6779. };
  6780. _proto.addVectors = function addVectors(a, b) {
  6781. this.x = a.x + b.x;
  6782. this.y = a.y + b.y;
  6783. return this;
  6784. };
  6785. _proto.addScaledVector = function addScaledVector(v, s) {
  6786. this.x += v.x * s;
  6787. this.y += v.y * s;
  6788. return this;
  6789. };
  6790. _proto.sub = function sub(v, w) {
  6791. if (w !== undefined) {
  6792. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6793. return this.subVectors(v, w);
  6794. }
  6795. this.x -= v.x;
  6796. this.y -= v.y;
  6797. return this;
  6798. };
  6799. _proto.subScalar = function subScalar(s) {
  6800. this.x -= s;
  6801. this.y -= s;
  6802. return this;
  6803. };
  6804. _proto.subVectors = function subVectors(a, b) {
  6805. this.x = a.x - b.x;
  6806. this.y = a.y - b.y;
  6807. return this;
  6808. };
  6809. _proto.multiply = function multiply(v) {
  6810. this.x *= v.x;
  6811. this.y *= v.y;
  6812. return this;
  6813. };
  6814. _proto.multiplyScalar = function multiplyScalar(scalar) {
  6815. this.x *= scalar;
  6816. this.y *= scalar;
  6817. return this;
  6818. };
  6819. _proto.divide = function divide(v) {
  6820. this.x /= v.x;
  6821. this.y /= v.y;
  6822. return this;
  6823. };
  6824. _proto.divideScalar = function divideScalar(scalar) {
  6825. return this.multiplyScalar(1 / scalar);
  6826. };
  6827. _proto.applyMatrix3 = function applyMatrix3(m) {
  6828. var x = this.x,
  6829. y = this.y;
  6830. var e = m.elements;
  6831. this.x = e[0] * x + e[3] * y + e[6];
  6832. this.y = e[1] * x + e[4] * y + e[7];
  6833. return this;
  6834. };
  6835. _proto.min = function min(v) {
  6836. this.x = Math.min(this.x, v.x);
  6837. this.y = Math.min(this.y, v.y);
  6838. return this;
  6839. };
  6840. _proto.max = function max(v) {
  6841. this.x = Math.max(this.x, v.x);
  6842. this.y = Math.max(this.y, v.y);
  6843. return this;
  6844. };
  6845. _proto.clamp = function clamp(min, max) {
  6846. // assumes min < max, componentwise
  6847. this.x = Math.max(min.x, Math.min(max.x, this.x));
  6848. this.y = Math.max(min.y, Math.min(max.y, this.y));
  6849. return this;
  6850. };
  6851. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  6852. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  6853. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  6854. return this;
  6855. };
  6856. _proto.clampLength = function clampLength(min, max) {
  6857. var length = this.length();
  6858. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  6859. };
  6860. _proto.floor = function floor() {
  6861. this.x = Math.floor(this.x);
  6862. this.y = Math.floor(this.y);
  6863. return this;
  6864. };
  6865. _proto.ceil = function ceil() {
  6866. this.x = Math.ceil(this.x);
  6867. this.y = Math.ceil(this.y);
  6868. return this;
  6869. };
  6870. _proto.round = function round() {
  6871. this.x = Math.round(this.x);
  6872. this.y = Math.round(this.y);
  6873. return this;
  6874. };
  6875. _proto.roundToZero = function roundToZero() {
  6876. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  6877. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  6878. return this;
  6879. };
  6880. _proto.negate = function negate() {
  6881. this.x = -this.x;
  6882. this.y = -this.y;
  6883. return this;
  6884. };
  6885. _proto.dot = function dot(v) {
  6886. return this.x * v.x + this.y * v.y;
  6887. };
  6888. _proto.cross = function cross(v) {
  6889. return this.x * v.y - this.y * v.x;
  6890. };
  6891. _proto.lengthSq = function lengthSq() {
  6892. return this.x * this.x + this.y * this.y;
  6893. };
  6894. _proto.length = function length() {
  6895. return Math.sqrt(this.x * this.x + this.y * this.y);
  6896. };
  6897. _proto.manhattanLength = function manhattanLength() {
  6898. return Math.abs(this.x) + Math.abs(this.y);
  6899. };
  6900. _proto.normalize = function normalize() {
  6901. return this.divideScalar(this.length() || 1);
  6902. };
  6903. _proto.angle = function angle() {
  6904. // computes the angle in radians with respect to the positive x-axis
  6905. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  6906. return angle;
  6907. };
  6908. _proto.distanceTo = function distanceTo(v) {
  6909. return Math.sqrt(this.distanceToSquared(v));
  6910. };
  6911. _proto.distanceToSquared = function distanceToSquared(v) {
  6912. var dx = this.x - v.x,
  6913. dy = this.y - v.y;
  6914. return dx * dx + dy * dy;
  6915. };
  6916. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  6917. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  6918. };
  6919. _proto.setLength = function setLength(length) {
  6920. return this.normalize().multiplyScalar(length);
  6921. };
  6922. _proto.lerp = function lerp(v, alpha) {
  6923. this.x += (v.x - this.x) * alpha;
  6924. this.y += (v.y - this.y) * alpha;
  6925. return this;
  6926. };
  6927. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  6928. this.x = v1.x + (v2.x - v1.x) * alpha;
  6929. this.y = v1.y + (v2.y - v1.y) * alpha;
  6930. return this;
  6931. };
  6932. _proto.equals = function equals(v) {
  6933. return v.x === this.x && v.y === this.y;
  6934. };
  6935. _proto.fromArray = function fromArray(array, offset) {
  6936. if (offset === void 0) {
  6937. offset = 0;
  6938. }
  6939. this.x = array[offset];
  6940. this.y = array[offset + 1];
  6941. return this;
  6942. };
  6943. _proto.toArray = function toArray(array, offset) {
  6944. if (array === void 0) {
  6945. array = [];
  6946. }
  6947. if (offset === void 0) {
  6948. offset = 0;
  6949. }
  6950. array[offset] = this.x;
  6951. array[offset + 1] = this.y;
  6952. return array;
  6953. };
  6954. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  6955. if (offset !== undefined) {
  6956. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  6957. }
  6958. this.x = attribute.getX(index);
  6959. this.y = attribute.getY(index);
  6960. return this;
  6961. };
  6962. _proto.rotateAround = function rotateAround(center, angle) {
  6963. var c = Math.cos(angle),
  6964. s = Math.sin(angle);
  6965. var x = this.x - center.x;
  6966. var y = this.y - center.y;
  6967. this.x = x * c - y * s + center.x;
  6968. this.y = x * s + y * c + center.y;
  6969. return this;
  6970. };
  6971. _proto.random = function random() {
  6972. this.x = Math.random();
  6973. this.y = Math.random();
  6974. return this;
  6975. };
  6976. _createClass(Vector2, [{
  6977. key: "width",
  6978. get: function get() {
  6979. return this.x;
  6980. },
  6981. set: function set(value) {
  6982. this.x = value;
  6983. }
  6984. }, {
  6985. key: "height",
  6986. get: function get() {
  6987. return this.y;
  6988. },
  6989. set: function set(value) {
  6990. this.y = value;
  6991. }
  6992. }]);
  6993. return Vector2;
  6994. }();
  6995. var Matrix3 = /*#__PURE__*/function () {
  6996. function Matrix3() {
  6997. Object.defineProperty(this, 'isMatrix3', {
  6998. value: true
  6999. });
  7000. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  7001. if (arguments.length > 0) {
  7002. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  7003. }
  7004. }
  7005. var _proto = Matrix3.prototype;
  7006. _proto.set = function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  7007. var te = this.elements;
  7008. te[0] = n11;
  7009. te[1] = n21;
  7010. te[2] = n31;
  7011. te[3] = n12;
  7012. te[4] = n22;
  7013. te[5] = n32;
  7014. te[6] = n13;
  7015. te[7] = n23;
  7016. te[8] = n33;
  7017. return this;
  7018. };
  7019. _proto.identity = function identity() {
  7020. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  7021. return this;
  7022. };
  7023. _proto.clone = function clone() {
  7024. return new this.constructor().fromArray(this.elements);
  7025. };
  7026. _proto.copy = function copy(m) {
  7027. var te = this.elements;
  7028. var me = m.elements;
  7029. te[0] = me[0];
  7030. te[1] = me[1];
  7031. te[2] = me[2];
  7032. te[3] = me[3];
  7033. te[4] = me[4];
  7034. te[5] = me[5];
  7035. te[6] = me[6];
  7036. te[7] = me[7];
  7037. te[8] = me[8];
  7038. return this;
  7039. };
  7040. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  7041. xAxis.setFromMatrix3Column(this, 0);
  7042. yAxis.setFromMatrix3Column(this, 1);
  7043. zAxis.setFromMatrix3Column(this, 2);
  7044. return this;
  7045. };
  7046. _proto.setFromMatrix4 = function setFromMatrix4(m) {
  7047. var me = m.elements;
  7048. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  7049. return this;
  7050. };
  7051. _proto.multiply = function multiply(m) {
  7052. return this.multiplyMatrices(this, m);
  7053. };
  7054. _proto.premultiply = function premultiply(m) {
  7055. return this.multiplyMatrices(m, this);
  7056. };
  7057. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  7058. var ae = a.elements;
  7059. var be = b.elements;
  7060. var te = this.elements;
  7061. var a11 = ae[0],
  7062. a12 = ae[3],
  7063. a13 = ae[6];
  7064. var a21 = ae[1],
  7065. a22 = ae[4],
  7066. a23 = ae[7];
  7067. var a31 = ae[2],
  7068. a32 = ae[5],
  7069. a33 = ae[8];
  7070. var b11 = be[0],
  7071. b12 = be[3],
  7072. b13 = be[6];
  7073. var b21 = be[1],
  7074. b22 = be[4],
  7075. b23 = be[7];
  7076. var b31 = be[2],
  7077. b32 = be[5],
  7078. b33 = be[8];
  7079. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  7080. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  7081. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  7082. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  7083. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  7084. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  7085. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  7086. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  7087. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  7088. return this;
  7089. };
  7090. _proto.multiplyScalar = function multiplyScalar(s) {
  7091. var te = this.elements;
  7092. te[0] *= s;
  7093. te[3] *= s;
  7094. te[6] *= s;
  7095. te[1] *= s;
  7096. te[4] *= s;
  7097. te[7] *= s;
  7098. te[2] *= s;
  7099. te[5] *= s;
  7100. te[8] *= s;
  7101. return this;
  7102. };
  7103. _proto.determinant = function determinant() {
  7104. var te = this.elements;
  7105. var a = te[0],
  7106. b = te[1],
  7107. c = te[2],
  7108. d = te[3],
  7109. e = te[4],
  7110. f = te[5],
  7111. g = te[6],
  7112. h = te[7],
  7113. i = te[8];
  7114. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  7115. };
  7116. _proto.invert = function invert() {
  7117. var te = this.elements,
  7118. n11 = te[0],
  7119. n21 = te[1],
  7120. n31 = te[2],
  7121. n12 = te[3],
  7122. n22 = te[4],
  7123. n32 = te[5],
  7124. n13 = te[6],
  7125. n23 = te[7],
  7126. n33 = te[8],
  7127. t11 = n33 * n22 - n32 * n23,
  7128. t12 = n32 * n13 - n33 * n12,
  7129. t13 = n23 * n12 - n22 * n13,
  7130. det = n11 * t11 + n21 * t12 + n31 * t13;
  7131. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  7132. var detInv = 1 / det;
  7133. te[0] = t11 * detInv;
  7134. te[1] = (n31 * n23 - n33 * n21) * detInv;
  7135. te[2] = (n32 * n21 - n31 * n22) * detInv;
  7136. te[3] = t12 * detInv;
  7137. te[4] = (n33 * n11 - n31 * n13) * detInv;
  7138. te[5] = (n31 * n12 - n32 * n11) * detInv;
  7139. te[6] = t13 * detInv;
  7140. te[7] = (n21 * n13 - n23 * n11) * detInv;
  7141. te[8] = (n22 * n11 - n21 * n12) * detInv;
  7142. return this;
  7143. };
  7144. _proto.transpose = function transpose() {
  7145. var tmp;
  7146. var m = this.elements;
  7147. tmp = m[1];
  7148. m[1] = m[3];
  7149. m[3] = tmp;
  7150. tmp = m[2];
  7151. m[2] = m[6];
  7152. m[6] = tmp;
  7153. tmp = m[5];
  7154. m[5] = m[7];
  7155. m[7] = tmp;
  7156. return this;
  7157. };
  7158. _proto.getNormalMatrix = function getNormalMatrix(matrix4) {
  7159. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  7160. };
  7161. _proto.transposeIntoArray = function transposeIntoArray(r) {
  7162. var m = this.elements;
  7163. r[0] = m[0];
  7164. r[1] = m[3];
  7165. r[2] = m[6];
  7166. r[3] = m[1];
  7167. r[4] = m[4];
  7168. r[5] = m[7];
  7169. r[6] = m[2];
  7170. r[7] = m[5];
  7171. r[8] = m[8];
  7172. return this;
  7173. };
  7174. _proto.setUvTransform = function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  7175. var c = Math.cos(rotation);
  7176. var s = Math.sin(rotation);
  7177. 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);
  7178. return this;
  7179. };
  7180. _proto.scale = function scale(sx, sy) {
  7181. var te = this.elements;
  7182. te[0] *= sx;
  7183. te[3] *= sx;
  7184. te[6] *= sx;
  7185. te[1] *= sy;
  7186. te[4] *= sy;
  7187. te[7] *= sy;
  7188. return this;
  7189. };
  7190. _proto.rotate = function rotate(theta) {
  7191. var c = Math.cos(theta);
  7192. var s = Math.sin(theta);
  7193. var te = this.elements;
  7194. var a11 = te[0],
  7195. a12 = te[3],
  7196. a13 = te[6];
  7197. var a21 = te[1],
  7198. a22 = te[4],
  7199. a23 = te[7];
  7200. te[0] = c * a11 + s * a21;
  7201. te[3] = c * a12 + s * a22;
  7202. te[6] = c * a13 + s * a23;
  7203. te[1] = -s * a11 + c * a21;
  7204. te[4] = -s * a12 + c * a22;
  7205. te[7] = -s * a13 + c * a23;
  7206. return this;
  7207. };
  7208. _proto.translate = function translate(tx, ty) {
  7209. var te = this.elements;
  7210. te[0] += tx * te[2];
  7211. te[3] += tx * te[5];
  7212. te[6] += tx * te[8];
  7213. te[1] += ty * te[2];
  7214. te[4] += ty * te[5];
  7215. te[7] += ty * te[8];
  7216. return this;
  7217. };
  7218. _proto.equals = function equals(matrix) {
  7219. var te = this.elements;
  7220. var me = matrix.elements;
  7221. for (var i = 0; i < 9; i++) {
  7222. if (te[i] !== me[i]) return false;
  7223. }
  7224. return true;
  7225. };
  7226. _proto.fromArray = function fromArray(array, offset) {
  7227. if (offset === void 0) {
  7228. offset = 0;
  7229. }
  7230. for (var i = 0; i < 9; i++) {
  7231. this.elements[i] = array[i + offset];
  7232. }
  7233. return this;
  7234. };
  7235. _proto.toArray = function toArray(array, offset) {
  7236. if (array === void 0) {
  7237. array = [];
  7238. }
  7239. if (offset === void 0) {
  7240. offset = 0;
  7241. }
  7242. var te = this.elements;
  7243. array[offset] = te[0];
  7244. array[offset + 1] = te[1];
  7245. array[offset + 2] = te[2];
  7246. array[offset + 3] = te[3];
  7247. array[offset + 4] = te[4];
  7248. array[offset + 5] = te[5];
  7249. array[offset + 6] = te[6];
  7250. array[offset + 7] = te[7];
  7251. array[offset + 8] = te[8];
  7252. return array;
  7253. };
  7254. return Matrix3;
  7255. }();
  7256. var _canvas;
  7257. var ImageUtils = {
  7258. getDataURL: function getDataURL(image) {
  7259. if (/^data:/i.test(image.src)) {
  7260. return image.src;
  7261. }
  7262. if (typeof HTMLCanvasElement == 'undefined') {
  7263. return image.src;
  7264. }
  7265. var canvas;
  7266. if (image instanceof HTMLCanvasElement) {
  7267. canvas = image;
  7268. } else {
  7269. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  7270. _canvas.width = image.width;
  7271. _canvas.height = image.height;
  7272. var context = _canvas.getContext('2d');
  7273. if (image instanceof ImageData) {
  7274. context.putImageData(image, 0, 0);
  7275. } else {
  7276. context.drawImage(image, 0, 0, image.width, image.height);
  7277. }
  7278. canvas = _canvas;
  7279. }
  7280. if (canvas.width > 2048 || canvas.height > 2048) {
  7281. return canvas.toDataURL('image/jpeg', 0.6);
  7282. } else {
  7283. return canvas.toDataURL('image/png');
  7284. }
  7285. }
  7286. };
  7287. var textureId = 0;
  7288. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7289. if (image === void 0) {
  7290. image = Texture.DEFAULT_IMAGE;
  7291. }
  7292. if (mapping === void 0) {
  7293. mapping = Texture.DEFAULT_MAPPING;
  7294. }
  7295. if (wrapS === void 0) {
  7296. wrapS = ClampToEdgeWrapping;
  7297. }
  7298. if (wrapT === void 0) {
  7299. wrapT = ClampToEdgeWrapping;
  7300. }
  7301. if (magFilter === void 0) {
  7302. magFilter = LinearFilter;
  7303. }
  7304. if (minFilter === void 0) {
  7305. minFilter = LinearMipmapLinearFilter;
  7306. }
  7307. if (format === void 0) {
  7308. format = RGBAFormat;
  7309. }
  7310. if (type === void 0) {
  7311. type = UnsignedByteType;
  7312. }
  7313. if (anisotropy === void 0) {
  7314. anisotropy = 1;
  7315. }
  7316. if (encoding === void 0) {
  7317. encoding = LinearEncoding;
  7318. }
  7319. Object.defineProperty(this, 'id', {
  7320. value: textureId++
  7321. });
  7322. this.uuid = MathUtils.generateUUID();
  7323. this.name = '';
  7324. this.image = image;
  7325. this.mipmaps = [];
  7326. this.mapping = mapping;
  7327. this.wrapS = wrapS;
  7328. this.wrapT = wrapT;
  7329. this.magFilter = magFilter;
  7330. this.minFilter = minFilter;
  7331. this.anisotropy = anisotropy;
  7332. this.format = format;
  7333. this.internalFormat = null;
  7334. this.type = type;
  7335. this.offset = new Vector2(0, 0);
  7336. this.repeat = new Vector2(1, 1);
  7337. this.center = new Vector2(0, 0);
  7338. this.rotation = 0;
  7339. this.matrixAutoUpdate = true;
  7340. this.matrix = new Matrix3();
  7341. this.generateMipmaps = true;
  7342. this.premultiplyAlpha = false;
  7343. this.flipY = true;
  7344. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7345. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  7346. //
  7347. // Also changing the encoding after already used by a Material will not automatically make the Material
  7348. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  7349. this.encoding = encoding;
  7350. this.version = 0;
  7351. this.onUpdate = null;
  7352. }
  7353. Texture.DEFAULT_IMAGE = undefined;
  7354. Texture.DEFAULT_MAPPING = UVMapping;
  7355. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7356. constructor: Texture,
  7357. isTexture: true,
  7358. updateMatrix: function updateMatrix() {
  7359. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  7360. },
  7361. clone: function clone() {
  7362. return new this.constructor().copy(this);
  7363. },
  7364. copy: function copy(source) {
  7365. this.name = source.name;
  7366. this.image = source.image;
  7367. this.mipmaps = source.mipmaps.slice(0);
  7368. this.mapping = source.mapping;
  7369. this.wrapS = source.wrapS;
  7370. this.wrapT = source.wrapT;
  7371. this.magFilter = source.magFilter;
  7372. this.minFilter = source.minFilter;
  7373. this.anisotropy = source.anisotropy;
  7374. this.format = source.format;
  7375. this.internalFormat = source.internalFormat;
  7376. this.type = source.type;
  7377. this.offset.copy(source.offset);
  7378. this.repeat.copy(source.repeat);
  7379. this.center.copy(source.center);
  7380. this.rotation = source.rotation;
  7381. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7382. this.matrix.copy(source.matrix);
  7383. this.generateMipmaps = source.generateMipmaps;
  7384. this.premultiplyAlpha = source.premultiplyAlpha;
  7385. this.flipY = source.flipY;
  7386. this.unpackAlignment = source.unpackAlignment;
  7387. this.encoding = source.encoding;
  7388. return this;
  7389. },
  7390. toJSON: function toJSON(meta) {
  7391. var isRootObject = meta === undefined || typeof meta === 'string';
  7392. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  7393. return meta.textures[this.uuid];
  7394. }
  7395. var output = {
  7396. metadata: {
  7397. version: 4.5,
  7398. type: 'Texture',
  7399. generator: 'Texture.toJSON'
  7400. },
  7401. uuid: this.uuid,
  7402. name: this.name,
  7403. mapping: this.mapping,
  7404. repeat: [this.repeat.x, this.repeat.y],
  7405. offset: [this.offset.x, this.offset.y],
  7406. center: [this.center.x, this.center.y],
  7407. rotation: this.rotation,
  7408. wrap: [this.wrapS, this.wrapT],
  7409. format: this.format,
  7410. type: this.type,
  7411. encoding: this.encoding,
  7412. minFilter: this.minFilter,
  7413. magFilter: this.magFilter,
  7414. anisotropy: this.anisotropy,
  7415. flipY: this.flipY,
  7416. premultiplyAlpha: this.premultiplyAlpha,
  7417. unpackAlignment: this.unpackAlignment
  7418. };
  7419. if (this.image !== undefined) {
  7420. // TODO: Move to THREE.Image
  7421. var image = this.image;
  7422. if (image.uuid === undefined) {
  7423. image.uuid = MathUtils.generateUUID(); // UGH
  7424. }
  7425. if (!isRootObject && meta.images[image.uuid] === undefined) {
  7426. var url;
  7427. if (Array.isArray(image)) {
  7428. // process array of images e.g. CubeTexture
  7429. url = [];
  7430. for (var i = 0, l = image.length; i < l; i++) {
  7431. // check cube texture with data textures
  7432. if (image[i].isDataTexture) {
  7433. url.push(serializeImage(image[i].image));
  7434. } else {
  7435. url.push(serializeImage(image[i]));
  7436. }
  7437. }
  7438. } else {
  7439. // process single image
  7440. url = serializeImage(image);
  7441. }
  7442. meta.images[image.uuid] = {
  7443. uuid: image.uuid,
  7444. url: url
  7445. };
  7446. }
  7447. output.image = image.uuid;
  7448. }
  7449. if (!isRootObject) {
  7450. meta.textures[this.uuid] = output;
  7451. }
  7452. return output;
  7453. },
  7454. dispose: function dispose() {
  7455. this.dispatchEvent({
  7456. type: 'dispose'
  7457. });
  7458. },
  7459. transformUv: function transformUv(uv) {
  7460. if (this.mapping !== UVMapping) return uv;
  7461. uv.applyMatrix3(this.matrix);
  7462. if (uv.x < 0 || uv.x > 1) {
  7463. switch (this.wrapS) {
  7464. case RepeatWrapping:
  7465. uv.x = uv.x - Math.floor(uv.x);
  7466. break;
  7467. case ClampToEdgeWrapping:
  7468. uv.x = uv.x < 0 ? 0 : 1;
  7469. break;
  7470. case MirroredRepeatWrapping:
  7471. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  7472. uv.x = Math.ceil(uv.x) - uv.x;
  7473. } else {
  7474. uv.x = uv.x - Math.floor(uv.x);
  7475. }
  7476. break;
  7477. }
  7478. }
  7479. if (uv.y < 0 || uv.y > 1) {
  7480. switch (this.wrapT) {
  7481. case RepeatWrapping:
  7482. uv.y = uv.y - Math.floor(uv.y);
  7483. break;
  7484. case ClampToEdgeWrapping:
  7485. uv.y = uv.y < 0 ? 0 : 1;
  7486. break;
  7487. case MirroredRepeatWrapping:
  7488. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  7489. uv.y = Math.ceil(uv.y) - uv.y;
  7490. } else {
  7491. uv.y = uv.y - Math.floor(uv.y);
  7492. }
  7493. break;
  7494. }
  7495. }
  7496. if (this.flipY) {
  7497. uv.y = 1 - uv.y;
  7498. }
  7499. return uv;
  7500. }
  7501. });
  7502. Object.defineProperty(Texture.prototype, 'needsUpdate', {
  7503. set: function set(value) {
  7504. if (value === true) this.version++;
  7505. }
  7506. });
  7507. function serializeImage(image) {
  7508. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  7509. // default images
  7510. return ImageUtils.getDataURL(image);
  7511. } else {
  7512. if (image.data) {
  7513. // images of DataTexture
  7514. return {
  7515. data: Array.prototype.slice.call(image.data),
  7516. width: image.width,
  7517. height: image.height,
  7518. type: image.data.constructor.name
  7519. };
  7520. } else {
  7521. console.warn('THREE.Texture: Unable to serialize Texture.');
  7522. return {};
  7523. }
  7524. }
  7525. }
  7526. var Vector4 = /*#__PURE__*/function () {
  7527. function Vector4(x, y, z, w) {
  7528. if (x === void 0) {
  7529. x = 0;
  7530. }
  7531. if (y === void 0) {
  7532. y = 0;
  7533. }
  7534. if (z === void 0) {
  7535. z = 0;
  7536. }
  7537. if (w === void 0) {
  7538. w = 1;
  7539. }
  7540. Object.defineProperty(this, 'isVector4', {
  7541. value: true
  7542. });
  7543. this.x = x;
  7544. this.y = y;
  7545. this.z = z;
  7546. this.w = w;
  7547. }
  7548. var _proto = Vector4.prototype;
  7549. _proto.set = function set(x, y, z, w) {
  7550. this.x = x;
  7551. this.y = y;
  7552. this.z = z;
  7553. this.w = w;
  7554. return this;
  7555. };
  7556. _proto.setScalar = function setScalar(scalar) {
  7557. this.x = scalar;
  7558. this.y = scalar;
  7559. this.z = scalar;
  7560. this.w = scalar;
  7561. return this;
  7562. };
  7563. _proto.setX = function setX(x) {
  7564. this.x = x;
  7565. return this;
  7566. };
  7567. _proto.setY = function setY(y) {
  7568. this.y = y;
  7569. return this;
  7570. };
  7571. _proto.setZ = function setZ(z) {
  7572. this.z = z;
  7573. return this;
  7574. };
  7575. _proto.setW = function setW(w) {
  7576. this.w = w;
  7577. return this;
  7578. };
  7579. _proto.setComponent = function setComponent(index, value) {
  7580. switch (index) {
  7581. case 0:
  7582. this.x = value;
  7583. break;
  7584. case 1:
  7585. this.y = value;
  7586. break;
  7587. case 2:
  7588. this.z = value;
  7589. break;
  7590. case 3:
  7591. this.w = value;
  7592. break;
  7593. default:
  7594. throw new Error('index is out of range: ' + index);
  7595. }
  7596. return this;
  7597. };
  7598. _proto.getComponent = function getComponent(index) {
  7599. switch (index) {
  7600. case 0:
  7601. return this.x;
  7602. case 1:
  7603. return this.y;
  7604. case 2:
  7605. return this.z;
  7606. case 3:
  7607. return this.w;
  7608. default:
  7609. throw new Error('index is out of range: ' + index);
  7610. }
  7611. };
  7612. _proto.clone = function clone() {
  7613. return new this.constructor(this.x, this.y, this.z, this.w);
  7614. };
  7615. _proto.copy = function copy(v) {
  7616. this.x = v.x;
  7617. this.y = v.y;
  7618. this.z = v.z;
  7619. this.w = v.w !== undefined ? v.w : 1;
  7620. return this;
  7621. };
  7622. _proto.add = function add(v, w) {
  7623. if (w !== undefined) {
  7624. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  7625. return this.addVectors(v, w);
  7626. }
  7627. this.x += v.x;
  7628. this.y += v.y;
  7629. this.z += v.z;
  7630. this.w += v.w;
  7631. return this;
  7632. };
  7633. _proto.addScalar = function addScalar(s) {
  7634. this.x += s;
  7635. this.y += s;
  7636. this.z += s;
  7637. this.w += s;
  7638. return this;
  7639. };
  7640. _proto.addVectors = function addVectors(a, b) {
  7641. this.x = a.x + b.x;
  7642. this.y = a.y + b.y;
  7643. this.z = a.z + b.z;
  7644. this.w = a.w + b.w;
  7645. return this;
  7646. };
  7647. _proto.addScaledVector = function addScaledVector(v, s) {
  7648. this.x += v.x * s;
  7649. this.y += v.y * s;
  7650. this.z += v.z * s;
  7651. this.w += v.w * s;
  7652. return this;
  7653. };
  7654. _proto.sub = function sub(v, w) {
  7655. if (w !== undefined) {
  7656. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  7657. return this.subVectors(v, w);
  7658. }
  7659. this.x -= v.x;
  7660. this.y -= v.y;
  7661. this.z -= v.z;
  7662. this.w -= v.w;
  7663. return this;
  7664. };
  7665. _proto.subScalar = function subScalar(s) {
  7666. this.x -= s;
  7667. this.y -= s;
  7668. this.z -= s;
  7669. this.w -= s;
  7670. return this;
  7671. };
  7672. _proto.subVectors = function subVectors(a, b) {
  7673. this.x = a.x - b.x;
  7674. this.y = a.y - b.y;
  7675. this.z = a.z - b.z;
  7676. this.w = a.w - b.w;
  7677. return this;
  7678. };
  7679. _proto.multiply = function multiply(v) {
  7680. this.x *= v.x;
  7681. this.y *= v.y;
  7682. this.z *= v.z;
  7683. this.w *= v.w;
  7684. return this;
  7685. };
  7686. _proto.multiplyScalar = function multiplyScalar(scalar) {
  7687. this.x *= scalar;
  7688. this.y *= scalar;
  7689. this.z *= scalar;
  7690. this.w *= scalar;
  7691. return this;
  7692. };
  7693. _proto.applyMatrix4 = function applyMatrix4(m) {
  7694. var x = this.x,
  7695. y = this.y,
  7696. z = this.z,
  7697. w = this.w;
  7698. var e = m.elements;
  7699. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  7700. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  7701. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  7702. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  7703. return this;
  7704. };
  7705. _proto.divideScalar = function divideScalar(scalar) {
  7706. return this.multiplyScalar(1 / scalar);
  7707. };
  7708. _proto.setAxisAngleFromQuaternion = function setAxisAngleFromQuaternion(q) {
  7709. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7710. // q is assumed to be normalized
  7711. this.w = 2 * Math.acos(q.w);
  7712. var s = Math.sqrt(1 - q.w * q.w);
  7713. if (s < 0.0001) {
  7714. this.x = 1;
  7715. this.y = 0;
  7716. this.z = 0;
  7717. } else {
  7718. this.x = q.x / s;
  7719. this.y = q.y / s;
  7720. this.z = q.z / s;
  7721. }
  7722. return this;
  7723. };
  7724. _proto.setAxisAngleFromRotationMatrix = function setAxisAngleFromRotationMatrix(m) {
  7725. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7726. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7727. var angle, x, y, z; // variables for result
  7728. var epsilon = 0.01,
  7729. // margin to allow for rounding errors
  7730. epsilon2 = 0.1,
  7731. // margin to distinguish between 0 and 180 degrees
  7732. te = m.elements,
  7733. m11 = te[0],
  7734. m12 = te[4],
  7735. m13 = te[8],
  7736. m21 = te[1],
  7737. m22 = te[5],
  7738. m23 = te[9],
  7739. m31 = te[2],
  7740. m32 = te[6],
  7741. m33 = te[10];
  7742. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  7743. // singularity found
  7744. // first check for identity matrix which must have +1 for all terms
  7745. // in leading diagonal and zero in other terms
  7746. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  7747. // this singularity is identity matrix so angle = 0
  7748. this.set(1, 0, 0, 0);
  7749. return this; // zero angle, arbitrary axis
  7750. } // otherwise this singularity is angle = 180
  7751. angle = Math.PI;
  7752. var xx = (m11 + 1) / 2;
  7753. var yy = (m22 + 1) / 2;
  7754. var zz = (m33 + 1) / 2;
  7755. var xy = (m12 + m21) / 4;
  7756. var xz = (m13 + m31) / 4;
  7757. var yz = (m23 + m32) / 4;
  7758. if (xx > yy && xx > zz) {
  7759. // m11 is the largest diagonal term
  7760. if (xx < epsilon) {
  7761. x = 0;
  7762. y = 0.707106781;
  7763. z = 0.707106781;
  7764. } else {
  7765. x = Math.sqrt(xx);
  7766. y = xy / x;
  7767. z = xz / x;
  7768. }
  7769. } else if (yy > zz) {
  7770. // m22 is the largest diagonal term
  7771. if (yy < epsilon) {
  7772. x = 0.707106781;
  7773. y = 0;
  7774. z = 0.707106781;
  7775. } else {
  7776. y = Math.sqrt(yy);
  7777. x = xy / y;
  7778. z = yz / y;
  7779. }
  7780. } else {
  7781. // m33 is the largest diagonal term so base result on this
  7782. if (zz < epsilon) {
  7783. x = 0.707106781;
  7784. y = 0.707106781;
  7785. z = 0;
  7786. } else {
  7787. z = Math.sqrt(zz);
  7788. x = xz / z;
  7789. y = yz / z;
  7790. }
  7791. }
  7792. this.set(x, y, z, angle);
  7793. return this; // return 180 deg rotation
  7794. } // as we have reached here there are no singularities so we can handle normally
  7795. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  7796. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7797. // caught by singularity test above, but I've left it in just in case
  7798. this.x = (m32 - m23) / s;
  7799. this.y = (m13 - m31) / s;
  7800. this.z = (m21 - m12) / s;
  7801. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  7802. return this;
  7803. };
  7804. _proto.min = function min(v) {
  7805. this.x = Math.min(this.x, v.x);
  7806. this.y = Math.min(this.y, v.y);
  7807. this.z = Math.min(this.z, v.z);
  7808. this.w = Math.min(this.w, v.w);
  7809. return this;
  7810. };
  7811. _proto.max = function max(v) {
  7812. this.x = Math.max(this.x, v.x);
  7813. this.y = Math.max(this.y, v.y);
  7814. this.z = Math.max(this.z, v.z);
  7815. this.w = Math.max(this.w, v.w);
  7816. return this;
  7817. };
  7818. _proto.clamp = function clamp(min, max) {
  7819. // assumes min < max, componentwise
  7820. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7821. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7822. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7823. this.w = Math.max(min.w, Math.min(max.w, this.w));
  7824. return this;
  7825. };
  7826. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  7827. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  7828. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  7829. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  7830. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  7831. return this;
  7832. };
  7833. _proto.clampLength = function clampLength(min, max) {
  7834. var length = this.length();
  7835. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  7836. };
  7837. _proto.floor = function floor() {
  7838. this.x = Math.floor(this.x);
  7839. this.y = Math.floor(this.y);
  7840. this.z = Math.floor(this.z);
  7841. this.w = Math.floor(this.w);
  7842. return this;
  7843. };
  7844. _proto.ceil = function ceil() {
  7845. this.x = Math.ceil(this.x);
  7846. this.y = Math.ceil(this.y);
  7847. this.z = Math.ceil(this.z);
  7848. this.w = Math.ceil(this.w);
  7849. return this;
  7850. };
  7851. _proto.round = function round() {
  7852. this.x = Math.round(this.x);
  7853. this.y = Math.round(this.y);
  7854. this.z = Math.round(this.z);
  7855. this.w = Math.round(this.w);
  7856. return this;
  7857. };
  7858. _proto.roundToZero = function roundToZero() {
  7859. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  7860. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  7861. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  7862. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  7863. return this;
  7864. };
  7865. _proto.negate = function negate() {
  7866. this.x = -this.x;
  7867. this.y = -this.y;
  7868. this.z = -this.z;
  7869. this.w = -this.w;
  7870. return this;
  7871. };
  7872. _proto.dot = function dot(v) {
  7873. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7874. };
  7875. _proto.lengthSq = function lengthSq() {
  7876. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7877. };
  7878. _proto.length = function length() {
  7879. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  7880. };
  7881. _proto.manhattanLength = function manhattanLength() {
  7882. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  7883. };
  7884. _proto.normalize = function normalize() {
  7885. return this.divideScalar(this.length() || 1);
  7886. };
  7887. _proto.setLength = function setLength(length) {
  7888. return this.normalize().multiplyScalar(length);
  7889. };
  7890. _proto.lerp = function lerp(v, alpha) {
  7891. this.x += (v.x - this.x) * alpha;
  7892. this.y += (v.y - this.y) * alpha;
  7893. this.z += (v.z - this.z) * alpha;
  7894. this.w += (v.w - this.w) * alpha;
  7895. return this;
  7896. };
  7897. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  7898. this.x = v1.x + (v2.x - v1.x) * alpha;
  7899. this.y = v1.y + (v2.y - v1.y) * alpha;
  7900. this.z = v1.z + (v2.z - v1.z) * alpha;
  7901. this.w = v1.w + (v2.w - v1.w) * alpha;
  7902. return this;
  7903. };
  7904. _proto.equals = function equals(v) {
  7905. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  7906. };
  7907. _proto.fromArray = function fromArray(array, offset) {
  7908. if (offset === void 0) {
  7909. offset = 0;
  7910. }
  7911. this.x = array[offset];
  7912. this.y = array[offset + 1];
  7913. this.z = array[offset + 2];
  7914. this.w = array[offset + 3];
  7915. return this;
  7916. };
  7917. _proto.toArray = function toArray(array, offset) {
  7918. if (array === void 0) {
  7919. array = [];
  7920. }
  7921. if (offset === void 0) {
  7922. offset = 0;
  7923. }
  7924. array[offset] = this.x;
  7925. array[offset + 1] = this.y;
  7926. array[offset + 2] = this.z;
  7927. array[offset + 3] = this.w;
  7928. return array;
  7929. };
  7930. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  7931. if (offset !== undefined) {
  7932. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  7933. }
  7934. this.x = attribute.getX(index);
  7935. this.y = attribute.getY(index);
  7936. this.z = attribute.getZ(index);
  7937. this.w = attribute.getW(index);
  7938. return this;
  7939. };
  7940. _proto.random = function random() {
  7941. this.x = Math.random();
  7942. this.y = Math.random();
  7943. this.z = Math.random();
  7944. this.w = Math.random();
  7945. return this;
  7946. };
  7947. _createClass(Vector4, [{
  7948. key: "width",
  7949. get: function get() {
  7950. return this.z;
  7951. },
  7952. set: function set(value) {
  7953. this.z = value;
  7954. }
  7955. }, {
  7956. key: "height",
  7957. get: function get() {
  7958. return this.w;
  7959. },
  7960. set: function set(value) {
  7961. this.w = value;
  7962. }
  7963. }]);
  7964. return Vector4;
  7965. }();
  7966. /*
  7967. In options, we can specify:
  7968. * Texture parameters for an auto-generated target texture
  7969. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7970. */
  7971. var WebGLRenderTarget = /*#__PURE__*/function (_EventDispatcher) {
  7972. _inheritsLoose(WebGLRenderTarget, _EventDispatcher);
  7973. function WebGLRenderTarget(width, height, options) {
  7974. var _this;
  7975. _this = _EventDispatcher.call(this) || this;
  7976. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLRenderTarget', {
  7977. value: true
  7978. });
  7979. _this.width = width;
  7980. _this.height = height;
  7981. _this.scissor = new Vector4(0, 0, width, height);
  7982. _this.scissorTest = false;
  7983. _this.viewport = new Vector4(0, 0, width, height);
  7984. options = options || {};
  7985. _this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7986. _this.texture.image = {};
  7987. _this.texture.image.width = width;
  7988. _this.texture.image.height = height;
  7989. _this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7990. _this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7991. _this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7992. _this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  7993. _this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7994. return _this;
  7995. }
  7996. var _proto = WebGLRenderTarget.prototype;
  7997. _proto.setSize = function setSize(width, height) {
  7998. if (this.width !== width || this.height !== height) {
  7999. this.width = width;
  8000. this.height = height;
  8001. this.texture.image.width = width;
  8002. this.texture.image.height = height;
  8003. this.dispose();
  8004. }
  8005. this.viewport.set(0, 0, width, height);
  8006. this.scissor.set(0, 0, width, height);
  8007. };
  8008. _proto.clone = function clone() {
  8009. return new this.constructor().copy(this);
  8010. };
  8011. _proto.copy = function copy(source) {
  8012. this.width = source.width;
  8013. this.height = source.height;
  8014. this.viewport.copy(source.viewport);
  8015. this.texture = source.texture.clone();
  8016. this.depthBuffer = source.depthBuffer;
  8017. this.stencilBuffer = source.stencilBuffer;
  8018. this.depthTexture = source.depthTexture;
  8019. return this;
  8020. };
  8021. _proto.dispose = function dispose() {
  8022. this.dispatchEvent({
  8023. type: 'dispose'
  8024. });
  8025. };
  8026. return WebGLRenderTarget;
  8027. }(EventDispatcher);
  8028. var WebGLMultisampleRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
  8029. _inheritsLoose(WebGLMultisampleRenderTarget, _WebGLRenderTarget);
  8030. function WebGLMultisampleRenderTarget(width, height, options) {
  8031. var _this;
  8032. _this = _WebGLRenderTarget.call(this, width, height, options) || this;
  8033. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLMultisampleRenderTarget', {
  8034. value: true
  8035. });
  8036. _this.samples = 4;
  8037. return _this;
  8038. }
  8039. var _proto = WebGLMultisampleRenderTarget.prototype;
  8040. _proto.copy = function copy(source) {
  8041. _WebGLRenderTarget.prototype.copy.call(this, source);
  8042. this.samples = source.samples;
  8043. return this;
  8044. };
  8045. return WebGLMultisampleRenderTarget;
  8046. }(WebGLRenderTarget);
  8047. var Quaternion = /*#__PURE__*/function () {
  8048. function Quaternion(x, y, z, w) {
  8049. if (x === void 0) {
  8050. x = 0;
  8051. }
  8052. if (y === void 0) {
  8053. y = 0;
  8054. }
  8055. if (z === void 0) {
  8056. z = 0;
  8057. }
  8058. if (w === void 0) {
  8059. w = 1;
  8060. }
  8061. Object.defineProperty(this, 'isQuaternion', {
  8062. value: true
  8063. });
  8064. this._x = x;
  8065. this._y = y;
  8066. this._z = z;
  8067. this._w = w;
  8068. }
  8069. Quaternion.slerp = function slerp(qa, qb, qm, t) {
  8070. return qm.copy(qa).slerp(qb, t);
  8071. };
  8072. Quaternion.slerpFlat = function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  8073. // fuzz-free, array-based Quaternion SLERP operation
  8074. var x0 = src0[srcOffset0 + 0],
  8075. y0 = src0[srcOffset0 + 1],
  8076. z0 = src0[srcOffset0 + 2],
  8077. w0 = src0[srcOffset0 + 3];
  8078. var x1 = src1[srcOffset1 + 0],
  8079. y1 = src1[srcOffset1 + 1],
  8080. z1 = src1[srcOffset1 + 2],
  8081. w1 = src1[srcOffset1 + 3];
  8082. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  8083. var s = 1 - t;
  8084. var cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  8085. dir = cos >= 0 ? 1 : -1,
  8086. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  8087. if (sqrSin > Number.EPSILON) {
  8088. var sin = Math.sqrt(sqrSin),
  8089. len = Math.atan2(sin, cos * dir);
  8090. s = Math.sin(s * len) / sin;
  8091. t = Math.sin(t * len) / sin;
  8092. }
  8093. var tDir = t * dir;
  8094. x0 = x0 * s + x1 * tDir;
  8095. y0 = y0 * s + y1 * tDir;
  8096. z0 = z0 * s + z1 * tDir;
  8097. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  8098. if (s === 1 - t) {
  8099. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  8100. x0 *= f;
  8101. y0 *= f;
  8102. z0 *= f;
  8103. w0 *= f;
  8104. }
  8105. }
  8106. dst[dstOffset] = x0;
  8107. dst[dstOffset + 1] = y0;
  8108. dst[dstOffset + 2] = z0;
  8109. dst[dstOffset + 3] = w0;
  8110. };
  8111. Quaternion.multiplyQuaternionsFlat = function multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  8112. var x0 = src0[srcOffset0];
  8113. var y0 = src0[srcOffset0 + 1];
  8114. var z0 = src0[srcOffset0 + 2];
  8115. var w0 = src0[srcOffset0 + 3];
  8116. var x1 = src1[srcOffset1];
  8117. var y1 = src1[srcOffset1 + 1];
  8118. var z1 = src1[srcOffset1 + 2];
  8119. var w1 = src1[srcOffset1 + 3];
  8120. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  8121. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  8122. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  8123. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  8124. return dst;
  8125. };
  8126. var _proto = Quaternion.prototype;
  8127. _proto.set = function set(x, y, z, w) {
  8128. this._x = x;
  8129. this._y = y;
  8130. this._z = z;
  8131. this._w = w;
  8132. this._onChangeCallback();
  8133. return this;
  8134. };
  8135. _proto.clone = function clone() {
  8136. return new this.constructor(this._x, this._y, this._z, this._w);
  8137. };
  8138. _proto.copy = function copy(quaternion) {
  8139. this._x = quaternion.x;
  8140. this._y = quaternion.y;
  8141. this._z = quaternion.z;
  8142. this._w = quaternion.w;
  8143. this._onChangeCallback();
  8144. return this;
  8145. };
  8146. _proto.setFromEuler = function setFromEuler(euler, update) {
  8147. if (!(euler && euler.isEuler)) {
  8148. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  8149. }
  8150. var x = euler._x,
  8151. y = euler._y,
  8152. z = euler._z,
  8153. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  8154. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  8155. // content/SpinCalc.m
  8156. var cos = Math.cos;
  8157. var sin = Math.sin;
  8158. var c1 = cos(x / 2);
  8159. var c2 = cos(y / 2);
  8160. var c3 = cos(z / 2);
  8161. var s1 = sin(x / 2);
  8162. var s2 = sin(y / 2);
  8163. var s3 = sin(z / 2);
  8164. switch (order) {
  8165. case 'XYZ':
  8166. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8167. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8168. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8169. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8170. break;
  8171. case 'YXZ':
  8172. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8173. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8174. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8175. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8176. break;
  8177. case 'ZXY':
  8178. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8179. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8180. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8181. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8182. break;
  8183. case 'ZYX':
  8184. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8185. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8186. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8187. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8188. break;
  8189. case 'YZX':
  8190. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8191. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8192. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8193. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8194. break;
  8195. case 'XZY':
  8196. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8197. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8198. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8199. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8200. break;
  8201. default:
  8202. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  8203. }
  8204. if (update !== false) this._onChangeCallback();
  8205. return this;
  8206. };
  8207. _proto.setFromAxisAngle = function setFromAxisAngle(axis, angle) {
  8208. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  8209. // assumes axis is normalized
  8210. var halfAngle = angle / 2,
  8211. s = Math.sin(halfAngle);
  8212. this._x = axis.x * s;
  8213. this._y = axis.y * s;
  8214. this._z = axis.z * s;
  8215. this._w = Math.cos(halfAngle);
  8216. this._onChangeCallback();
  8217. return this;
  8218. };
  8219. _proto.setFromRotationMatrix = function setFromRotationMatrix(m) {
  8220. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  8221. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8222. var te = m.elements,
  8223. m11 = te[0],
  8224. m12 = te[4],
  8225. m13 = te[8],
  8226. m21 = te[1],
  8227. m22 = te[5],
  8228. m23 = te[9],
  8229. m31 = te[2],
  8230. m32 = te[6],
  8231. m33 = te[10],
  8232. trace = m11 + m22 + m33;
  8233. if (trace > 0) {
  8234. var s = 0.5 / Math.sqrt(trace + 1.0);
  8235. this._w = 0.25 / s;
  8236. this._x = (m32 - m23) * s;
  8237. this._y = (m13 - m31) * s;
  8238. this._z = (m21 - m12) * s;
  8239. } else if (m11 > m22 && m11 > m33) {
  8240. var _s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  8241. this._w = (m32 - m23) / _s;
  8242. this._x = 0.25 * _s;
  8243. this._y = (m12 + m21) / _s;
  8244. this._z = (m13 + m31) / _s;
  8245. } else if (m22 > m33) {
  8246. var _s2 = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  8247. this._w = (m13 - m31) / _s2;
  8248. this._x = (m12 + m21) / _s2;
  8249. this._y = 0.25 * _s2;
  8250. this._z = (m23 + m32) / _s2;
  8251. } else {
  8252. var _s3 = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  8253. this._w = (m21 - m12) / _s3;
  8254. this._x = (m13 + m31) / _s3;
  8255. this._y = (m23 + m32) / _s3;
  8256. this._z = 0.25 * _s3;
  8257. }
  8258. this._onChangeCallback();
  8259. return this;
  8260. };
  8261. _proto.setFromUnitVectors = function setFromUnitVectors(vFrom, vTo) {
  8262. // assumes direction vectors vFrom and vTo are normalized
  8263. var EPS = 0.000001;
  8264. var r = vFrom.dot(vTo) + 1;
  8265. if (r < EPS) {
  8266. r = 0;
  8267. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  8268. this._x = -vFrom.y;
  8269. this._y = vFrom.x;
  8270. this._z = 0;
  8271. this._w = r;
  8272. } else {
  8273. this._x = 0;
  8274. this._y = -vFrom.z;
  8275. this._z = vFrom.y;
  8276. this._w = r;
  8277. }
  8278. } else {
  8279. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  8280. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  8281. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  8282. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  8283. this._w = r;
  8284. }
  8285. return this.normalize();
  8286. };
  8287. _proto.angleTo = function angleTo(q) {
  8288. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  8289. };
  8290. _proto.rotateTowards = function rotateTowards(q, step) {
  8291. var angle = this.angleTo(q);
  8292. if (angle === 0) return this;
  8293. var t = Math.min(1, step / angle);
  8294. this.slerp(q, t);
  8295. return this;
  8296. };
  8297. _proto.identity = function identity() {
  8298. return this.set(0, 0, 0, 1);
  8299. };
  8300. _proto.invert = function invert() {
  8301. // quaternion is assumed to have unit length
  8302. return this.conjugate();
  8303. };
  8304. _proto.conjugate = function conjugate() {
  8305. this._x *= -1;
  8306. this._y *= -1;
  8307. this._z *= -1;
  8308. this._onChangeCallback();
  8309. return this;
  8310. };
  8311. _proto.dot = function dot(v) {
  8312. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  8313. };
  8314. _proto.lengthSq = function lengthSq() {
  8315. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  8316. };
  8317. _proto.length = function length() {
  8318. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  8319. };
  8320. _proto.normalize = function normalize() {
  8321. var l = this.length();
  8322. if (l === 0) {
  8323. this._x = 0;
  8324. this._y = 0;
  8325. this._z = 0;
  8326. this._w = 1;
  8327. } else {
  8328. l = 1 / l;
  8329. this._x = this._x * l;
  8330. this._y = this._y * l;
  8331. this._z = this._z * l;
  8332. this._w = this._w * l;
  8333. }
  8334. this._onChangeCallback();
  8335. return this;
  8336. };
  8337. _proto.multiply = function multiply(q, p) {
  8338. if (p !== undefined) {
  8339. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  8340. return this.multiplyQuaternions(q, p);
  8341. }
  8342. return this.multiplyQuaternions(this, q);
  8343. };
  8344. _proto.premultiply = function premultiply(q) {
  8345. return this.multiplyQuaternions(q, this);
  8346. };
  8347. _proto.multiplyQuaternions = function multiplyQuaternions(a, b) {
  8348. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  8349. var qax = a._x,
  8350. qay = a._y,
  8351. qaz = a._z,
  8352. qaw = a._w;
  8353. var qbx = b._x,
  8354. qby = b._y,
  8355. qbz = b._z,
  8356. qbw = b._w;
  8357. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  8358. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  8359. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  8360. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  8361. this._onChangeCallback();
  8362. return this;
  8363. };
  8364. _proto.slerp = function slerp(qb, t) {
  8365. if (t === 0) return this;
  8366. if (t === 1) return this.copy(qb);
  8367. var x = this._x,
  8368. y = this._y,
  8369. z = this._z,
  8370. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  8371. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  8372. if (cosHalfTheta < 0) {
  8373. this._w = -qb._w;
  8374. this._x = -qb._x;
  8375. this._y = -qb._y;
  8376. this._z = -qb._z;
  8377. cosHalfTheta = -cosHalfTheta;
  8378. } else {
  8379. this.copy(qb);
  8380. }
  8381. if (cosHalfTheta >= 1.0) {
  8382. this._w = w;
  8383. this._x = x;
  8384. this._y = y;
  8385. this._z = z;
  8386. return this;
  8387. }
  8388. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  8389. if (sqrSinHalfTheta <= Number.EPSILON) {
  8390. var s = 1 - t;
  8391. this._w = s * w + t * this._w;
  8392. this._x = s * x + t * this._x;
  8393. this._y = s * y + t * this._y;
  8394. this._z = s * z + t * this._z;
  8395. this.normalize();
  8396. this._onChangeCallback();
  8397. return this;
  8398. }
  8399. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  8400. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  8401. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  8402. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  8403. this._w = w * ratioA + this._w * ratioB;
  8404. this._x = x * ratioA + this._x * ratioB;
  8405. this._y = y * ratioA + this._y * ratioB;
  8406. this._z = z * ratioA + this._z * ratioB;
  8407. this._onChangeCallback();
  8408. return this;
  8409. };
  8410. _proto.equals = function equals(quaternion) {
  8411. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  8412. };
  8413. _proto.fromArray = function fromArray(array, offset) {
  8414. if (offset === void 0) {
  8415. offset = 0;
  8416. }
  8417. this._x = array[offset];
  8418. this._y = array[offset + 1];
  8419. this._z = array[offset + 2];
  8420. this._w = array[offset + 3];
  8421. this._onChangeCallback();
  8422. return this;
  8423. };
  8424. _proto.toArray = function toArray(array, offset) {
  8425. if (array === void 0) {
  8426. array = [];
  8427. }
  8428. if (offset === void 0) {
  8429. offset = 0;
  8430. }
  8431. array[offset] = this._x;
  8432. array[offset + 1] = this._y;
  8433. array[offset + 2] = this._z;
  8434. array[offset + 3] = this._w;
  8435. return array;
  8436. };
  8437. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  8438. this._x = attribute.getX(index);
  8439. this._y = attribute.getY(index);
  8440. this._z = attribute.getZ(index);
  8441. this._w = attribute.getW(index);
  8442. return this;
  8443. };
  8444. _proto._onChange = function _onChange(callback) {
  8445. this._onChangeCallback = callback;
  8446. return this;
  8447. };
  8448. _proto._onChangeCallback = function _onChangeCallback() {};
  8449. _createClass(Quaternion, [{
  8450. key: "x",
  8451. get: function get() {
  8452. return this._x;
  8453. },
  8454. set: function set(value) {
  8455. this._x = value;
  8456. this._onChangeCallback();
  8457. }
  8458. }, {
  8459. key: "y",
  8460. get: function get() {
  8461. return this._y;
  8462. },
  8463. set: function set(value) {
  8464. this._y = value;
  8465. this._onChangeCallback();
  8466. }
  8467. }, {
  8468. key: "z",
  8469. get: function get() {
  8470. return this._z;
  8471. },
  8472. set: function set(value) {
  8473. this._z = value;
  8474. this._onChangeCallback();
  8475. }
  8476. }, {
  8477. key: "w",
  8478. get: function get() {
  8479. return this._w;
  8480. },
  8481. set: function set(value) {
  8482. this._w = value;
  8483. this._onChangeCallback();
  8484. }
  8485. }]);
  8486. return Quaternion;
  8487. }();
  8488. var Vector3 = /*#__PURE__*/function () {
  8489. function Vector3(x, y, z) {
  8490. if (x === void 0) {
  8491. x = 0;
  8492. }
  8493. if (y === void 0) {
  8494. y = 0;
  8495. }
  8496. if (z === void 0) {
  8497. z = 0;
  8498. }
  8499. Object.defineProperty(this, 'isVector3', {
  8500. value: true
  8501. });
  8502. this.x = x;
  8503. this.y = y;
  8504. this.z = z;
  8505. }
  8506. var _proto = Vector3.prototype;
  8507. _proto.set = function set(x, y, z) {
  8508. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  8509. this.x = x;
  8510. this.y = y;
  8511. this.z = z;
  8512. return this;
  8513. };
  8514. _proto.setScalar = function setScalar(scalar) {
  8515. this.x = scalar;
  8516. this.y = scalar;
  8517. this.z = scalar;
  8518. return this;
  8519. };
  8520. _proto.setX = function setX(x) {
  8521. this.x = x;
  8522. return this;
  8523. };
  8524. _proto.setY = function setY(y) {
  8525. this.y = y;
  8526. return this;
  8527. };
  8528. _proto.setZ = function setZ(z) {
  8529. this.z = z;
  8530. return this;
  8531. };
  8532. _proto.setComponent = function setComponent(index, value) {
  8533. switch (index) {
  8534. case 0:
  8535. this.x = value;
  8536. break;
  8537. case 1:
  8538. this.y = value;
  8539. break;
  8540. case 2:
  8541. this.z = value;
  8542. break;
  8543. default:
  8544. throw new Error('index is out of range: ' + index);
  8545. }
  8546. return this;
  8547. };
  8548. _proto.getComponent = function getComponent(index) {
  8549. switch (index) {
  8550. case 0:
  8551. return this.x;
  8552. case 1:
  8553. return this.y;
  8554. case 2:
  8555. return this.z;
  8556. default:
  8557. throw new Error('index is out of range: ' + index);
  8558. }
  8559. };
  8560. _proto.clone = function clone() {
  8561. return new this.constructor(this.x, this.y, this.z);
  8562. };
  8563. _proto.copy = function copy(v) {
  8564. this.x = v.x;
  8565. this.y = v.y;
  8566. this.z = v.z;
  8567. return this;
  8568. };
  8569. _proto.add = function add(v, w) {
  8570. if (w !== undefined) {
  8571. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  8572. return this.addVectors(v, w);
  8573. }
  8574. this.x += v.x;
  8575. this.y += v.y;
  8576. this.z += v.z;
  8577. return this;
  8578. };
  8579. _proto.addScalar = function addScalar(s) {
  8580. this.x += s;
  8581. this.y += s;
  8582. this.z += s;
  8583. return this;
  8584. };
  8585. _proto.addVectors = function addVectors(a, b) {
  8586. this.x = a.x + b.x;
  8587. this.y = a.y + b.y;
  8588. this.z = a.z + b.z;
  8589. return this;
  8590. };
  8591. _proto.addScaledVector = function addScaledVector(v, s) {
  8592. this.x += v.x * s;
  8593. this.y += v.y * s;
  8594. this.z += v.z * s;
  8595. return this;
  8596. };
  8597. _proto.sub = function sub(v, w) {
  8598. if (w !== undefined) {
  8599. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  8600. return this.subVectors(v, w);
  8601. }
  8602. this.x -= v.x;
  8603. this.y -= v.y;
  8604. this.z -= v.z;
  8605. return this;
  8606. };
  8607. _proto.subScalar = function subScalar(s) {
  8608. this.x -= s;
  8609. this.y -= s;
  8610. this.z -= s;
  8611. return this;
  8612. };
  8613. _proto.subVectors = function subVectors(a, b) {
  8614. this.x = a.x - b.x;
  8615. this.y = a.y - b.y;
  8616. this.z = a.z - b.z;
  8617. return this;
  8618. };
  8619. _proto.multiply = function multiply(v, w) {
  8620. if (w !== undefined) {
  8621. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  8622. return this.multiplyVectors(v, w);
  8623. }
  8624. this.x *= v.x;
  8625. this.y *= v.y;
  8626. this.z *= v.z;
  8627. return this;
  8628. };
  8629. _proto.multiplyScalar = function multiplyScalar(scalar) {
  8630. this.x *= scalar;
  8631. this.y *= scalar;
  8632. this.z *= scalar;
  8633. return this;
  8634. };
  8635. _proto.multiplyVectors = function multiplyVectors(a, b) {
  8636. this.x = a.x * b.x;
  8637. this.y = a.y * b.y;
  8638. this.z = a.z * b.z;
  8639. return this;
  8640. };
  8641. _proto.applyEuler = function applyEuler(euler) {
  8642. if (!(euler && euler.isEuler)) {
  8643. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  8644. }
  8645. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  8646. };
  8647. _proto.applyAxisAngle = function applyAxisAngle(axis, angle) {
  8648. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  8649. };
  8650. _proto.applyMatrix3 = function applyMatrix3(m) {
  8651. var x = this.x,
  8652. y = this.y,
  8653. z = this.z;
  8654. var e = m.elements;
  8655. this.x = e[0] * x + e[3] * y + e[6] * z;
  8656. this.y = e[1] * x + e[4] * y + e[7] * z;
  8657. this.z = e[2] * x + e[5] * y + e[8] * z;
  8658. return this;
  8659. };
  8660. _proto.applyNormalMatrix = function applyNormalMatrix(m) {
  8661. return this.applyMatrix3(m).normalize();
  8662. };
  8663. _proto.applyMatrix4 = function applyMatrix4(m) {
  8664. var x = this.x,
  8665. y = this.y,
  8666. z = this.z;
  8667. var e = m.elements;
  8668. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  8669. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  8670. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  8671. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  8672. return this;
  8673. };
  8674. _proto.applyQuaternion = function applyQuaternion(q) {
  8675. var x = this.x,
  8676. y = this.y,
  8677. z = this.z;
  8678. var qx = q.x,
  8679. qy = q.y,
  8680. qz = q.z,
  8681. qw = q.w; // calculate quat * vector
  8682. var ix = qw * x + qy * z - qz * y;
  8683. var iy = qw * y + qz * x - qx * z;
  8684. var iz = qw * z + qx * y - qy * x;
  8685. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  8686. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  8687. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  8688. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  8689. return this;
  8690. };
  8691. _proto.project = function project(camera) {
  8692. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  8693. };
  8694. _proto.unproject = function unproject(camera) {
  8695. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  8696. };
  8697. _proto.transformDirection = function transformDirection(m) {
  8698. // input: THREE.Matrix4 affine matrix
  8699. // vector interpreted as a direction
  8700. var x = this.x,
  8701. y = this.y,
  8702. z = this.z;
  8703. var e = m.elements;
  8704. this.x = e[0] * x + e[4] * y + e[8] * z;
  8705. this.y = e[1] * x + e[5] * y + e[9] * z;
  8706. this.z = e[2] * x + e[6] * y + e[10] * z;
  8707. return this.normalize();
  8708. };
  8709. _proto.divide = function divide(v) {
  8710. this.x /= v.x;
  8711. this.y /= v.y;
  8712. this.z /= v.z;
  8713. return this;
  8714. };
  8715. _proto.divideScalar = function divideScalar(scalar) {
  8716. return this.multiplyScalar(1 / scalar);
  8717. };
  8718. _proto.min = function min(v) {
  8719. this.x = Math.min(this.x, v.x);
  8720. this.y = Math.min(this.y, v.y);
  8721. this.z = Math.min(this.z, v.z);
  8722. return this;
  8723. };
  8724. _proto.max = function max(v) {
  8725. this.x = Math.max(this.x, v.x);
  8726. this.y = Math.max(this.y, v.y);
  8727. this.z = Math.max(this.z, v.z);
  8728. return this;
  8729. };
  8730. _proto.clamp = function clamp(min, max) {
  8731. // assumes min < max, componentwise
  8732. this.x = Math.max(min.x, Math.min(max.x, this.x));
  8733. this.y = Math.max(min.y, Math.min(max.y, this.y));
  8734. this.z = Math.max(min.z, Math.min(max.z, this.z));
  8735. return this;
  8736. };
  8737. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  8738. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  8739. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  8740. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  8741. return this;
  8742. };
  8743. _proto.clampLength = function clampLength(min, max) {
  8744. var length = this.length();
  8745. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  8746. };
  8747. _proto.floor = function floor() {
  8748. this.x = Math.floor(this.x);
  8749. this.y = Math.floor(this.y);
  8750. this.z = Math.floor(this.z);
  8751. return this;
  8752. };
  8753. _proto.ceil = function ceil() {
  8754. this.x = Math.ceil(this.x);
  8755. this.y = Math.ceil(this.y);
  8756. this.z = Math.ceil(this.z);
  8757. return this;
  8758. };
  8759. _proto.round = function round() {
  8760. this.x = Math.round(this.x);
  8761. this.y = Math.round(this.y);
  8762. this.z = Math.round(this.z);
  8763. return this;
  8764. };
  8765. _proto.roundToZero = function roundToZero() {
  8766. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  8767. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  8768. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  8769. return this;
  8770. };
  8771. _proto.negate = function negate() {
  8772. this.x = -this.x;
  8773. this.y = -this.y;
  8774. this.z = -this.z;
  8775. return this;
  8776. };
  8777. _proto.dot = function dot(v) {
  8778. return this.x * v.x + this.y * v.y + this.z * v.z;
  8779. } // TODO lengthSquared?
  8780. ;
  8781. _proto.lengthSq = function lengthSq() {
  8782. return this.x * this.x + this.y * this.y + this.z * this.z;
  8783. };
  8784. _proto.length = function length() {
  8785. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  8786. };
  8787. _proto.manhattanLength = function manhattanLength() {
  8788. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  8789. };
  8790. _proto.normalize = function normalize() {
  8791. return this.divideScalar(this.length() || 1);
  8792. };
  8793. _proto.setLength = function setLength(length) {
  8794. return this.normalize().multiplyScalar(length);
  8795. };
  8796. _proto.lerp = function lerp(v, alpha) {
  8797. this.x += (v.x - this.x) * alpha;
  8798. this.y += (v.y - this.y) * alpha;
  8799. this.z += (v.z - this.z) * alpha;
  8800. return this;
  8801. };
  8802. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  8803. this.x = v1.x + (v2.x - v1.x) * alpha;
  8804. this.y = v1.y + (v2.y - v1.y) * alpha;
  8805. this.z = v1.z + (v2.z - v1.z) * alpha;
  8806. return this;
  8807. };
  8808. _proto.cross = function cross(v, w) {
  8809. if (w !== undefined) {
  8810. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  8811. return this.crossVectors(v, w);
  8812. }
  8813. return this.crossVectors(this, v);
  8814. };
  8815. _proto.crossVectors = function crossVectors(a, b) {
  8816. var ax = a.x,
  8817. ay = a.y,
  8818. az = a.z;
  8819. var bx = b.x,
  8820. by = b.y,
  8821. bz = b.z;
  8822. this.x = ay * bz - az * by;
  8823. this.y = az * bx - ax * bz;
  8824. this.z = ax * by - ay * bx;
  8825. return this;
  8826. };
  8827. _proto.projectOnVector = function projectOnVector(v) {
  8828. var denominator = v.lengthSq();
  8829. if (denominator === 0) return this.set(0, 0, 0);
  8830. var scalar = v.dot(this) / denominator;
  8831. return this.copy(v).multiplyScalar(scalar);
  8832. };
  8833. _proto.projectOnPlane = function projectOnPlane(planeNormal) {
  8834. _vector.copy(this).projectOnVector(planeNormal);
  8835. return this.sub(_vector);
  8836. };
  8837. _proto.reflect = function reflect(normal) {
  8838. // reflect incident vector off plane orthogonal to normal
  8839. // normal is assumed to have unit length
  8840. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  8841. };
  8842. _proto.angleTo = function angleTo(v) {
  8843. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  8844. if (denominator === 0) return Math.PI / 2;
  8845. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  8846. return Math.acos(MathUtils.clamp(theta, -1, 1));
  8847. };
  8848. _proto.distanceTo = function distanceTo(v) {
  8849. return Math.sqrt(this.distanceToSquared(v));
  8850. };
  8851. _proto.distanceToSquared = function distanceToSquared(v) {
  8852. var dx = this.x - v.x,
  8853. dy = this.y - v.y,
  8854. dz = this.z - v.z;
  8855. return dx * dx + dy * dy + dz * dz;
  8856. };
  8857. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  8858. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  8859. };
  8860. _proto.setFromSpherical = function setFromSpherical(s) {
  8861. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  8862. };
  8863. _proto.setFromSphericalCoords = function setFromSphericalCoords(radius, phi, theta) {
  8864. var sinPhiRadius = Math.sin(phi) * radius;
  8865. this.x = sinPhiRadius * Math.sin(theta);
  8866. this.y = Math.cos(phi) * radius;
  8867. this.z = sinPhiRadius * Math.cos(theta);
  8868. return this;
  8869. };
  8870. _proto.setFromCylindrical = function setFromCylindrical(c) {
  8871. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  8872. };
  8873. _proto.setFromCylindricalCoords = function setFromCylindricalCoords(radius, theta, y) {
  8874. this.x = radius * Math.sin(theta);
  8875. this.y = y;
  8876. this.z = radius * Math.cos(theta);
  8877. return this;
  8878. };
  8879. _proto.setFromMatrixPosition = function setFromMatrixPosition(m) {
  8880. var e = m.elements;
  8881. this.x = e[12];
  8882. this.y = e[13];
  8883. this.z = e[14];
  8884. return this;
  8885. };
  8886. _proto.setFromMatrixScale = function setFromMatrixScale(m) {
  8887. var sx = this.setFromMatrixColumn(m, 0).length();
  8888. var sy = this.setFromMatrixColumn(m, 1).length();
  8889. var sz = this.setFromMatrixColumn(m, 2).length();
  8890. this.x = sx;
  8891. this.y = sy;
  8892. this.z = sz;
  8893. return this;
  8894. };
  8895. _proto.setFromMatrixColumn = function setFromMatrixColumn(m, index) {
  8896. return this.fromArray(m.elements, index * 4);
  8897. };
  8898. _proto.setFromMatrix3Column = function setFromMatrix3Column(m, index) {
  8899. return this.fromArray(m.elements, index * 3);
  8900. };
  8901. _proto.equals = function equals(v) {
  8902. return v.x === this.x && v.y === this.y && v.z === this.z;
  8903. };
  8904. _proto.fromArray = function fromArray(array, offset) {
  8905. if (offset === void 0) {
  8906. offset = 0;
  8907. }
  8908. this.x = array[offset];
  8909. this.y = array[offset + 1];
  8910. this.z = array[offset + 2];
  8911. return this;
  8912. };
  8913. _proto.toArray = function toArray(array, offset) {
  8914. if (array === void 0) {
  8915. array = [];
  8916. }
  8917. if (offset === void 0) {
  8918. offset = 0;
  8919. }
  8920. array[offset] = this.x;
  8921. array[offset + 1] = this.y;
  8922. array[offset + 2] = this.z;
  8923. return array;
  8924. };
  8925. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  8926. if (offset !== undefined) {
  8927. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  8928. }
  8929. this.x = attribute.getX(index);
  8930. this.y = attribute.getY(index);
  8931. this.z = attribute.getZ(index);
  8932. return this;
  8933. };
  8934. _proto.random = function random() {
  8935. this.x = Math.random();
  8936. this.y = Math.random();
  8937. this.z = Math.random();
  8938. return this;
  8939. };
  8940. return Vector3;
  8941. }();
  8942. var _vector = /*@__PURE__*/new Vector3();
  8943. var _quaternion = /*@__PURE__*/new Quaternion();
  8944. var Box3 = /*#__PURE__*/function () {
  8945. function Box3(min, max) {
  8946. Object.defineProperty(this, 'isBox3', {
  8947. value: true
  8948. });
  8949. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  8950. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  8951. }
  8952. var _proto = Box3.prototype;
  8953. _proto.set = function set(min, max) {
  8954. this.min.copy(min);
  8955. this.max.copy(max);
  8956. return this;
  8957. };
  8958. _proto.setFromArray = function setFromArray(array) {
  8959. var minX = +Infinity;
  8960. var minY = +Infinity;
  8961. var minZ = +Infinity;
  8962. var maxX = -Infinity;
  8963. var maxY = -Infinity;
  8964. var maxZ = -Infinity;
  8965. for (var i = 0, l = array.length; i < l; i += 3) {
  8966. var x = array[i];
  8967. var y = array[i + 1];
  8968. var z = array[i + 2];
  8969. if (x < minX) minX = x;
  8970. if (y < minY) minY = y;
  8971. if (z < minZ) minZ = z;
  8972. if (x > maxX) maxX = x;
  8973. if (y > maxY) maxY = y;
  8974. if (z > maxZ) maxZ = z;
  8975. }
  8976. this.min.set(minX, minY, minZ);
  8977. this.max.set(maxX, maxY, maxZ);
  8978. return this;
  8979. };
  8980. _proto.setFromBufferAttribute = function setFromBufferAttribute(attribute) {
  8981. var minX = +Infinity;
  8982. var minY = +Infinity;
  8983. var minZ = +Infinity;
  8984. var maxX = -Infinity;
  8985. var maxY = -Infinity;
  8986. var maxZ = -Infinity;
  8987. for (var i = 0, l = attribute.count; i < l; i++) {
  8988. var x = attribute.getX(i);
  8989. var y = attribute.getY(i);
  8990. var z = attribute.getZ(i);
  8991. if (x < minX) minX = x;
  8992. if (y < minY) minY = y;
  8993. if (z < minZ) minZ = z;
  8994. if (x > maxX) maxX = x;
  8995. if (y > maxY) maxY = y;
  8996. if (z > maxZ) maxZ = z;
  8997. }
  8998. this.min.set(minX, minY, minZ);
  8999. this.max.set(maxX, maxY, maxZ);
  9000. return this;
  9001. };
  9002. _proto.setFromPoints = function setFromPoints(points) {
  9003. this.makeEmpty();
  9004. for (var i = 0, il = points.length; i < il; i++) {
  9005. this.expandByPoint(points[i]);
  9006. }
  9007. return this;
  9008. };
  9009. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  9010. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  9011. this.min.copy(center).sub(halfSize);
  9012. this.max.copy(center).add(halfSize);
  9013. return this;
  9014. };
  9015. _proto.setFromObject = function setFromObject(object) {
  9016. this.makeEmpty();
  9017. return this.expandByObject(object);
  9018. };
  9019. _proto.clone = function clone() {
  9020. return new this.constructor().copy(this);
  9021. };
  9022. _proto.copy = function copy(box) {
  9023. this.min.copy(box.min);
  9024. this.max.copy(box.max);
  9025. return this;
  9026. };
  9027. _proto.makeEmpty = function makeEmpty() {
  9028. this.min.x = this.min.y = this.min.z = +Infinity;
  9029. this.max.x = this.max.y = this.max.z = -Infinity;
  9030. return this;
  9031. };
  9032. _proto.isEmpty = function isEmpty() {
  9033. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9034. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  9035. };
  9036. _proto.getCenter = function getCenter(target) {
  9037. if (target === undefined) {
  9038. console.warn('THREE.Box3: .getCenter() target is now required');
  9039. target = new Vector3();
  9040. }
  9041. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  9042. };
  9043. _proto.getSize = function getSize(target) {
  9044. if (target === undefined) {
  9045. console.warn('THREE.Box3: .getSize() target is now required');
  9046. target = new Vector3();
  9047. }
  9048. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  9049. };
  9050. _proto.expandByPoint = function expandByPoint(point) {
  9051. this.min.min(point);
  9052. this.max.max(point);
  9053. return this;
  9054. };
  9055. _proto.expandByVector = function expandByVector(vector) {
  9056. this.min.sub(vector);
  9057. this.max.add(vector);
  9058. return this;
  9059. };
  9060. _proto.expandByScalar = function expandByScalar(scalar) {
  9061. this.min.addScalar(-scalar);
  9062. this.max.addScalar(scalar);
  9063. return this;
  9064. };
  9065. _proto.expandByObject = function expandByObject(object) {
  9066. // Computes the world-axis-aligned bounding box of an object (including its children),
  9067. // accounting for both the object's, and children's, world transforms
  9068. object.updateWorldMatrix(false, false);
  9069. var geometry = object.geometry;
  9070. if (geometry !== undefined) {
  9071. if (geometry.boundingBox === null) {
  9072. geometry.computeBoundingBox();
  9073. }
  9074. _box.copy(geometry.boundingBox);
  9075. _box.applyMatrix4(object.matrixWorld);
  9076. this.union(_box);
  9077. }
  9078. var children = object.children;
  9079. for (var i = 0, l = children.length; i < l; i++) {
  9080. this.expandByObject(children[i]);
  9081. }
  9082. return this;
  9083. };
  9084. _proto.containsPoint = function containsPoint(point) {
  9085. 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;
  9086. };
  9087. _proto.containsBox = function containsBox(box) {
  9088. 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;
  9089. };
  9090. _proto.getParameter = function getParameter(point, target) {
  9091. // This can potentially have a divide by zero if the box
  9092. // has a size dimension of 0.
  9093. if (target === undefined) {
  9094. console.warn('THREE.Box3: .getParameter() target is now required');
  9095. target = new Vector3();
  9096. }
  9097. 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));
  9098. };
  9099. _proto.intersectsBox = function intersectsBox(box) {
  9100. // using 6 splitting planes to rule out intersections.
  9101. 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;
  9102. };
  9103. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9104. // Find the point on the AABB closest to the sphere center.
  9105. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  9106. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  9107. };
  9108. _proto.intersectsPlane = function intersectsPlane(plane) {
  9109. // We compute the minimum and maximum dot product values. If those values
  9110. // are on the same side (back or front) of the plane, then there is no intersection.
  9111. var min, max;
  9112. if (plane.normal.x > 0) {
  9113. min = plane.normal.x * this.min.x;
  9114. max = plane.normal.x * this.max.x;
  9115. } else {
  9116. min = plane.normal.x * this.max.x;
  9117. max = plane.normal.x * this.min.x;
  9118. }
  9119. if (plane.normal.y > 0) {
  9120. min += plane.normal.y * this.min.y;
  9121. max += plane.normal.y * this.max.y;
  9122. } else {
  9123. min += plane.normal.y * this.max.y;
  9124. max += plane.normal.y * this.min.y;
  9125. }
  9126. if (plane.normal.z > 0) {
  9127. min += plane.normal.z * this.min.z;
  9128. max += plane.normal.z * this.max.z;
  9129. } else {
  9130. min += plane.normal.z * this.max.z;
  9131. max += plane.normal.z * this.min.z;
  9132. }
  9133. return min <= -plane.constant && max >= -plane.constant;
  9134. };
  9135. _proto.intersectsTriangle = function intersectsTriangle(triangle) {
  9136. if (this.isEmpty()) {
  9137. return false;
  9138. } // compute box center and extents
  9139. this.getCenter(_center);
  9140. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  9141. _v0.subVectors(triangle.a, _center);
  9142. _v1.subVectors(triangle.b, _center);
  9143. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  9144. _f0.subVectors(_v1, _v0);
  9145. _f1.subVectors(_v2, _v1);
  9146. _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
  9147. // 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
  9148. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  9149. 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];
  9150. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  9151. return false;
  9152. } // test 3 face normals from the aabb
  9153. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  9154. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  9155. return false;
  9156. } // finally testing the face normal of the triangle
  9157. // use already existing triangle edge vectors here
  9158. _triangleNormal.crossVectors(_f0, _f1);
  9159. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  9160. return satForAxes(axes, _v0, _v1, _v2, _extents);
  9161. };
  9162. _proto.clampPoint = function clampPoint(point, target) {
  9163. if (target === undefined) {
  9164. console.warn('THREE.Box3: .clampPoint() target is now required');
  9165. target = new Vector3();
  9166. }
  9167. return target.copy(point).clamp(this.min, this.max);
  9168. };
  9169. _proto.distanceToPoint = function distanceToPoint(point) {
  9170. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  9171. return clampedPoint.sub(point).length();
  9172. };
  9173. _proto.getBoundingSphere = function getBoundingSphere(target) {
  9174. if (target === undefined) {
  9175. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  9176. }
  9177. this.getCenter(target.center);
  9178. target.radius = this.getSize(_vector$1).length() * 0.5;
  9179. return target;
  9180. };
  9181. _proto.intersect = function intersect(box) {
  9182. this.min.max(box.min);
  9183. 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.
  9184. if (this.isEmpty()) this.makeEmpty();
  9185. return this;
  9186. };
  9187. _proto.union = function union(box) {
  9188. this.min.min(box.min);
  9189. this.max.max(box.max);
  9190. return this;
  9191. };
  9192. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  9193. // transform of empty box is an empty box.
  9194. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9195. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  9196. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  9197. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  9198. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  9199. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  9200. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  9201. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  9202. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  9203. this.setFromPoints(_points);
  9204. return this;
  9205. };
  9206. _proto.translate = function translate(offset) {
  9207. this.min.add(offset);
  9208. this.max.add(offset);
  9209. return this;
  9210. };
  9211. _proto.equals = function equals(box) {
  9212. return box.min.equals(this.min) && box.max.equals(this.max);
  9213. };
  9214. return Box3;
  9215. }();
  9216. function satForAxes(axes, v0, v1, v2, extents) {
  9217. for (var i = 0, j = axes.length - 3; i <= j; i += 3) {
  9218. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  9219. 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
  9220. var p0 = v0.dot(_testAxis);
  9221. var p1 = v1.dot(_testAxis);
  9222. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  9223. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  9224. // points of the projected triangle are outside the projected half-length of the aabb
  9225. // the axis is seperating and we can exit
  9226. return false;
  9227. }
  9228. }
  9229. return true;
  9230. }
  9231. 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()];
  9232. var _vector$1 = /*@__PURE__*/new Vector3();
  9233. var _box = /*@__PURE__*/new Box3(); // triangle centered vertices
  9234. var _v0 = /*@__PURE__*/new Vector3();
  9235. var _v1 = /*@__PURE__*/new Vector3();
  9236. var _v2 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  9237. var _f0 = /*@__PURE__*/new Vector3();
  9238. var _f1 = /*@__PURE__*/new Vector3();
  9239. var _f2 = /*@__PURE__*/new Vector3();
  9240. var _center = /*@__PURE__*/new Vector3();
  9241. var _extents = /*@__PURE__*/new Vector3();
  9242. var _triangleNormal = /*@__PURE__*/new Vector3();
  9243. var _testAxis = /*@__PURE__*/new Vector3();
  9244. var _box$1 = /*@__PURE__*/new Box3();
  9245. var Sphere = /*#__PURE__*/function () {
  9246. function Sphere(center, radius) {
  9247. this.center = center !== undefined ? center : new Vector3();
  9248. this.radius = radius !== undefined ? radius : -1;
  9249. }
  9250. var _proto = Sphere.prototype;
  9251. _proto.set = function set(center, radius) {
  9252. this.center.copy(center);
  9253. this.radius = radius;
  9254. return this;
  9255. };
  9256. _proto.setFromPoints = function setFromPoints(points, optionalCenter) {
  9257. var center = this.center;
  9258. if (optionalCenter !== undefined) {
  9259. center.copy(optionalCenter);
  9260. } else {
  9261. _box$1.setFromPoints(points).getCenter(center);
  9262. }
  9263. var maxRadiusSq = 0;
  9264. for (var i = 0, il = points.length; i < il; i++) {
  9265. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  9266. }
  9267. this.radius = Math.sqrt(maxRadiusSq);
  9268. return this;
  9269. };
  9270. _proto.clone = function clone() {
  9271. return new this.constructor().copy(this);
  9272. };
  9273. _proto.copy = function copy(sphere) {
  9274. this.center.copy(sphere.center);
  9275. this.radius = sphere.radius;
  9276. return this;
  9277. };
  9278. _proto.isEmpty = function isEmpty() {
  9279. return this.radius < 0;
  9280. };
  9281. _proto.makeEmpty = function makeEmpty() {
  9282. this.center.set(0, 0, 0);
  9283. this.radius = -1;
  9284. return this;
  9285. };
  9286. _proto.containsPoint = function containsPoint(point) {
  9287. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  9288. };
  9289. _proto.distanceToPoint = function distanceToPoint(point) {
  9290. return point.distanceTo(this.center) - this.radius;
  9291. };
  9292. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9293. var radiusSum = this.radius + sphere.radius;
  9294. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  9295. };
  9296. _proto.intersectsBox = function intersectsBox(box) {
  9297. return box.intersectsSphere(this);
  9298. };
  9299. _proto.intersectsPlane = function intersectsPlane(plane) {
  9300. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  9301. };
  9302. _proto.clampPoint = function clampPoint(point, target) {
  9303. var deltaLengthSq = this.center.distanceToSquared(point);
  9304. if (target === undefined) {
  9305. console.warn('THREE.Sphere: .clampPoint() target is now required');
  9306. target = new Vector3();
  9307. }
  9308. target.copy(point);
  9309. if (deltaLengthSq > this.radius * this.radius) {
  9310. target.sub(this.center).normalize();
  9311. target.multiplyScalar(this.radius).add(this.center);
  9312. }
  9313. return target;
  9314. };
  9315. _proto.getBoundingBox = function getBoundingBox(target) {
  9316. if (target === undefined) {
  9317. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  9318. target = new Box3();
  9319. }
  9320. if (this.isEmpty()) {
  9321. // Empty sphere produces empty bounding box
  9322. target.makeEmpty();
  9323. return target;
  9324. }
  9325. target.set(this.center, this.center);
  9326. target.expandByScalar(this.radius);
  9327. return target;
  9328. };
  9329. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  9330. this.center.applyMatrix4(matrix);
  9331. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9332. return this;
  9333. };
  9334. _proto.translate = function translate(offset) {
  9335. this.center.add(offset);
  9336. return this;
  9337. };
  9338. _proto.equals = function equals(sphere) {
  9339. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  9340. };
  9341. return Sphere;
  9342. }();
  9343. var _vector$2 = /*@__PURE__*/new Vector3();
  9344. var _segCenter = /*@__PURE__*/new Vector3();
  9345. var _segDir = /*@__PURE__*/new Vector3();
  9346. var _diff = /*@__PURE__*/new Vector3();
  9347. var _edge1 = /*@__PURE__*/new Vector3();
  9348. var _edge2 = /*@__PURE__*/new Vector3();
  9349. var _normal = /*@__PURE__*/new Vector3();
  9350. var Ray = /*#__PURE__*/function () {
  9351. function Ray(origin, direction) {
  9352. this.origin = origin !== undefined ? origin : new Vector3();
  9353. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  9354. }
  9355. var _proto = Ray.prototype;
  9356. _proto.set = function set(origin, direction) {
  9357. this.origin.copy(origin);
  9358. this.direction.copy(direction);
  9359. return this;
  9360. };
  9361. _proto.clone = function clone() {
  9362. return new this.constructor().copy(this);
  9363. };
  9364. _proto.copy = function copy(ray) {
  9365. this.origin.copy(ray.origin);
  9366. this.direction.copy(ray.direction);
  9367. return this;
  9368. };
  9369. _proto.at = function at(t, target) {
  9370. if (target === undefined) {
  9371. console.warn('THREE.Ray: .at() target is now required');
  9372. target = new Vector3();
  9373. }
  9374. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  9375. };
  9376. _proto.lookAt = function lookAt(v) {
  9377. this.direction.copy(v).sub(this.origin).normalize();
  9378. return this;
  9379. };
  9380. _proto.recast = function recast(t) {
  9381. this.origin.copy(this.at(t, _vector$2));
  9382. return this;
  9383. };
  9384. _proto.closestPointToPoint = function closestPointToPoint(point, target) {
  9385. if (target === undefined) {
  9386. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  9387. target = new Vector3();
  9388. }
  9389. target.subVectors(point, this.origin);
  9390. var directionDistance = target.dot(this.direction);
  9391. if (directionDistance < 0) {
  9392. return target.copy(this.origin);
  9393. }
  9394. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  9395. };
  9396. _proto.distanceToPoint = function distanceToPoint(point) {
  9397. return Math.sqrt(this.distanceSqToPoint(point));
  9398. };
  9399. _proto.distanceSqToPoint = function distanceSqToPoint(point) {
  9400. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  9401. if (directionDistance < 0) {
  9402. return this.origin.distanceToSquared(point);
  9403. }
  9404. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  9405. return _vector$2.distanceToSquared(point);
  9406. };
  9407. _proto.distanceSqToSegment = function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  9408. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9409. // It returns the min distance between the ray and the segment
  9410. // defined by v0 and v1
  9411. // It can also set two optional targets :
  9412. // - The closest point on the ray
  9413. // - The closest point on the segment
  9414. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  9415. _segDir.copy(v1).sub(v0).normalize();
  9416. _diff.copy(this.origin).sub(_segCenter);
  9417. var segExtent = v0.distanceTo(v1) * 0.5;
  9418. var a01 = -this.direction.dot(_segDir);
  9419. var b0 = _diff.dot(this.direction);
  9420. var b1 = -_diff.dot(_segDir);
  9421. var c = _diff.lengthSq();
  9422. var det = Math.abs(1 - a01 * a01);
  9423. var s0, s1, sqrDist, extDet;
  9424. if (det > 0) {
  9425. // The ray and segment are not parallel.
  9426. s0 = a01 * b1 - b0;
  9427. s1 = a01 * b0 - b1;
  9428. extDet = segExtent * det;
  9429. if (s0 >= 0) {
  9430. if (s1 >= -extDet) {
  9431. if (s1 <= extDet) {
  9432. // region 0
  9433. // Minimum at interior points of ray and segment.
  9434. var invDet = 1 / det;
  9435. s0 *= invDet;
  9436. s1 *= invDet;
  9437. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  9438. } else {
  9439. // region 1
  9440. s1 = segExtent;
  9441. s0 = Math.max(0, -(a01 * s1 + b0));
  9442. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9443. }
  9444. } else {
  9445. // region 5
  9446. s1 = -segExtent;
  9447. s0 = Math.max(0, -(a01 * s1 + b0));
  9448. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9449. }
  9450. } else {
  9451. if (s1 <= -extDet) {
  9452. // region 4
  9453. s0 = Math.max(0, -(-a01 * segExtent + b0));
  9454. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  9455. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9456. } else if (s1 <= extDet) {
  9457. // region 3
  9458. s0 = 0;
  9459. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  9460. sqrDist = s1 * (s1 + 2 * b1) + c;
  9461. } else {
  9462. // region 2
  9463. s0 = Math.max(0, -(a01 * segExtent + b0));
  9464. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  9465. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9466. }
  9467. }
  9468. } else {
  9469. // Ray and segment are parallel.
  9470. s1 = a01 > 0 ? -segExtent : segExtent;
  9471. s0 = Math.max(0, -(a01 * s1 + b0));
  9472. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9473. }
  9474. if (optionalPointOnRay) {
  9475. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  9476. }
  9477. if (optionalPointOnSegment) {
  9478. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  9479. }
  9480. return sqrDist;
  9481. };
  9482. _proto.intersectSphere = function intersectSphere(sphere, target) {
  9483. _vector$2.subVectors(sphere.center, this.origin);
  9484. var tca = _vector$2.dot(this.direction);
  9485. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  9486. var radius2 = sphere.radius * sphere.radius;
  9487. if (d2 > radius2) return null;
  9488. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  9489. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  9490. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  9491. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  9492. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9493. // in order to always return an intersect point that is in front of the ray.
  9494. 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
  9495. return this.at(t0, target);
  9496. };
  9497. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9498. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  9499. };
  9500. _proto.distanceToPlane = function distanceToPlane(plane) {
  9501. var denominator = plane.normal.dot(this.direction);
  9502. if (denominator === 0) {
  9503. // line is coplanar, return origin
  9504. if (plane.distanceToPoint(this.origin) === 0) {
  9505. return 0;
  9506. } // Null is preferable to undefined since undefined means.... it is undefined
  9507. return null;
  9508. }
  9509. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  9510. return t >= 0 ? t : null;
  9511. };
  9512. _proto.intersectPlane = function intersectPlane(plane, target) {
  9513. var t = this.distanceToPlane(plane);
  9514. if (t === null) {
  9515. return null;
  9516. }
  9517. return this.at(t, target);
  9518. };
  9519. _proto.intersectsPlane = function intersectsPlane(plane) {
  9520. // check if the ray lies on the plane first
  9521. var distToPoint = plane.distanceToPoint(this.origin);
  9522. if (distToPoint === 0) {
  9523. return true;
  9524. }
  9525. var denominator = plane.normal.dot(this.direction);
  9526. if (denominator * distToPoint < 0) {
  9527. return true;
  9528. } // ray origin is behind the plane (and is pointing behind it)
  9529. return false;
  9530. };
  9531. _proto.intersectBox = function intersectBox(box, target) {
  9532. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9533. var invdirx = 1 / this.direction.x,
  9534. invdiry = 1 / this.direction.y,
  9535. invdirz = 1 / this.direction.z;
  9536. var origin = this.origin;
  9537. if (invdirx >= 0) {
  9538. tmin = (box.min.x - origin.x) * invdirx;
  9539. tmax = (box.max.x - origin.x) * invdirx;
  9540. } else {
  9541. tmin = (box.max.x - origin.x) * invdirx;
  9542. tmax = (box.min.x - origin.x) * invdirx;
  9543. }
  9544. if (invdiry >= 0) {
  9545. tymin = (box.min.y - origin.y) * invdiry;
  9546. tymax = (box.max.y - origin.y) * invdiry;
  9547. } else {
  9548. tymin = (box.max.y - origin.y) * invdiry;
  9549. tymax = (box.min.y - origin.y) * invdiry;
  9550. }
  9551. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  9552. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9553. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  9554. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  9555. if (invdirz >= 0) {
  9556. tzmin = (box.min.z - origin.z) * invdirz;
  9557. tzmax = (box.max.z - origin.z) * invdirz;
  9558. } else {
  9559. tzmin = (box.max.z - origin.z) * invdirz;
  9560. tzmax = (box.min.z - origin.z) * invdirz;
  9561. }
  9562. if (tmin > tzmax || tzmin > tmax) return null;
  9563. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  9564. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  9565. if (tmax < 0) return null;
  9566. return this.at(tmin >= 0 ? tmin : tmax, target);
  9567. };
  9568. _proto.intersectsBox = function intersectsBox(box) {
  9569. return this.intersectBox(box, _vector$2) !== null;
  9570. };
  9571. _proto.intersectTriangle = function intersectTriangle(a, b, c, backfaceCulling, target) {
  9572. // Compute the offset origin, edges, and normal.
  9573. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9574. _edge1.subVectors(b, a);
  9575. _edge2.subVectors(c, a);
  9576. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9577. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9578. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9579. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9580. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9581. var DdN = this.direction.dot(_normal);
  9582. var sign;
  9583. if (DdN > 0) {
  9584. if (backfaceCulling) return null;
  9585. sign = 1;
  9586. } else if (DdN < 0) {
  9587. sign = -1;
  9588. DdN = -DdN;
  9589. } else {
  9590. return null;
  9591. }
  9592. _diff.subVectors(this.origin, a);
  9593. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  9594. if (DdQxE2 < 0) {
  9595. return null;
  9596. }
  9597. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  9598. if (DdE1xQ < 0) {
  9599. return null;
  9600. } // b1+b2 > 1, no intersection
  9601. if (DdQxE2 + DdE1xQ > DdN) {
  9602. return null;
  9603. } // Line intersects triangle, check if ray does.
  9604. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  9605. if (QdN < 0) {
  9606. return null;
  9607. } // Ray intersects triangle.
  9608. return this.at(QdN / DdN, target);
  9609. };
  9610. _proto.applyMatrix4 = function applyMatrix4(matrix4) {
  9611. this.origin.applyMatrix4(matrix4);
  9612. this.direction.transformDirection(matrix4);
  9613. return this;
  9614. };
  9615. _proto.equals = function equals(ray) {
  9616. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  9617. };
  9618. return Ray;
  9619. }();
  9620. var Matrix4 = /*#__PURE__*/function () {
  9621. function Matrix4() {
  9622. Object.defineProperty(this, 'isMatrix4', {
  9623. value: true
  9624. });
  9625. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  9626. if (arguments.length > 0) {
  9627. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  9628. }
  9629. }
  9630. var _proto = Matrix4.prototype;
  9631. _proto.set = function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  9632. var te = this.elements;
  9633. te[0] = n11;
  9634. te[4] = n12;
  9635. te[8] = n13;
  9636. te[12] = n14;
  9637. te[1] = n21;
  9638. te[5] = n22;
  9639. te[9] = n23;
  9640. te[13] = n24;
  9641. te[2] = n31;
  9642. te[6] = n32;
  9643. te[10] = n33;
  9644. te[14] = n34;
  9645. te[3] = n41;
  9646. te[7] = n42;
  9647. te[11] = n43;
  9648. te[15] = n44;
  9649. return this;
  9650. };
  9651. _proto.identity = function identity() {
  9652. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  9653. return this;
  9654. };
  9655. _proto.clone = function clone() {
  9656. return new Matrix4().fromArray(this.elements);
  9657. };
  9658. _proto.copy = function copy(m) {
  9659. var te = this.elements;
  9660. var me = m.elements;
  9661. te[0] = me[0];
  9662. te[1] = me[1];
  9663. te[2] = me[2];
  9664. te[3] = me[3];
  9665. te[4] = me[4];
  9666. te[5] = me[5];
  9667. te[6] = me[6];
  9668. te[7] = me[7];
  9669. te[8] = me[8];
  9670. te[9] = me[9];
  9671. te[10] = me[10];
  9672. te[11] = me[11];
  9673. te[12] = me[12];
  9674. te[13] = me[13];
  9675. te[14] = me[14];
  9676. te[15] = me[15];
  9677. return this;
  9678. };
  9679. _proto.copyPosition = function copyPosition(m) {
  9680. var te = this.elements,
  9681. me = m.elements;
  9682. te[12] = me[12];
  9683. te[13] = me[13];
  9684. te[14] = me[14];
  9685. return this;
  9686. };
  9687. _proto.setFromMatrix3 = function setFromMatrix3(m) {
  9688. var me = m.elements;
  9689. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  9690. return this;
  9691. };
  9692. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  9693. xAxis.setFromMatrixColumn(this, 0);
  9694. yAxis.setFromMatrixColumn(this, 1);
  9695. zAxis.setFromMatrixColumn(this, 2);
  9696. return this;
  9697. };
  9698. _proto.makeBasis = function makeBasis(xAxis, yAxis, zAxis) {
  9699. 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);
  9700. return this;
  9701. };
  9702. _proto.extractRotation = function extractRotation(m) {
  9703. // this method does not support reflection matrices
  9704. var te = this.elements;
  9705. var me = m.elements;
  9706. var scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  9707. var scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  9708. var scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  9709. te[0] = me[0] * scaleX;
  9710. te[1] = me[1] * scaleX;
  9711. te[2] = me[2] * scaleX;
  9712. te[3] = 0;
  9713. te[4] = me[4] * scaleY;
  9714. te[5] = me[5] * scaleY;
  9715. te[6] = me[6] * scaleY;
  9716. te[7] = 0;
  9717. te[8] = me[8] * scaleZ;
  9718. te[9] = me[9] * scaleZ;
  9719. te[10] = me[10] * scaleZ;
  9720. te[11] = 0;
  9721. te[12] = 0;
  9722. te[13] = 0;
  9723. te[14] = 0;
  9724. te[15] = 1;
  9725. return this;
  9726. };
  9727. _proto.makeRotationFromEuler = function makeRotationFromEuler(euler) {
  9728. if (!(euler && euler.isEuler)) {
  9729. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  9730. }
  9731. var te = this.elements;
  9732. var x = euler.x,
  9733. y = euler.y,
  9734. z = euler.z;
  9735. var a = Math.cos(x),
  9736. b = Math.sin(x);
  9737. var c = Math.cos(y),
  9738. d = Math.sin(y);
  9739. var e = Math.cos(z),
  9740. f = Math.sin(z);
  9741. if (euler.order === 'XYZ') {
  9742. var ae = a * e,
  9743. af = a * f,
  9744. be = b * e,
  9745. bf = b * f;
  9746. te[0] = c * e;
  9747. te[4] = -c * f;
  9748. te[8] = d;
  9749. te[1] = af + be * d;
  9750. te[5] = ae - bf * d;
  9751. te[9] = -b * c;
  9752. te[2] = bf - ae * d;
  9753. te[6] = be + af * d;
  9754. te[10] = a * c;
  9755. } else if (euler.order === 'YXZ') {
  9756. var ce = c * e,
  9757. cf = c * f,
  9758. de = d * e,
  9759. df = d * f;
  9760. te[0] = ce + df * b;
  9761. te[4] = de * b - cf;
  9762. te[8] = a * d;
  9763. te[1] = a * f;
  9764. te[5] = a * e;
  9765. te[9] = -b;
  9766. te[2] = cf * b - de;
  9767. te[6] = df + ce * b;
  9768. te[10] = a * c;
  9769. } else if (euler.order === 'ZXY') {
  9770. var _ce = c * e,
  9771. _cf = c * f,
  9772. _de = d * e,
  9773. _df = d * f;
  9774. te[0] = _ce - _df * b;
  9775. te[4] = -a * f;
  9776. te[8] = _de + _cf * b;
  9777. te[1] = _cf + _de * b;
  9778. te[5] = a * e;
  9779. te[9] = _df - _ce * b;
  9780. te[2] = -a * d;
  9781. te[6] = b;
  9782. te[10] = a * c;
  9783. } else if (euler.order === 'ZYX') {
  9784. var _ae = a * e,
  9785. _af = a * f,
  9786. _be = b * e,
  9787. _bf = b * f;
  9788. te[0] = c * e;
  9789. te[4] = _be * d - _af;
  9790. te[8] = _ae * d + _bf;
  9791. te[1] = c * f;
  9792. te[5] = _bf * d + _ae;
  9793. te[9] = _af * d - _be;
  9794. te[2] = -d;
  9795. te[6] = b * c;
  9796. te[10] = a * c;
  9797. } else if (euler.order === 'YZX') {
  9798. var ac = a * c,
  9799. ad = a * d,
  9800. bc = b * c,
  9801. bd = b * d;
  9802. te[0] = c * e;
  9803. te[4] = bd - ac * f;
  9804. te[8] = bc * f + ad;
  9805. te[1] = f;
  9806. te[5] = a * e;
  9807. te[9] = -b * e;
  9808. te[2] = -d * e;
  9809. te[6] = ad * f + bc;
  9810. te[10] = ac - bd * f;
  9811. } else if (euler.order === 'XZY') {
  9812. var _ac = a * c,
  9813. _ad = a * d,
  9814. _bc = b * c,
  9815. _bd = b * d;
  9816. te[0] = c * e;
  9817. te[4] = -f;
  9818. te[8] = d * e;
  9819. te[1] = _ac * f + _bd;
  9820. te[5] = a * e;
  9821. te[9] = _ad * f - _bc;
  9822. te[2] = _bc * f - _ad;
  9823. te[6] = b * e;
  9824. te[10] = _bd * f + _ac;
  9825. } // bottom row
  9826. te[3] = 0;
  9827. te[7] = 0;
  9828. te[11] = 0; // last column
  9829. te[12] = 0;
  9830. te[13] = 0;
  9831. te[14] = 0;
  9832. te[15] = 1;
  9833. return this;
  9834. };
  9835. _proto.makeRotationFromQuaternion = function makeRotationFromQuaternion(q) {
  9836. return this.compose(_zero, q, _one);
  9837. };
  9838. _proto.lookAt = function lookAt(eye, target, up) {
  9839. var te = this.elements;
  9840. _z.subVectors(eye, target);
  9841. if (_z.lengthSq() === 0) {
  9842. // eye and target are in the same position
  9843. _z.z = 1;
  9844. }
  9845. _z.normalize();
  9846. _x.crossVectors(up, _z);
  9847. if (_x.lengthSq() === 0) {
  9848. // up and z are parallel
  9849. if (Math.abs(up.z) === 1) {
  9850. _z.x += 0.0001;
  9851. } else {
  9852. _z.z += 0.0001;
  9853. }
  9854. _z.normalize();
  9855. _x.crossVectors(up, _z);
  9856. }
  9857. _x.normalize();
  9858. _y.crossVectors(_z, _x);
  9859. te[0] = _x.x;
  9860. te[4] = _y.x;
  9861. te[8] = _z.x;
  9862. te[1] = _x.y;
  9863. te[5] = _y.y;
  9864. te[9] = _z.y;
  9865. te[2] = _x.z;
  9866. te[6] = _y.z;
  9867. te[10] = _z.z;
  9868. return this;
  9869. };
  9870. _proto.multiply = function multiply(m, n) {
  9871. if (n !== undefined) {
  9872. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  9873. return this.multiplyMatrices(m, n);
  9874. }
  9875. return this.multiplyMatrices(this, m);
  9876. };
  9877. _proto.premultiply = function premultiply(m) {
  9878. return this.multiplyMatrices(m, this);
  9879. };
  9880. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  9881. var ae = a.elements;
  9882. var be = b.elements;
  9883. var te = this.elements;
  9884. var a11 = ae[0],
  9885. a12 = ae[4],
  9886. a13 = ae[8],
  9887. a14 = ae[12];
  9888. var a21 = ae[1],
  9889. a22 = ae[5],
  9890. a23 = ae[9],
  9891. a24 = ae[13];
  9892. var a31 = ae[2],
  9893. a32 = ae[6],
  9894. a33 = ae[10],
  9895. a34 = ae[14];
  9896. var a41 = ae[3],
  9897. a42 = ae[7],
  9898. a43 = ae[11],
  9899. a44 = ae[15];
  9900. var b11 = be[0],
  9901. b12 = be[4],
  9902. b13 = be[8],
  9903. b14 = be[12];
  9904. var b21 = be[1],
  9905. b22 = be[5],
  9906. b23 = be[9],
  9907. b24 = be[13];
  9908. var b31 = be[2],
  9909. b32 = be[6],
  9910. b33 = be[10],
  9911. b34 = be[14];
  9912. var b41 = be[3],
  9913. b42 = be[7],
  9914. b43 = be[11],
  9915. b44 = be[15];
  9916. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9917. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9918. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9919. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9920. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9921. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9922. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9923. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9924. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9925. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9926. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9927. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9928. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9929. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9930. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9931. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9932. return this;
  9933. };
  9934. _proto.multiplyScalar = function multiplyScalar(s) {
  9935. var te = this.elements;
  9936. te[0] *= s;
  9937. te[4] *= s;
  9938. te[8] *= s;
  9939. te[12] *= s;
  9940. te[1] *= s;
  9941. te[5] *= s;
  9942. te[9] *= s;
  9943. te[13] *= s;
  9944. te[2] *= s;
  9945. te[6] *= s;
  9946. te[10] *= s;
  9947. te[14] *= s;
  9948. te[3] *= s;
  9949. te[7] *= s;
  9950. te[11] *= s;
  9951. te[15] *= s;
  9952. return this;
  9953. };
  9954. _proto.determinant = function determinant() {
  9955. var te = this.elements;
  9956. var n11 = te[0],
  9957. n12 = te[4],
  9958. n13 = te[8],
  9959. n14 = te[12];
  9960. var n21 = te[1],
  9961. n22 = te[5],
  9962. n23 = te[9],
  9963. n24 = te[13];
  9964. var n31 = te[2],
  9965. n32 = te[6],
  9966. n33 = te[10],
  9967. n34 = te[14];
  9968. var n41 = te[3],
  9969. n42 = te[7],
  9970. n43 = te[11],
  9971. n44 = te[15]; //TODO: make this more efficient
  9972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  9973. 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);
  9974. };
  9975. _proto.transpose = function transpose() {
  9976. var te = this.elements;
  9977. var tmp;
  9978. tmp = te[1];
  9979. te[1] = te[4];
  9980. te[4] = tmp;
  9981. tmp = te[2];
  9982. te[2] = te[8];
  9983. te[8] = tmp;
  9984. tmp = te[6];
  9985. te[6] = te[9];
  9986. te[9] = tmp;
  9987. tmp = te[3];
  9988. te[3] = te[12];
  9989. te[12] = tmp;
  9990. tmp = te[7];
  9991. te[7] = te[13];
  9992. te[13] = tmp;
  9993. tmp = te[11];
  9994. te[11] = te[14];
  9995. te[14] = tmp;
  9996. return this;
  9997. };
  9998. _proto.setPosition = function setPosition(x, y, z) {
  9999. var te = this.elements;
  10000. if (x.isVector3) {
  10001. te[12] = x.x;
  10002. te[13] = x.y;
  10003. te[14] = x.z;
  10004. } else {
  10005. te[12] = x;
  10006. te[13] = y;
  10007. te[14] = z;
  10008. }
  10009. return this;
  10010. };
  10011. _proto.invert = function invert() {
  10012. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  10013. var te = this.elements,
  10014. n11 = te[0],
  10015. n21 = te[1],
  10016. n31 = te[2],
  10017. n41 = te[3],
  10018. n12 = te[4],
  10019. n22 = te[5],
  10020. n32 = te[6],
  10021. n42 = te[7],
  10022. n13 = te[8],
  10023. n23 = te[9],
  10024. n33 = te[10],
  10025. n43 = te[11],
  10026. n14 = te[12],
  10027. n24 = te[13],
  10028. n34 = te[14],
  10029. n44 = te[15],
  10030. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  10031. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  10032. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  10033. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  10034. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  10035. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  10036. var detInv = 1 / det;
  10037. te[0] = t11 * detInv;
  10038. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  10039. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  10040. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  10041. te[4] = t12 * detInv;
  10042. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  10043. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  10044. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  10045. te[8] = t13 * detInv;
  10046. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  10047. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  10048. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  10049. te[12] = t14 * detInv;
  10050. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  10051. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  10052. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  10053. return this;
  10054. };
  10055. _proto.scale = function scale(v) {
  10056. var te = this.elements;
  10057. var x = v.x,
  10058. y = v.y,
  10059. z = v.z;
  10060. te[0] *= x;
  10061. te[4] *= y;
  10062. te[8] *= z;
  10063. te[1] *= x;
  10064. te[5] *= y;
  10065. te[9] *= z;
  10066. te[2] *= x;
  10067. te[6] *= y;
  10068. te[10] *= z;
  10069. te[3] *= x;
  10070. te[7] *= y;
  10071. te[11] *= z;
  10072. return this;
  10073. };
  10074. _proto.getMaxScaleOnAxis = function getMaxScaleOnAxis() {
  10075. var te = this.elements;
  10076. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  10077. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  10078. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  10079. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  10080. };
  10081. _proto.makeTranslation = function makeTranslation(x, y, z) {
  10082. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  10083. return this;
  10084. };
  10085. _proto.makeRotationX = function makeRotationX(theta) {
  10086. var c = Math.cos(theta),
  10087. s = Math.sin(theta);
  10088. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  10089. return this;
  10090. };
  10091. _proto.makeRotationY = function makeRotationY(theta) {
  10092. var c = Math.cos(theta),
  10093. s = Math.sin(theta);
  10094. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  10095. return this;
  10096. };
  10097. _proto.makeRotationZ = function makeRotationZ(theta) {
  10098. var c = Math.cos(theta),
  10099. s = Math.sin(theta);
  10100. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  10101. return this;
  10102. };
  10103. _proto.makeRotationAxis = function makeRotationAxis(axis, angle) {
  10104. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  10105. var c = Math.cos(angle);
  10106. var s = Math.sin(angle);
  10107. var t = 1 - c;
  10108. var x = axis.x,
  10109. y = axis.y,
  10110. z = axis.z;
  10111. var tx = t * x,
  10112. ty = t * y;
  10113. 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);
  10114. return this;
  10115. };
  10116. _proto.makeScale = function makeScale(x, y, z) {
  10117. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  10118. return this;
  10119. };
  10120. _proto.makeShear = function makeShear(x, y, z) {
  10121. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  10122. return this;
  10123. };
  10124. _proto.compose = function compose(position, quaternion, scale) {
  10125. var te = this.elements;
  10126. var x = quaternion._x,
  10127. y = quaternion._y,
  10128. z = quaternion._z,
  10129. w = quaternion._w;
  10130. var x2 = x + x,
  10131. y2 = y + y,
  10132. z2 = z + z;
  10133. var xx = x * x2,
  10134. xy = x * y2,
  10135. xz = x * z2;
  10136. var yy = y * y2,
  10137. yz = y * z2,
  10138. zz = z * z2;
  10139. var wx = w * x2,
  10140. wy = w * y2,
  10141. wz = w * z2;
  10142. var sx = scale.x,
  10143. sy = scale.y,
  10144. sz = scale.z;
  10145. te[0] = (1 - (yy + zz)) * sx;
  10146. te[1] = (xy + wz) * sx;
  10147. te[2] = (xz - wy) * sx;
  10148. te[3] = 0;
  10149. te[4] = (xy - wz) * sy;
  10150. te[5] = (1 - (xx + zz)) * sy;
  10151. te[6] = (yz + wx) * sy;
  10152. te[7] = 0;
  10153. te[8] = (xz + wy) * sz;
  10154. te[9] = (yz - wx) * sz;
  10155. te[10] = (1 - (xx + yy)) * sz;
  10156. te[11] = 0;
  10157. te[12] = position.x;
  10158. te[13] = position.y;
  10159. te[14] = position.z;
  10160. te[15] = 1;
  10161. return this;
  10162. };
  10163. _proto.decompose = function decompose(position, quaternion, scale) {
  10164. var te = this.elements;
  10165. var sx = _v1$1.set(te[0], te[1], te[2]).length();
  10166. var sy = _v1$1.set(te[4], te[5], te[6]).length();
  10167. var sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  10168. var det = this.determinant();
  10169. if (det < 0) sx = -sx;
  10170. position.x = te[12];
  10171. position.y = te[13];
  10172. position.z = te[14]; // scale the rotation part
  10173. _m1.copy(this);
  10174. var invSX = 1 / sx;
  10175. var invSY = 1 / sy;
  10176. var invSZ = 1 / sz;
  10177. _m1.elements[0] *= invSX;
  10178. _m1.elements[1] *= invSX;
  10179. _m1.elements[2] *= invSX;
  10180. _m1.elements[4] *= invSY;
  10181. _m1.elements[5] *= invSY;
  10182. _m1.elements[6] *= invSY;
  10183. _m1.elements[8] *= invSZ;
  10184. _m1.elements[9] *= invSZ;
  10185. _m1.elements[10] *= invSZ;
  10186. quaternion.setFromRotationMatrix(_m1);
  10187. scale.x = sx;
  10188. scale.y = sy;
  10189. scale.z = sz;
  10190. return this;
  10191. };
  10192. _proto.makePerspective = function makePerspective(left, right, top, bottom, near, far) {
  10193. if (far === undefined) {
  10194. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  10195. }
  10196. var te = this.elements;
  10197. var x = 2 * near / (right - left);
  10198. var y = 2 * near / (top - bottom);
  10199. var a = (right + left) / (right - left);
  10200. var b = (top + bottom) / (top - bottom);
  10201. var c = -(far + near) / (far - near);
  10202. var d = -2 * far * near / (far - near);
  10203. te[0] = x;
  10204. te[4] = 0;
  10205. te[8] = a;
  10206. te[12] = 0;
  10207. te[1] = 0;
  10208. te[5] = y;
  10209. te[9] = b;
  10210. te[13] = 0;
  10211. te[2] = 0;
  10212. te[6] = 0;
  10213. te[10] = c;
  10214. te[14] = d;
  10215. te[3] = 0;
  10216. te[7] = 0;
  10217. te[11] = -1;
  10218. te[15] = 0;
  10219. return this;
  10220. };
  10221. _proto.makeOrthographic = function makeOrthographic(left, right, top, bottom, near, far) {
  10222. var te = this.elements;
  10223. var w = 1.0 / (right - left);
  10224. var h = 1.0 / (top - bottom);
  10225. var p = 1.0 / (far - near);
  10226. var x = (right + left) * w;
  10227. var y = (top + bottom) * h;
  10228. var z = (far + near) * p;
  10229. te[0] = 2 * w;
  10230. te[4] = 0;
  10231. te[8] = 0;
  10232. te[12] = -x;
  10233. te[1] = 0;
  10234. te[5] = 2 * h;
  10235. te[9] = 0;
  10236. te[13] = -y;
  10237. te[2] = 0;
  10238. te[6] = 0;
  10239. te[10] = -2 * p;
  10240. te[14] = -z;
  10241. te[3] = 0;
  10242. te[7] = 0;
  10243. te[11] = 0;
  10244. te[15] = 1;
  10245. return this;
  10246. };
  10247. _proto.equals = function equals(matrix) {
  10248. var te = this.elements;
  10249. var me = matrix.elements;
  10250. for (var i = 0; i < 16; i++) {
  10251. if (te[i] !== me[i]) return false;
  10252. }
  10253. return true;
  10254. };
  10255. _proto.fromArray = function fromArray(array, offset) {
  10256. if (offset === void 0) {
  10257. offset = 0;
  10258. }
  10259. for (var i = 0; i < 16; i++) {
  10260. this.elements[i] = array[i + offset];
  10261. }
  10262. return this;
  10263. };
  10264. _proto.toArray = function toArray(array, offset) {
  10265. if (array === void 0) {
  10266. array = [];
  10267. }
  10268. if (offset === void 0) {
  10269. offset = 0;
  10270. }
  10271. var te = this.elements;
  10272. array[offset] = te[0];
  10273. array[offset + 1] = te[1];
  10274. array[offset + 2] = te[2];
  10275. array[offset + 3] = te[3];
  10276. array[offset + 4] = te[4];
  10277. array[offset + 5] = te[5];
  10278. array[offset + 6] = te[6];
  10279. array[offset + 7] = te[7];
  10280. array[offset + 8] = te[8];
  10281. array[offset + 9] = te[9];
  10282. array[offset + 10] = te[10];
  10283. array[offset + 11] = te[11];
  10284. array[offset + 12] = te[12];
  10285. array[offset + 13] = te[13];
  10286. array[offset + 14] = te[14];
  10287. array[offset + 15] = te[15];
  10288. return array;
  10289. };
  10290. return Matrix4;
  10291. }();
  10292. var _v1$1 = /*@__PURE__*/new Vector3();
  10293. var _m1 = /*@__PURE__*/new Matrix4();
  10294. var _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  10295. var _one = /*@__PURE__*/new Vector3(1, 1, 1);
  10296. var _x = /*@__PURE__*/new Vector3();
  10297. var _y = /*@__PURE__*/new Vector3();
  10298. var _z = /*@__PURE__*/new Vector3();
  10299. var Euler = /*#__PURE__*/function () {
  10300. function Euler(x, y, z, order) {
  10301. if (x === void 0) {
  10302. x = 0;
  10303. }
  10304. if (y === void 0) {
  10305. y = 0;
  10306. }
  10307. if (z === void 0) {
  10308. z = 0;
  10309. }
  10310. if (order === void 0) {
  10311. order = Euler.DefaultOrder;
  10312. }
  10313. Object.defineProperty(this, 'isEuler', {
  10314. value: true
  10315. });
  10316. this._x = x;
  10317. this._y = y;
  10318. this._z = z;
  10319. this._order = order;
  10320. }
  10321. var _proto = Euler.prototype;
  10322. _proto.set = function set(x, y, z, order) {
  10323. this._x = x;
  10324. this._y = y;
  10325. this._z = z;
  10326. this._order = order || this._order;
  10327. this._onChangeCallback();
  10328. return this;
  10329. };
  10330. _proto.clone = function clone() {
  10331. return new this.constructor(this._x, this._y, this._z, this._order);
  10332. };
  10333. _proto.copy = function copy(euler) {
  10334. this._x = euler._x;
  10335. this._y = euler._y;
  10336. this._z = euler._z;
  10337. this._order = euler._order;
  10338. this._onChangeCallback();
  10339. return this;
  10340. };
  10341. _proto.setFromRotationMatrix = function setFromRotationMatrix(m, order, update) {
  10342. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10343. var te = m.elements;
  10344. var m11 = te[0],
  10345. m12 = te[4],
  10346. m13 = te[8];
  10347. var m21 = te[1],
  10348. m22 = te[5],
  10349. m23 = te[9];
  10350. var m31 = te[2],
  10351. m32 = te[6],
  10352. m33 = te[10];
  10353. order = order || this._order;
  10354. switch (order) {
  10355. case 'XYZ':
  10356. this._y = Math.asin(clamp(m13, -1, 1));
  10357. if (Math.abs(m13) < 0.9999999) {
  10358. this._x = Math.atan2(-m23, m33);
  10359. this._z = Math.atan2(-m12, m11);
  10360. } else {
  10361. this._x = Math.atan2(m32, m22);
  10362. this._z = 0;
  10363. }
  10364. break;
  10365. case 'YXZ':
  10366. this._x = Math.asin(-clamp(m23, -1, 1));
  10367. if (Math.abs(m23) < 0.9999999) {
  10368. this._y = Math.atan2(m13, m33);
  10369. this._z = Math.atan2(m21, m22);
  10370. } else {
  10371. this._y = Math.atan2(-m31, m11);
  10372. this._z = 0;
  10373. }
  10374. break;
  10375. case 'ZXY':
  10376. this._x = Math.asin(clamp(m32, -1, 1));
  10377. if (Math.abs(m32) < 0.9999999) {
  10378. this._y = Math.atan2(-m31, m33);
  10379. this._z = Math.atan2(-m12, m22);
  10380. } else {
  10381. this._y = 0;
  10382. this._z = Math.atan2(m21, m11);
  10383. }
  10384. break;
  10385. case 'ZYX':
  10386. this._y = Math.asin(-clamp(m31, -1, 1));
  10387. if (Math.abs(m31) < 0.9999999) {
  10388. this._x = Math.atan2(m32, m33);
  10389. this._z = Math.atan2(m21, m11);
  10390. } else {
  10391. this._x = 0;
  10392. this._z = Math.atan2(-m12, m22);
  10393. }
  10394. break;
  10395. case 'YZX':
  10396. this._z = Math.asin(clamp(m21, -1, 1));
  10397. if (Math.abs(m21) < 0.9999999) {
  10398. this._x = Math.atan2(-m23, m22);
  10399. this._y = Math.atan2(-m31, m11);
  10400. } else {
  10401. this._x = 0;
  10402. this._y = Math.atan2(m13, m33);
  10403. }
  10404. break;
  10405. case 'XZY':
  10406. this._z = Math.asin(-clamp(m12, -1, 1));
  10407. if (Math.abs(m12) < 0.9999999) {
  10408. this._x = Math.atan2(m32, m22);
  10409. this._y = Math.atan2(m13, m11);
  10410. } else {
  10411. this._x = Math.atan2(-m23, m33);
  10412. this._y = 0;
  10413. }
  10414. break;
  10415. default:
  10416. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  10417. }
  10418. this._order = order;
  10419. if (update !== false) this._onChangeCallback();
  10420. return this;
  10421. };
  10422. _proto.setFromQuaternion = function setFromQuaternion(q, order, update) {
  10423. _matrix.makeRotationFromQuaternion(q);
  10424. return this.setFromRotationMatrix(_matrix, order, update);
  10425. };
  10426. _proto.setFromVector3 = function setFromVector3(v, order) {
  10427. return this.set(v.x, v.y, v.z, order || this._order);
  10428. };
  10429. _proto.reorder = function reorder(newOrder) {
  10430. // WARNING: this discards revolution information -bhouston
  10431. _quaternion$1.setFromEuler(this);
  10432. return this.setFromQuaternion(_quaternion$1, newOrder);
  10433. };
  10434. _proto.equals = function equals(euler) {
  10435. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  10436. };
  10437. _proto.fromArray = function fromArray(array) {
  10438. this._x = array[0];
  10439. this._y = array[1];
  10440. this._z = array[2];
  10441. if (array[3] !== undefined) this._order = array[3];
  10442. this._onChangeCallback();
  10443. return this;
  10444. };
  10445. _proto.toArray = function toArray(array, offset) {
  10446. if (array === void 0) {
  10447. array = [];
  10448. }
  10449. if (offset === void 0) {
  10450. offset = 0;
  10451. }
  10452. array[offset] = this._x;
  10453. array[offset + 1] = this._y;
  10454. array[offset + 2] = this._z;
  10455. array[offset + 3] = this._order;
  10456. return array;
  10457. };
  10458. _proto.toVector3 = function toVector3(optionalResult) {
  10459. if (optionalResult) {
  10460. return optionalResult.set(this._x, this._y, this._z);
  10461. } else {
  10462. return new Vector3(this._x, this._y, this._z);
  10463. }
  10464. };
  10465. _proto._onChange = function _onChange(callback) {
  10466. this._onChangeCallback = callback;
  10467. return this;
  10468. };
  10469. _proto._onChangeCallback = function _onChangeCallback() {};
  10470. _createClass(Euler, [{
  10471. key: "x",
  10472. get: function get() {
  10473. return this._x;
  10474. },
  10475. set: function set(value) {
  10476. this._x = value;
  10477. this._onChangeCallback();
  10478. }
  10479. }, {
  10480. key: "y",
  10481. get: function get() {
  10482. return this._y;
  10483. },
  10484. set: function set(value) {
  10485. this._y = value;
  10486. this._onChangeCallback();
  10487. }
  10488. }, {
  10489. key: "z",
  10490. get: function get() {
  10491. return this._z;
  10492. },
  10493. set: function set(value) {
  10494. this._z = value;
  10495. this._onChangeCallback();
  10496. }
  10497. }, {
  10498. key: "order",
  10499. get: function get() {
  10500. return this._order;
  10501. },
  10502. set: function set(value) {
  10503. this._order = value;
  10504. this._onChangeCallback();
  10505. }
  10506. }]);
  10507. return Euler;
  10508. }();
  10509. Euler.DefaultOrder = 'XYZ';
  10510. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  10511. var _matrix = /*@__PURE__*/new Matrix4();
  10512. var _quaternion$1 = /*@__PURE__*/new Quaternion();
  10513. var Layers = /*#__PURE__*/function () {
  10514. function Layers() {
  10515. this.mask = 1 | 0;
  10516. }
  10517. var _proto = Layers.prototype;
  10518. _proto.set = function set(channel) {
  10519. this.mask = 1 << channel | 0;
  10520. };
  10521. _proto.enable = function enable(channel) {
  10522. this.mask |= 1 << channel | 0;
  10523. };
  10524. _proto.enableAll = function enableAll() {
  10525. this.mask = 0xffffffff | 0;
  10526. };
  10527. _proto.toggle = function toggle(channel) {
  10528. this.mask ^= 1 << channel | 0;
  10529. };
  10530. _proto.disable = function disable(channel) {
  10531. this.mask &= ~(1 << channel | 0);
  10532. };
  10533. _proto.disableAll = function disableAll() {
  10534. this.mask = 0;
  10535. };
  10536. _proto.test = function test(layers) {
  10537. return (this.mask & layers.mask) !== 0;
  10538. };
  10539. return Layers;
  10540. }();
  10541. var _object3DId = 0;
  10542. var _v1$2 = new Vector3();
  10543. var _q1 = new Quaternion();
  10544. var _m1$1 = new Matrix4();
  10545. var _target = new Vector3();
  10546. var _position = new Vector3();
  10547. var _scale = new Vector3();
  10548. var _quaternion$2 = new Quaternion();
  10549. var _xAxis = new Vector3(1, 0, 0);
  10550. var _yAxis = new Vector3(0, 1, 0);
  10551. var _zAxis = new Vector3(0, 0, 1);
  10552. var _addedEvent = {
  10553. type: 'added'
  10554. };
  10555. var _removedEvent = {
  10556. type: 'removed'
  10557. };
  10558. function Object3D() {
  10559. Object.defineProperty(this, 'id', {
  10560. value: _object3DId++
  10561. });
  10562. this.uuid = MathUtils.generateUUID();
  10563. this.name = '';
  10564. this.type = 'Object3D';
  10565. this.parent = null;
  10566. this.children = [];
  10567. this.up = Object3D.DefaultUp.clone();
  10568. var position = new Vector3();
  10569. var rotation = new Euler();
  10570. var quaternion = new Quaternion();
  10571. var scale = new Vector3(1, 1, 1);
  10572. function onRotationChange() {
  10573. quaternion.setFromEuler(rotation, false);
  10574. }
  10575. function onQuaternionChange() {
  10576. rotation.setFromQuaternion(quaternion, undefined, false);
  10577. }
  10578. rotation._onChange(onRotationChange);
  10579. quaternion._onChange(onQuaternionChange);
  10580. Object.defineProperties(this, {
  10581. position: {
  10582. configurable: true,
  10583. enumerable: true,
  10584. value: position
  10585. },
  10586. rotation: {
  10587. configurable: true,
  10588. enumerable: true,
  10589. value: rotation
  10590. },
  10591. quaternion: {
  10592. configurable: true,
  10593. enumerable: true,
  10594. value: quaternion
  10595. },
  10596. scale: {
  10597. configurable: true,
  10598. enumerable: true,
  10599. value: scale
  10600. },
  10601. modelViewMatrix: {
  10602. value: new Matrix4()
  10603. },
  10604. normalMatrix: {
  10605. value: new Matrix3()
  10606. }
  10607. });
  10608. this.matrix = new Matrix4();
  10609. this.matrixWorld = new Matrix4();
  10610. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10611. this.matrixWorldNeedsUpdate = false;
  10612. this.layers = new Layers();
  10613. this.visible = true;
  10614. this.castShadow = false;
  10615. this.receiveShadow = false;
  10616. this.frustumCulled = true;
  10617. this.renderOrder = 0;
  10618. this.animations = [];
  10619. this.userData = {};
  10620. }
  10621. Object3D.DefaultUp = new Vector3(0, 1, 0);
  10622. Object3D.DefaultMatrixAutoUpdate = true;
  10623. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  10624. constructor: Object3D,
  10625. isObject3D: true,
  10626. onBeforeRender: function onBeforeRender() {},
  10627. onAfterRender: function onAfterRender() {},
  10628. applyMatrix4: function applyMatrix4(matrix) {
  10629. if (this.matrixAutoUpdate) this.updateMatrix();
  10630. this.matrix.premultiply(matrix);
  10631. this.matrix.decompose(this.position, this.quaternion, this.scale);
  10632. },
  10633. applyQuaternion: function applyQuaternion(q) {
  10634. this.quaternion.premultiply(q);
  10635. return this;
  10636. },
  10637. setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {
  10638. // assumes axis is normalized
  10639. this.quaternion.setFromAxisAngle(axis, angle);
  10640. },
  10641. setRotationFromEuler: function setRotationFromEuler(euler) {
  10642. this.quaternion.setFromEuler(euler, true);
  10643. },
  10644. setRotationFromMatrix: function setRotationFromMatrix(m) {
  10645. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10646. this.quaternion.setFromRotationMatrix(m);
  10647. },
  10648. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  10649. // assumes q is normalized
  10650. this.quaternion.copy(q);
  10651. },
  10652. rotateOnAxis: function rotateOnAxis(axis, angle) {
  10653. // rotate object on axis in object space
  10654. // axis is assumed to be normalized
  10655. _q1.setFromAxisAngle(axis, angle);
  10656. this.quaternion.multiply(_q1);
  10657. return this;
  10658. },
  10659. rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {
  10660. // rotate object on axis in world space
  10661. // axis is assumed to be normalized
  10662. // method assumes no rotated parent
  10663. _q1.setFromAxisAngle(axis, angle);
  10664. this.quaternion.premultiply(_q1);
  10665. return this;
  10666. },
  10667. rotateX: function rotateX(angle) {
  10668. return this.rotateOnAxis(_xAxis, angle);
  10669. },
  10670. rotateY: function rotateY(angle) {
  10671. return this.rotateOnAxis(_yAxis, angle);
  10672. },
  10673. rotateZ: function rotateZ(angle) {
  10674. return this.rotateOnAxis(_zAxis, angle);
  10675. },
  10676. translateOnAxis: function translateOnAxis(axis, distance) {
  10677. // translate object by distance along axis in object space
  10678. // axis is assumed to be normalized
  10679. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  10680. this.position.add(_v1$2.multiplyScalar(distance));
  10681. return this;
  10682. },
  10683. translateX: function translateX(distance) {
  10684. return this.translateOnAxis(_xAxis, distance);
  10685. },
  10686. translateY: function translateY(distance) {
  10687. return this.translateOnAxis(_yAxis, distance);
  10688. },
  10689. translateZ: function translateZ(distance) {
  10690. return this.translateOnAxis(_zAxis, distance);
  10691. },
  10692. localToWorld: function localToWorld(vector) {
  10693. return vector.applyMatrix4(this.matrixWorld);
  10694. },
  10695. worldToLocal: function worldToLocal(vector) {
  10696. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  10697. },
  10698. lookAt: function lookAt(x, y, z) {
  10699. // This method does not support objects having non-uniformly-scaled parent(s)
  10700. if (x.isVector3) {
  10701. _target.copy(x);
  10702. } else {
  10703. _target.set(x, y, z);
  10704. }
  10705. var parent = this.parent;
  10706. this.updateWorldMatrix(true, false);
  10707. _position.setFromMatrixPosition(this.matrixWorld);
  10708. if (this.isCamera || this.isLight) {
  10709. _m1$1.lookAt(_position, _target, this.up);
  10710. } else {
  10711. _m1$1.lookAt(_target, _position, this.up);
  10712. }
  10713. this.quaternion.setFromRotationMatrix(_m1$1);
  10714. if (parent) {
  10715. _m1$1.extractRotation(parent.matrixWorld);
  10716. _q1.setFromRotationMatrix(_m1$1);
  10717. this.quaternion.premultiply(_q1.invert());
  10718. }
  10719. },
  10720. add: function add(object) {
  10721. if (arguments.length > 1) {
  10722. for (var i = 0; i < arguments.length; i++) {
  10723. this.add(arguments[i]);
  10724. }
  10725. return this;
  10726. }
  10727. if (object === this) {
  10728. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  10729. return this;
  10730. }
  10731. if (object && object.isObject3D) {
  10732. if (object.parent !== null) {
  10733. object.parent.remove(object);
  10734. }
  10735. object.parent = this;
  10736. this.children.push(object);
  10737. object.dispatchEvent(_addedEvent);
  10738. } else {
  10739. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  10740. }
  10741. return this;
  10742. },
  10743. remove: function remove(object) {
  10744. if (arguments.length > 1) {
  10745. for (var i = 0; i < arguments.length; i++) {
  10746. this.remove(arguments[i]);
  10747. }
  10748. return this;
  10749. }
  10750. var index = this.children.indexOf(object);
  10751. if (index !== -1) {
  10752. object.parent = null;
  10753. this.children.splice(index, 1);
  10754. object.dispatchEvent(_removedEvent);
  10755. }
  10756. return this;
  10757. },
  10758. clear: function clear() {
  10759. for (var i = 0; i < this.children.length; i++) {
  10760. var object = this.children[i];
  10761. object.parent = null;
  10762. object.dispatchEvent(_removedEvent);
  10763. }
  10764. this.children.length = 0;
  10765. return this;
  10766. },
  10767. attach: function attach(object) {
  10768. // adds object as a child of this, while maintaining the object's world transform
  10769. this.updateWorldMatrix(true, false);
  10770. _m1$1.copy(this.matrixWorld).invert();
  10771. if (object.parent !== null) {
  10772. object.parent.updateWorldMatrix(true, false);
  10773. _m1$1.multiply(object.parent.matrixWorld);
  10774. }
  10775. object.applyMatrix4(_m1$1);
  10776. object.updateWorldMatrix(false, false);
  10777. this.add(object);
  10778. return this;
  10779. },
  10780. getObjectById: function getObjectById(id) {
  10781. return this.getObjectByProperty('id', id);
  10782. },
  10783. getObjectByName: function getObjectByName(name) {
  10784. return this.getObjectByProperty('name', name);
  10785. },
  10786. getObjectByProperty: function getObjectByProperty(name, value) {
  10787. if (this[name] === value) return this;
  10788. for (var i = 0, l = this.children.length; i < l; i++) {
  10789. var child = this.children[i];
  10790. var object = child.getObjectByProperty(name, value);
  10791. if (object !== undefined) {
  10792. return object;
  10793. }
  10794. }
  10795. return undefined;
  10796. },
  10797. getWorldPosition: function getWorldPosition(target) {
  10798. if (target === undefined) {
  10799. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  10800. target = new Vector3();
  10801. }
  10802. this.updateWorldMatrix(true, false);
  10803. return target.setFromMatrixPosition(this.matrixWorld);
  10804. },
  10805. getWorldQuaternion: function getWorldQuaternion(target) {
  10806. if (target === undefined) {
  10807. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  10808. target = new Quaternion();
  10809. }
  10810. this.updateWorldMatrix(true, false);
  10811. this.matrixWorld.decompose(_position, target, _scale);
  10812. return target;
  10813. },
  10814. getWorldScale: function getWorldScale(target) {
  10815. if (target === undefined) {
  10816. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  10817. target = new Vector3();
  10818. }
  10819. this.updateWorldMatrix(true, false);
  10820. this.matrixWorld.decompose(_position, _quaternion$2, target);
  10821. return target;
  10822. },
  10823. getWorldDirection: function getWorldDirection(target) {
  10824. if (target === undefined) {
  10825. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  10826. target = new Vector3();
  10827. }
  10828. this.updateWorldMatrix(true, false);
  10829. var e = this.matrixWorld.elements;
  10830. return target.set(e[8], e[9], e[10]).normalize();
  10831. },
  10832. raycast: function raycast() {},
  10833. traverse: function traverse(callback) {
  10834. callback(this);
  10835. var children = this.children;
  10836. for (var i = 0, l = children.length; i < l; i++) {
  10837. children[i].traverse(callback);
  10838. }
  10839. },
  10840. traverseVisible: function traverseVisible(callback) {
  10841. if (this.visible === false) return;
  10842. callback(this);
  10843. var children = this.children;
  10844. for (var i = 0, l = children.length; i < l; i++) {
  10845. children[i].traverseVisible(callback);
  10846. }
  10847. },
  10848. traverseAncestors: function traverseAncestors(callback) {
  10849. var parent = this.parent;
  10850. if (parent !== null) {
  10851. callback(parent);
  10852. parent.traverseAncestors(callback);
  10853. }
  10854. },
  10855. updateMatrix: function updateMatrix() {
  10856. this.matrix.compose(this.position, this.quaternion, this.scale);
  10857. this.matrixWorldNeedsUpdate = true;
  10858. },
  10859. updateMatrixWorld: function updateMatrixWorld(force) {
  10860. if (this.matrixAutoUpdate) this.updateMatrix();
  10861. if (this.matrixWorldNeedsUpdate || force) {
  10862. if (this.parent === null) {
  10863. this.matrixWorld.copy(this.matrix);
  10864. } else {
  10865. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10866. }
  10867. this.matrixWorldNeedsUpdate = false;
  10868. force = true;
  10869. } // update children
  10870. var children = this.children;
  10871. for (var i = 0, l = children.length; i < l; i++) {
  10872. children[i].updateMatrixWorld(force);
  10873. }
  10874. },
  10875. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  10876. var parent = this.parent;
  10877. if (updateParents === true && parent !== null) {
  10878. parent.updateWorldMatrix(true, false);
  10879. }
  10880. if (this.matrixAutoUpdate) this.updateMatrix();
  10881. if (this.parent === null) {
  10882. this.matrixWorld.copy(this.matrix);
  10883. } else {
  10884. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10885. } // update children
  10886. if (updateChildren === true) {
  10887. var children = this.children;
  10888. for (var i = 0, l = children.length; i < l; i++) {
  10889. children[i].updateWorldMatrix(false, true);
  10890. }
  10891. }
  10892. },
  10893. toJSON: function toJSON(meta) {
  10894. // meta is a string when called from JSON.stringify
  10895. var isRootObject = meta === undefined || typeof meta === 'string';
  10896. var output = {}; // meta is a hash used to collect geometries, materials.
  10897. // not providing it implies that this is the root object
  10898. // being serialized.
  10899. if (isRootObject) {
  10900. // initialize meta obj
  10901. meta = {
  10902. geometries: {},
  10903. materials: {},
  10904. textures: {},
  10905. images: {},
  10906. shapes: {},
  10907. skeletons: {},
  10908. animations: {}
  10909. };
  10910. output.metadata = {
  10911. version: 4.5,
  10912. type: 'Object',
  10913. generator: 'Object3D.toJSON'
  10914. };
  10915. } // standard Object3D serialization
  10916. var object = {};
  10917. object.uuid = this.uuid;
  10918. object.type = this.type;
  10919. if (this.name !== '') object.name = this.name;
  10920. if (this.castShadow === true) object.castShadow = true;
  10921. if (this.receiveShadow === true) object.receiveShadow = true;
  10922. if (this.visible === false) object.visible = false;
  10923. if (this.frustumCulled === false) object.frustumCulled = false;
  10924. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  10925. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  10926. object.layers = this.layers.mask;
  10927. object.matrix = this.matrix.toArray();
  10928. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  10929. if (this.isInstancedMesh) {
  10930. object.type = 'InstancedMesh';
  10931. object.count = this.count;
  10932. object.instanceMatrix = this.instanceMatrix.toJSON();
  10933. } //
  10934. function serialize(library, element) {
  10935. if (library[element.uuid] === undefined) {
  10936. library[element.uuid] = element.toJSON(meta);
  10937. }
  10938. return element.uuid;
  10939. }
  10940. if (this.isMesh || this.isLine || this.isPoints) {
  10941. object.geometry = serialize(meta.geometries, this.geometry);
  10942. var parameters = this.geometry.parameters;
  10943. if (parameters !== undefined && parameters.shapes !== undefined) {
  10944. var shapes = parameters.shapes;
  10945. if (Array.isArray(shapes)) {
  10946. for (var i = 0, l = shapes.length; i < l; i++) {
  10947. var shape = shapes[i];
  10948. serialize(meta.shapes, shape);
  10949. }
  10950. } else {
  10951. serialize(meta.shapes, shapes);
  10952. }
  10953. }
  10954. }
  10955. if (this.isSkinnedMesh) {
  10956. object.bindMode = this.bindMode;
  10957. object.bindMatrix = this.bindMatrix.toArray();
  10958. if (this.skeleton !== undefined) {
  10959. serialize(meta.skeletons, this.skeleton);
  10960. object.skeleton = this.skeleton.uuid;
  10961. }
  10962. }
  10963. if (this.material !== undefined) {
  10964. if (Array.isArray(this.material)) {
  10965. var uuids = [];
  10966. for (var _i = 0, _l = this.material.length; _i < _l; _i++) {
  10967. uuids.push(serialize(meta.materials, this.material[_i]));
  10968. }
  10969. object.material = uuids;
  10970. } else {
  10971. object.material = serialize(meta.materials, this.material);
  10972. }
  10973. } //
  10974. if (this.children.length > 0) {
  10975. object.children = [];
  10976. for (var _i2 = 0; _i2 < this.children.length; _i2++) {
  10977. object.children.push(this.children[_i2].toJSON(meta).object);
  10978. }
  10979. } //
  10980. if (this.animations.length > 0) {
  10981. object.animations = [];
  10982. for (var _i3 = 0; _i3 < this.animations.length; _i3++) {
  10983. var animation = this.animations[_i3];
  10984. object.animations.push(serialize(meta.animations, animation));
  10985. }
  10986. }
  10987. if (isRootObject) {
  10988. var geometries = extractFromCache(meta.geometries);
  10989. var materials = extractFromCache(meta.materials);
  10990. var textures = extractFromCache(meta.textures);
  10991. var images = extractFromCache(meta.images);
  10992. var _shapes = extractFromCache(meta.shapes);
  10993. var skeletons = extractFromCache(meta.skeletons);
  10994. var animations = extractFromCache(meta.animations);
  10995. if (geometries.length > 0) output.geometries = geometries;
  10996. if (materials.length > 0) output.materials = materials;
  10997. if (textures.length > 0) output.textures = textures;
  10998. if (images.length > 0) output.images = images;
  10999. if (_shapes.length > 0) output.shapes = _shapes;
  11000. if (skeletons.length > 0) output.skeletons = skeletons;
  11001. if (animations.length > 0) output.animations = animations;
  11002. }
  11003. output.object = object;
  11004. return output; // extract data from the cache hash
  11005. // remove metadata on each item
  11006. // and return as array
  11007. function extractFromCache(cache) {
  11008. var values = [];
  11009. for (var key in cache) {
  11010. var data = cache[key];
  11011. delete data.metadata;
  11012. values.push(data);
  11013. }
  11014. return values;
  11015. }
  11016. },
  11017. clone: function clone(recursive) {
  11018. return new this.constructor().copy(this, recursive);
  11019. },
  11020. copy: function copy(source, recursive) {
  11021. if (recursive === void 0) {
  11022. recursive = true;
  11023. }
  11024. this.name = source.name;
  11025. this.up.copy(source.up);
  11026. this.position.copy(source.position);
  11027. this.rotation.order = source.rotation.order;
  11028. this.quaternion.copy(source.quaternion);
  11029. this.scale.copy(source.scale);
  11030. this.matrix.copy(source.matrix);
  11031. this.matrixWorld.copy(source.matrixWorld);
  11032. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11033. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11034. this.layers.mask = source.layers.mask;
  11035. this.visible = source.visible;
  11036. this.castShadow = source.castShadow;
  11037. this.receiveShadow = source.receiveShadow;
  11038. this.frustumCulled = source.frustumCulled;
  11039. this.renderOrder = source.renderOrder;
  11040. this.userData = JSON.parse(JSON.stringify(source.userData));
  11041. if (recursive === true) {
  11042. for (var i = 0; i < source.children.length; i++) {
  11043. var child = source.children[i];
  11044. this.add(child.clone());
  11045. }
  11046. }
  11047. return this;
  11048. }
  11049. });
  11050. var _vector1 = /*@__PURE__*/new Vector3();
  11051. var _vector2 = /*@__PURE__*/new Vector3();
  11052. var _normalMatrix = /*@__PURE__*/new Matrix3();
  11053. var Plane = /*#__PURE__*/function () {
  11054. function Plane(normal, constant) {
  11055. Object.defineProperty(this, 'isPlane', {
  11056. value: true
  11057. }); // normal is assumed to be normalized
  11058. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  11059. this.constant = constant !== undefined ? constant : 0;
  11060. }
  11061. var _proto = Plane.prototype;
  11062. _proto.set = function set(normal, constant) {
  11063. this.normal.copy(normal);
  11064. this.constant = constant;
  11065. return this;
  11066. };
  11067. _proto.setComponents = function setComponents(x, y, z, w) {
  11068. this.normal.set(x, y, z);
  11069. this.constant = w;
  11070. return this;
  11071. };
  11072. _proto.setFromNormalAndCoplanarPoint = function setFromNormalAndCoplanarPoint(normal, point) {
  11073. this.normal.copy(normal);
  11074. this.constant = -point.dot(this.normal);
  11075. return this;
  11076. };
  11077. _proto.setFromCoplanarPoints = function setFromCoplanarPoints(a, b, c) {
  11078. 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)?
  11079. this.setFromNormalAndCoplanarPoint(normal, a);
  11080. return this;
  11081. };
  11082. _proto.clone = function clone() {
  11083. return new this.constructor().copy(this);
  11084. };
  11085. _proto.copy = function copy(plane) {
  11086. this.normal.copy(plane.normal);
  11087. this.constant = plane.constant;
  11088. return this;
  11089. };
  11090. _proto.normalize = function normalize() {
  11091. // Note: will lead to a divide by zero if the plane is invalid.
  11092. var inverseNormalLength = 1.0 / this.normal.length();
  11093. this.normal.multiplyScalar(inverseNormalLength);
  11094. this.constant *= inverseNormalLength;
  11095. return this;
  11096. };
  11097. _proto.negate = function negate() {
  11098. this.constant *= -1;
  11099. this.normal.negate();
  11100. return this;
  11101. };
  11102. _proto.distanceToPoint = function distanceToPoint(point) {
  11103. return this.normal.dot(point) + this.constant;
  11104. };
  11105. _proto.distanceToSphere = function distanceToSphere(sphere) {
  11106. return this.distanceToPoint(sphere.center) - sphere.radius;
  11107. };
  11108. _proto.projectPoint = function projectPoint(point, target) {
  11109. if (target === undefined) {
  11110. console.warn('THREE.Plane: .projectPoint() target is now required');
  11111. target = new Vector3();
  11112. }
  11113. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  11114. };
  11115. _proto.intersectLine = function intersectLine(line, target) {
  11116. if (target === undefined) {
  11117. console.warn('THREE.Plane: .intersectLine() target is now required');
  11118. target = new Vector3();
  11119. }
  11120. var direction = line.delta(_vector1);
  11121. var denominator = this.normal.dot(direction);
  11122. if (denominator === 0) {
  11123. // line is coplanar, return origin
  11124. if (this.distanceToPoint(line.start) === 0) {
  11125. return target.copy(line.start);
  11126. } // Unsure if this is the correct method to handle this case.
  11127. return undefined;
  11128. }
  11129. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  11130. if (t < 0 || t > 1) {
  11131. return undefined;
  11132. }
  11133. return target.copy(direction).multiplyScalar(t).add(line.start);
  11134. };
  11135. _proto.intersectsLine = function intersectsLine(line) {
  11136. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  11137. var startSign = this.distanceToPoint(line.start);
  11138. var endSign = this.distanceToPoint(line.end);
  11139. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  11140. };
  11141. _proto.intersectsBox = function intersectsBox(box) {
  11142. return box.intersectsPlane(this);
  11143. };
  11144. _proto.intersectsSphere = function intersectsSphere(sphere) {
  11145. return sphere.intersectsPlane(this);
  11146. };
  11147. _proto.coplanarPoint = function coplanarPoint(target) {
  11148. if (target === undefined) {
  11149. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  11150. target = new Vector3();
  11151. }
  11152. return target.copy(this.normal).multiplyScalar(-this.constant);
  11153. };
  11154. _proto.applyMatrix4 = function applyMatrix4(matrix, optionalNormalMatrix) {
  11155. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  11156. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  11157. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  11158. this.constant = -referencePoint.dot(normal);
  11159. return this;
  11160. };
  11161. _proto.translate = function translate(offset) {
  11162. this.constant -= offset.dot(this.normal);
  11163. return this;
  11164. };
  11165. _proto.equals = function equals(plane) {
  11166. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  11167. };
  11168. return Plane;
  11169. }();
  11170. var _v0$1 = /*@__PURE__*/new Vector3();
  11171. var _v1$3 = /*@__PURE__*/new Vector3();
  11172. var _v2$1 = /*@__PURE__*/new Vector3();
  11173. var _v3 = /*@__PURE__*/new Vector3();
  11174. var _vab = /*@__PURE__*/new Vector3();
  11175. var _vac = /*@__PURE__*/new Vector3();
  11176. var _vbc = /*@__PURE__*/new Vector3();
  11177. var _vap = /*@__PURE__*/new Vector3();
  11178. var _vbp = /*@__PURE__*/new Vector3();
  11179. var _vcp = /*@__PURE__*/new Vector3();
  11180. var Triangle = /*#__PURE__*/function () {
  11181. function Triangle(a, b, c) {
  11182. this.a = a !== undefined ? a : new Vector3();
  11183. this.b = b !== undefined ? b : new Vector3();
  11184. this.c = c !== undefined ? c : new Vector3();
  11185. }
  11186. Triangle.getNormal = function getNormal(a, b, c, target) {
  11187. if (target === undefined) {
  11188. console.warn('THREE.Triangle: .getNormal() target is now required');
  11189. target = new Vector3();
  11190. }
  11191. target.subVectors(c, b);
  11192. _v0$1.subVectors(a, b);
  11193. target.cross(_v0$1);
  11194. var targetLengthSq = target.lengthSq();
  11195. if (targetLengthSq > 0) {
  11196. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  11197. }
  11198. return target.set(0, 0, 0);
  11199. } // static/instance method to calculate barycentric coordinates
  11200. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11201. ;
  11202. Triangle.getBarycoord = function getBarycoord(point, a, b, c, target) {
  11203. _v0$1.subVectors(c, a);
  11204. _v1$3.subVectors(b, a);
  11205. _v2$1.subVectors(point, a);
  11206. var dot00 = _v0$1.dot(_v0$1);
  11207. var dot01 = _v0$1.dot(_v1$3);
  11208. var dot02 = _v0$1.dot(_v2$1);
  11209. var dot11 = _v1$3.dot(_v1$3);
  11210. var dot12 = _v1$3.dot(_v2$1);
  11211. var denom = dot00 * dot11 - dot01 * dot01;
  11212. if (target === undefined) {
  11213. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  11214. target = new Vector3();
  11215. } // collinear or singular triangle
  11216. if (denom === 0) {
  11217. // arbitrary location outside of triangle?
  11218. // not sure if this is the best idea, maybe should be returning undefined
  11219. return target.set(-2, -1, -1);
  11220. }
  11221. var invDenom = 1 / denom;
  11222. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  11223. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  11224. return target.set(1 - u - v, v, u);
  11225. };
  11226. Triangle.containsPoint = function containsPoint(point, a, b, c) {
  11227. this.getBarycoord(point, a, b, c, _v3);
  11228. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  11229. };
  11230. Triangle.getUV = function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  11231. this.getBarycoord(point, p1, p2, p3, _v3);
  11232. target.set(0, 0);
  11233. target.addScaledVector(uv1, _v3.x);
  11234. target.addScaledVector(uv2, _v3.y);
  11235. target.addScaledVector(uv3, _v3.z);
  11236. return target;
  11237. };
  11238. Triangle.isFrontFacing = function isFrontFacing(a, b, c, direction) {
  11239. _v0$1.subVectors(c, b);
  11240. _v1$3.subVectors(a, b); // strictly front facing
  11241. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  11242. };
  11243. var _proto = Triangle.prototype;
  11244. _proto.set = function set(a, b, c) {
  11245. this.a.copy(a);
  11246. this.b.copy(b);
  11247. this.c.copy(c);
  11248. return this;
  11249. };
  11250. _proto.setFromPointsAndIndices = function setFromPointsAndIndices(points, i0, i1, i2) {
  11251. this.a.copy(points[i0]);
  11252. this.b.copy(points[i1]);
  11253. this.c.copy(points[i2]);
  11254. return this;
  11255. };
  11256. _proto.clone = function clone() {
  11257. return new this.constructor().copy(this);
  11258. };
  11259. _proto.copy = function copy(triangle) {
  11260. this.a.copy(triangle.a);
  11261. this.b.copy(triangle.b);
  11262. this.c.copy(triangle.c);
  11263. return this;
  11264. };
  11265. _proto.getArea = function getArea() {
  11266. _v0$1.subVectors(this.c, this.b);
  11267. _v1$3.subVectors(this.a, this.b);
  11268. return _v0$1.cross(_v1$3).length() * 0.5;
  11269. };
  11270. _proto.getMidpoint = function getMidpoint(target) {
  11271. if (target === undefined) {
  11272. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  11273. target = new Vector3();
  11274. }
  11275. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  11276. };
  11277. _proto.getNormal = function getNormal(target) {
  11278. return Triangle.getNormal(this.a, this.b, this.c, target);
  11279. };
  11280. _proto.getPlane = function getPlane(target) {
  11281. if (target === undefined) {
  11282. console.warn('THREE.Triangle: .getPlane() target is now required');
  11283. target = new Plane();
  11284. }
  11285. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  11286. };
  11287. _proto.getBarycoord = function getBarycoord(point, target) {
  11288. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  11289. };
  11290. _proto.getUV = function getUV(point, uv1, uv2, uv3, target) {
  11291. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  11292. };
  11293. _proto.containsPoint = function containsPoint(point) {
  11294. return Triangle.containsPoint(point, this.a, this.b, this.c);
  11295. };
  11296. _proto.isFrontFacing = function isFrontFacing(direction) {
  11297. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  11298. };
  11299. _proto.intersectsBox = function intersectsBox(box) {
  11300. return box.intersectsTriangle(this);
  11301. };
  11302. _proto.closestPointToPoint = function closestPointToPoint(p, target) {
  11303. if (target === undefined) {
  11304. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  11305. target = new Vector3();
  11306. }
  11307. var a = this.a,
  11308. b = this.b,
  11309. c = this.c;
  11310. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11311. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11312. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11313. // basically, we're distinguishing which of the voronoi regions of the triangle
  11314. // the point lies in with the minimum amount of redundant computation.
  11315. _vab.subVectors(b, a);
  11316. _vac.subVectors(c, a);
  11317. _vap.subVectors(p, a);
  11318. var d1 = _vab.dot(_vap);
  11319. var d2 = _vac.dot(_vap);
  11320. if (d1 <= 0 && d2 <= 0) {
  11321. // vertex region of A; barycentric coords (1, 0, 0)
  11322. return target.copy(a);
  11323. }
  11324. _vbp.subVectors(p, b);
  11325. var d3 = _vab.dot(_vbp);
  11326. var d4 = _vac.dot(_vbp);
  11327. if (d3 >= 0 && d4 <= d3) {
  11328. // vertex region of B; barycentric coords (0, 1, 0)
  11329. return target.copy(b);
  11330. }
  11331. var vc = d1 * d4 - d3 * d2;
  11332. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  11333. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  11334. return target.copy(a).addScaledVector(_vab, v);
  11335. }
  11336. _vcp.subVectors(p, c);
  11337. var d5 = _vab.dot(_vcp);
  11338. var d6 = _vac.dot(_vcp);
  11339. if (d6 >= 0 && d5 <= d6) {
  11340. // vertex region of C; barycentric coords (0, 0, 1)
  11341. return target.copy(c);
  11342. }
  11343. var vb = d5 * d2 - d1 * d6;
  11344. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  11345. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  11346. return target.copy(a).addScaledVector(_vac, w);
  11347. }
  11348. var va = d3 * d6 - d5 * d4;
  11349. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  11350. _vbc.subVectors(c, b);
  11351. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  11352. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  11353. } // face region
  11354. var denom = 1 / (va + vb + vc); // u = va * denom
  11355. v = vb * denom;
  11356. w = vc * denom;
  11357. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  11358. };
  11359. _proto.equals = function equals(triangle) {
  11360. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  11361. };
  11362. return Triangle;
  11363. }();
  11364. var _colorKeywords = {
  11365. 'aliceblue': 0xF0F8FF,
  11366. 'antiquewhite': 0xFAEBD7,
  11367. 'aqua': 0x00FFFF,
  11368. 'aquamarine': 0x7FFFD4,
  11369. 'azure': 0xF0FFFF,
  11370. 'beige': 0xF5F5DC,
  11371. 'bisque': 0xFFE4C4,
  11372. 'black': 0x000000,
  11373. 'blanchedalmond': 0xFFEBCD,
  11374. 'blue': 0x0000FF,
  11375. 'blueviolet': 0x8A2BE2,
  11376. 'brown': 0xA52A2A,
  11377. 'burlywood': 0xDEB887,
  11378. 'cadetblue': 0x5F9EA0,
  11379. 'chartreuse': 0x7FFF00,
  11380. 'chocolate': 0xD2691E,
  11381. 'coral': 0xFF7F50,
  11382. 'cornflowerblue': 0x6495ED,
  11383. 'cornsilk': 0xFFF8DC,
  11384. 'crimson': 0xDC143C,
  11385. 'cyan': 0x00FFFF,
  11386. 'darkblue': 0x00008B,
  11387. 'darkcyan': 0x008B8B,
  11388. 'darkgoldenrod': 0xB8860B,
  11389. 'darkgray': 0xA9A9A9,
  11390. 'darkgreen': 0x006400,
  11391. 'darkgrey': 0xA9A9A9,
  11392. 'darkkhaki': 0xBDB76B,
  11393. 'darkmagenta': 0x8B008B,
  11394. 'darkolivegreen': 0x556B2F,
  11395. 'darkorange': 0xFF8C00,
  11396. 'darkorchid': 0x9932CC,
  11397. 'darkred': 0x8B0000,
  11398. 'darksalmon': 0xE9967A,
  11399. 'darkseagreen': 0x8FBC8F,
  11400. 'darkslateblue': 0x483D8B,
  11401. 'darkslategray': 0x2F4F4F,
  11402. 'darkslategrey': 0x2F4F4F,
  11403. 'darkturquoise': 0x00CED1,
  11404. 'darkviolet': 0x9400D3,
  11405. 'deeppink': 0xFF1493,
  11406. 'deepskyblue': 0x00BFFF,
  11407. 'dimgray': 0x696969,
  11408. 'dimgrey': 0x696969,
  11409. 'dodgerblue': 0x1E90FF,
  11410. 'firebrick': 0xB22222,
  11411. 'floralwhite': 0xFFFAF0,
  11412. 'forestgreen': 0x228B22,
  11413. 'fuchsia': 0xFF00FF,
  11414. 'gainsboro': 0xDCDCDC,
  11415. 'ghostwhite': 0xF8F8FF,
  11416. 'gold': 0xFFD700,
  11417. 'goldenrod': 0xDAA520,
  11418. 'gray': 0x808080,
  11419. 'green': 0x008000,
  11420. 'greenyellow': 0xADFF2F,
  11421. 'grey': 0x808080,
  11422. 'honeydew': 0xF0FFF0,
  11423. 'hotpink': 0xFF69B4,
  11424. 'indianred': 0xCD5C5C,
  11425. 'indigo': 0x4B0082,
  11426. 'ivory': 0xFFFFF0,
  11427. 'khaki': 0xF0E68C,
  11428. 'lavender': 0xE6E6FA,
  11429. 'lavenderblush': 0xFFF0F5,
  11430. 'lawngreen': 0x7CFC00,
  11431. 'lemonchiffon': 0xFFFACD,
  11432. 'lightblue': 0xADD8E6,
  11433. 'lightcoral': 0xF08080,
  11434. 'lightcyan': 0xE0FFFF,
  11435. 'lightgoldenrodyellow': 0xFAFAD2,
  11436. 'lightgray': 0xD3D3D3,
  11437. 'lightgreen': 0x90EE90,
  11438. 'lightgrey': 0xD3D3D3,
  11439. 'lightpink': 0xFFB6C1,
  11440. 'lightsalmon': 0xFFA07A,
  11441. 'lightseagreen': 0x20B2AA,
  11442. 'lightskyblue': 0x87CEFA,
  11443. 'lightslategray': 0x778899,
  11444. 'lightslategrey': 0x778899,
  11445. 'lightsteelblue': 0xB0C4DE,
  11446. 'lightyellow': 0xFFFFE0,
  11447. 'lime': 0x00FF00,
  11448. 'limegreen': 0x32CD32,
  11449. 'linen': 0xFAF0E6,
  11450. 'magenta': 0xFF00FF,
  11451. 'maroon': 0x800000,
  11452. 'mediumaquamarine': 0x66CDAA,
  11453. 'mediumblue': 0x0000CD,
  11454. 'mediumorchid': 0xBA55D3,
  11455. 'mediumpurple': 0x9370DB,
  11456. 'mediumseagreen': 0x3CB371,
  11457. 'mediumslateblue': 0x7B68EE,
  11458. 'mediumspringgreen': 0x00FA9A,
  11459. 'mediumturquoise': 0x48D1CC,
  11460. 'mediumvioletred': 0xC71585,
  11461. 'midnightblue': 0x191970,
  11462. 'mintcream': 0xF5FFFA,
  11463. 'mistyrose': 0xFFE4E1,
  11464. 'moccasin': 0xFFE4B5,
  11465. 'navajowhite': 0xFFDEAD,
  11466. 'navy': 0x000080,
  11467. 'oldlace': 0xFDF5E6,
  11468. 'olive': 0x808000,
  11469. 'olivedrab': 0x6B8E23,
  11470. 'orange': 0xFFA500,
  11471. 'orangered': 0xFF4500,
  11472. 'orchid': 0xDA70D6,
  11473. 'palegoldenrod': 0xEEE8AA,
  11474. 'palegreen': 0x98FB98,
  11475. 'paleturquoise': 0xAFEEEE,
  11476. 'palevioletred': 0xDB7093,
  11477. 'papayawhip': 0xFFEFD5,
  11478. 'peachpuff': 0xFFDAB9,
  11479. 'peru': 0xCD853F,
  11480. 'pink': 0xFFC0CB,
  11481. 'plum': 0xDDA0DD,
  11482. 'powderblue': 0xB0E0E6,
  11483. 'purple': 0x800080,
  11484. 'rebeccapurple': 0x663399,
  11485. 'red': 0xFF0000,
  11486. 'rosybrown': 0xBC8F8F,
  11487. 'royalblue': 0x4169E1,
  11488. 'saddlebrown': 0x8B4513,
  11489. 'salmon': 0xFA8072,
  11490. 'sandybrown': 0xF4A460,
  11491. 'seagreen': 0x2E8B57,
  11492. 'seashell': 0xFFF5EE,
  11493. 'sienna': 0xA0522D,
  11494. 'silver': 0xC0C0C0,
  11495. 'skyblue': 0x87CEEB,
  11496. 'slateblue': 0x6A5ACD,
  11497. 'slategray': 0x708090,
  11498. 'slategrey': 0x708090,
  11499. 'snow': 0xFFFAFA,
  11500. 'springgreen': 0x00FF7F,
  11501. 'steelblue': 0x4682B4,
  11502. 'tan': 0xD2B48C,
  11503. 'teal': 0x008080,
  11504. 'thistle': 0xD8BFD8,
  11505. 'tomato': 0xFF6347,
  11506. 'turquoise': 0x40E0D0,
  11507. 'violet': 0xEE82EE,
  11508. 'wheat': 0xF5DEB3,
  11509. 'white': 0xFFFFFF,
  11510. 'whitesmoke': 0xF5F5F5,
  11511. 'yellow': 0xFFFF00,
  11512. 'yellowgreen': 0x9ACD32
  11513. };
  11514. var _hslA = {
  11515. h: 0,
  11516. s: 0,
  11517. l: 0
  11518. };
  11519. var _hslB = {
  11520. h: 0,
  11521. s: 0,
  11522. l: 0
  11523. };
  11524. function hue2rgb(p, q, t) {
  11525. if (t < 0) t += 1;
  11526. if (t > 1) t -= 1;
  11527. if (t < 1 / 6) return p + (q - p) * 6 * t;
  11528. if (t < 1 / 2) return q;
  11529. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  11530. return p;
  11531. }
  11532. function SRGBToLinear(c) {
  11533. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  11534. }
  11535. function LinearToSRGB(c) {
  11536. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  11537. }
  11538. var Color = /*#__PURE__*/function () {
  11539. function Color(r, g, b) {
  11540. Object.defineProperty(this, 'isColor', {
  11541. value: true
  11542. });
  11543. if (g === undefined && b === undefined) {
  11544. // r is THREE.Color, hex or string
  11545. return this.set(r);
  11546. }
  11547. return this.setRGB(r, g, b);
  11548. }
  11549. var _proto = Color.prototype;
  11550. _proto.set = function set(value) {
  11551. if (value && value.isColor) {
  11552. this.copy(value);
  11553. } else if (typeof value === 'number') {
  11554. this.setHex(value);
  11555. } else if (typeof value === 'string') {
  11556. this.setStyle(value);
  11557. }
  11558. return this;
  11559. };
  11560. _proto.setScalar = function setScalar(scalar) {
  11561. this.r = scalar;
  11562. this.g = scalar;
  11563. this.b = scalar;
  11564. return this;
  11565. };
  11566. _proto.setHex = function setHex(hex) {
  11567. hex = Math.floor(hex);
  11568. this.r = (hex >> 16 & 255) / 255;
  11569. this.g = (hex >> 8 & 255) / 255;
  11570. this.b = (hex & 255) / 255;
  11571. return this;
  11572. };
  11573. _proto.setRGB = function setRGB(r, g, b) {
  11574. this.r = r;
  11575. this.g = g;
  11576. this.b = b;
  11577. return this;
  11578. };
  11579. _proto.setHSL = function setHSL(h, s, l) {
  11580. // h,s,l ranges are in 0.0 - 1.0
  11581. h = MathUtils.euclideanModulo(h, 1);
  11582. s = MathUtils.clamp(s, 0, 1);
  11583. l = MathUtils.clamp(l, 0, 1);
  11584. if (s === 0) {
  11585. this.r = this.g = this.b = l;
  11586. } else {
  11587. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  11588. var q = 2 * l - p;
  11589. this.r = hue2rgb(q, p, h + 1 / 3);
  11590. this.g = hue2rgb(q, p, h);
  11591. this.b = hue2rgb(q, p, h - 1 / 3);
  11592. }
  11593. return this;
  11594. };
  11595. _proto.setStyle = function setStyle(style) {
  11596. function handleAlpha(string) {
  11597. if (string === undefined) return;
  11598. if (parseFloat(string) < 1) {
  11599. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  11600. }
  11601. }
  11602. var m;
  11603. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  11604. // rgb / hsl
  11605. var color;
  11606. var name = m[1];
  11607. var components = m[2];
  11608. switch (name) {
  11609. case 'rgb':
  11610. case 'rgba':
  11611. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11612. // rgb(255,0,0) rgba(255,0,0,0.5)
  11613. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  11614. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  11615. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  11616. handleAlpha(color[4]);
  11617. return this;
  11618. }
  11619. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11620. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11621. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  11622. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  11623. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  11624. handleAlpha(color[4]);
  11625. return this;
  11626. }
  11627. break;
  11628. case 'hsl':
  11629. case 'hsla':
  11630. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11631. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11632. var h = parseFloat(color[1]) / 360;
  11633. var s = parseInt(color[2], 10) / 100;
  11634. var l = parseInt(color[3], 10) / 100;
  11635. handleAlpha(color[4]);
  11636. return this.setHSL(h, s, l);
  11637. }
  11638. break;
  11639. }
  11640. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  11641. // hex color
  11642. var hex = m[1];
  11643. var size = hex.length;
  11644. if (size === 3) {
  11645. // #ff0
  11646. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  11647. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  11648. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  11649. return this;
  11650. } else if (size === 6) {
  11651. // #ff0000
  11652. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  11653. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  11654. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  11655. return this;
  11656. }
  11657. }
  11658. if (style && style.length > 0) {
  11659. return this.setColorName(style);
  11660. }
  11661. return this;
  11662. };
  11663. _proto.setColorName = function setColorName(style) {
  11664. // color keywords
  11665. var hex = _colorKeywords[style];
  11666. if (hex !== undefined) {
  11667. // red
  11668. this.setHex(hex);
  11669. } else {
  11670. // unknown color
  11671. console.warn('THREE.Color: Unknown color ' + style);
  11672. }
  11673. return this;
  11674. };
  11675. _proto.clone = function clone() {
  11676. return new this.constructor(this.r, this.g, this.b);
  11677. };
  11678. _proto.copy = function copy(color) {
  11679. this.r = color.r;
  11680. this.g = color.g;
  11681. this.b = color.b;
  11682. return this;
  11683. };
  11684. _proto.copyGammaToLinear = function copyGammaToLinear(color, gammaFactor) {
  11685. if (gammaFactor === void 0) {
  11686. gammaFactor = 2.0;
  11687. }
  11688. this.r = Math.pow(color.r, gammaFactor);
  11689. this.g = Math.pow(color.g, gammaFactor);
  11690. this.b = Math.pow(color.b, gammaFactor);
  11691. return this;
  11692. };
  11693. _proto.copyLinearToGamma = function copyLinearToGamma(color, gammaFactor) {
  11694. if (gammaFactor === void 0) {
  11695. gammaFactor = 2.0;
  11696. }
  11697. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  11698. this.r = Math.pow(color.r, safeInverse);
  11699. this.g = Math.pow(color.g, safeInverse);
  11700. this.b = Math.pow(color.b, safeInverse);
  11701. return this;
  11702. };
  11703. _proto.convertGammaToLinear = function convertGammaToLinear(gammaFactor) {
  11704. this.copyGammaToLinear(this, gammaFactor);
  11705. return this;
  11706. };
  11707. _proto.convertLinearToGamma = function convertLinearToGamma(gammaFactor) {
  11708. this.copyLinearToGamma(this, gammaFactor);
  11709. return this;
  11710. };
  11711. _proto.copySRGBToLinear = function copySRGBToLinear(color) {
  11712. this.r = SRGBToLinear(color.r);
  11713. this.g = SRGBToLinear(color.g);
  11714. this.b = SRGBToLinear(color.b);
  11715. return this;
  11716. };
  11717. _proto.copyLinearToSRGB = function copyLinearToSRGB(color) {
  11718. this.r = LinearToSRGB(color.r);
  11719. this.g = LinearToSRGB(color.g);
  11720. this.b = LinearToSRGB(color.b);
  11721. return this;
  11722. };
  11723. _proto.convertSRGBToLinear = function convertSRGBToLinear() {
  11724. this.copySRGBToLinear(this);
  11725. return this;
  11726. };
  11727. _proto.convertLinearToSRGB = function convertLinearToSRGB() {
  11728. this.copyLinearToSRGB(this);
  11729. return this;
  11730. };
  11731. _proto.getHex = function getHex() {
  11732. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  11733. };
  11734. _proto.getHexString = function getHexString() {
  11735. return ('000000' + this.getHex().toString(16)).slice(-6);
  11736. };
  11737. _proto.getHSL = function getHSL(target) {
  11738. // h,s,l ranges are in 0.0 - 1.0
  11739. if (target === undefined) {
  11740. console.warn('THREE.Color: .getHSL() target is now required');
  11741. target = {
  11742. h: 0,
  11743. s: 0,
  11744. l: 0
  11745. };
  11746. }
  11747. var r = this.r,
  11748. g = this.g,
  11749. b = this.b;
  11750. var max = Math.max(r, g, b);
  11751. var min = Math.min(r, g, b);
  11752. var hue, saturation;
  11753. var lightness = (min + max) / 2.0;
  11754. if (min === max) {
  11755. hue = 0;
  11756. saturation = 0;
  11757. } else {
  11758. var delta = max - min;
  11759. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  11760. switch (max) {
  11761. case r:
  11762. hue = (g - b) / delta + (g < b ? 6 : 0);
  11763. break;
  11764. case g:
  11765. hue = (b - r) / delta + 2;
  11766. break;
  11767. case b:
  11768. hue = (r - g) / delta + 4;
  11769. break;
  11770. }
  11771. hue /= 6;
  11772. }
  11773. target.h = hue;
  11774. target.s = saturation;
  11775. target.l = lightness;
  11776. return target;
  11777. };
  11778. _proto.getStyle = function getStyle() {
  11779. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  11780. };
  11781. _proto.offsetHSL = function offsetHSL(h, s, l) {
  11782. this.getHSL(_hslA);
  11783. _hslA.h += h;
  11784. _hslA.s += s;
  11785. _hslA.l += l;
  11786. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  11787. return this;
  11788. };
  11789. _proto.add = function add(color) {
  11790. this.r += color.r;
  11791. this.g += color.g;
  11792. this.b += color.b;
  11793. return this;
  11794. };
  11795. _proto.addColors = function addColors(color1, color2) {
  11796. this.r = color1.r + color2.r;
  11797. this.g = color1.g + color2.g;
  11798. this.b = color1.b + color2.b;
  11799. return this;
  11800. };
  11801. _proto.addScalar = function addScalar(s) {
  11802. this.r += s;
  11803. this.g += s;
  11804. this.b += s;
  11805. return this;
  11806. };
  11807. _proto.sub = function sub(color) {
  11808. this.r = Math.max(0, this.r - color.r);
  11809. this.g = Math.max(0, this.g - color.g);
  11810. this.b = Math.max(0, this.b - color.b);
  11811. return this;
  11812. };
  11813. _proto.multiply = function multiply(color) {
  11814. this.r *= color.r;
  11815. this.g *= color.g;
  11816. this.b *= color.b;
  11817. return this;
  11818. };
  11819. _proto.multiplyScalar = function multiplyScalar(s) {
  11820. this.r *= s;
  11821. this.g *= s;
  11822. this.b *= s;
  11823. return this;
  11824. };
  11825. _proto.lerp = function lerp(color, alpha) {
  11826. this.r += (color.r - this.r) * alpha;
  11827. this.g += (color.g - this.g) * alpha;
  11828. this.b += (color.b - this.b) * alpha;
  11829. return this;
  11830. };
  11831. _proto.lerpColors = function lerpColors(color1, color2, alpha) {
  11832. this.r = color1.r + (color2.r - color1.r) * alpha;
  11833. this.g = color1.g + (color2.g - color1.g) * alpha;
  11834. this.b = color1.b + (color2.b - color1.b) * alpha;
  11835. return this;
  11836. };
  11837. _proto.lerpHSL = function lerpHSL(color, alpha) {
  11838. this.getHSL(_hslA);
  11839. color.getHSL(_hslB);
  11840. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  11841. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  11842. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  11843. this.setHSL(h, s, l);
  11844. return this;
  11845. };
  11846. _proto.equals = function equals(c) {
  11847. return c.r === this.r && c.g === this.g && c.b === this.b;
  11848. };
  11849. _proto.fromArray = function fromArray(array, offset) {
  11850. if (offset === void 0) {
  11851. offset = 0;
  11852. }
  11853. this.r = array[offset];
  11854. this.g = array[offset + 1];
  11855. this.b = array[offset + 2];
  11856. return this;
  11857. };
  11858. _proto.toArray = function toArray(array, offset) {
  11859. if (array === void 0) {
  11860. array = [];
  11861. }
  11862. if (offset === void 0) {
  11863. offset = 0;
  11864. }
  11865. array[offset] = this.r;
  11866. array[offset + 1] = this.g;
  11867. array[offset + 2] = this.b;
  11868. return array;
  11869. };
  11870. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  11871. this.r = attribute.getX(index);
  11872. this.g = attribute.getY(index);
  11873. this.b = attribute.getZ(index);
  11874. if (attribute.normalized === true) {
  11875. // assuming Uint8Array
  11876. this.r /= 255;
  11877. this.g /= 255;
  11878. this.b /= 255;
  11879. }
  11880. return this;
  11881. };
  11882. _proto.toJSON = function toJSON() {
  11883. return this.getHex();
  11884. };
  11885. return Color;
  11886. }();
  11887. Color.NAMES = _colorKeywords;
  11888. Color.prototype.r = 1;
  11889. Color.prototype.g = 1;
  11890. Color.prototype.b = 1;
  11891. var Face3 = /*#__PURE__*/function () {
  11892. function Face3(a, b, c, normal, color, materialIndex) {
  11893. if (materialIndex === void 0) {
  11894. materialIndex = 0;
  11895. }
  11896. this.a = a;
  11897. this.b = b;
  11898. this.c = c;
  11899. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  11900. this.vertexNormals = Array.isArray(normal) ? normal : [];
  11901. this.color = color && color.isColor ? color : new Color();
  11902. this.vertexColors = Array.isArray(color) ? color : [];
  11903. this.materialIndex = materialIndex;
  11904. }
  11905. var _proto = Face3.prototype;
  11906. _proto.clone = function clone() {
  11907. return new this.constructor().copy(this);
  11908. };
  11909. _proto.copy = function copy(source) {
  11910. this.a = source.a;
  11911. this.b = source.b;
  11912. this.c = source.c;
  11913. this.normal.copy(source.normal);
  11914. this.color.copy(source.color);
  11915. this.materialIndex = source.materialIndex;
  11916. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  11917. this.vertexNormals[i] = source.vertexNormals[i].clone();
  11918. }
  11919. for (var _i = 0, _il = source.vertexColors.length; _i < _il; _i++) {
  11920. this.vertexColors[_i] = source.vertexColors[_i].clone();
  11921. }
  11922. return this;
  11923. };
  11924. return Face3;
  11925. }();
  11926. var materialId = 0;
  11927. function Material() {
  11928. Object.defineProperty(this, 'id', {
  11929. value: materialId++
  11930. });
  11931. this.uuid = MathUtils.generateUUID();
  11932. this.name = '';
  11933. this.type = 'Material';
  11934. this.fog = true;
  11935. this.blending = NormalBlending;
  11936. this.side = FrontSide;
  11937. this.flatShading = false;
  11938. this.vertexColors = false;
  11939. this.opacity = 1;
  11940. this.transparent = false;
  11941. this.blendSrc = SrcAlphaFactor;
  11942. this.blendDst = OneMinusSrcAlphaFactor;
  11943. this.blendEquation = AddEquation;
  11944. this.blendSrcAlpha = null;
  11945. this.blendDstAlpha = null;
  11946. this.blendEquationAlpha = null;
  11947. this.depthFunc = LessEqualDepth;
  11948. this.depthTest = true;
  11949. this.depthWrite = true;
  11950. this.stencilWriteMask = 0xff;
  11951. this.stencilFunc = AlwaysStencilFunc;
  11952. this.stencilRef = 0;
  11953. this.stencilFuncMask = 0xff;
  11954. this.stencilFail = KeepStencilOp;
  11955. this.stencilZFail = KeepStencilOp;
  11956. this.stencilZPass = KeepStencilOp;
  11957. this.stencilWrite = false;
  11958. this.clippingPlanes = null;
  11959. this.clipIntersection = false;
  11960. this.clipShadows = false;
  11961. this.shadowSide = null;
  11962. this.colorWrite = true;
  11963. this.precision = null; // override the renderer's default precision for this material
  11964. this.polygonOffset = false;
  11965. this.polygonOffsetFactor = 0;
  11966. this.polygonOffsetUnits = 0;
  11967. this.dithering = false;
  11968. this.alphaTest = 0;
  11969. this.premultipliedAlpha = false;
  11970. this.visible = true;
  11971. this.toneMapped = true;
  11972. this.userData = {};
  11973. this.version = 0;
  11974. }
  11975. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  11976. constructor: Material,
  11977. isMaterial: true,
  11978. onBeforeCompile: function onBeforeCompile()
  11979. /* shaderobject, renderer */
  11980. {},
  11981. customProgramCacheKey: function customProgramCacheKey() {
  11982. return this.onBeforeCompile.toString();
  11983. },
  11984. setValues: function setValues(values) {
  11985. if (values === undefined) return;
  11986. for (var key in values) {
  11987. var newValue = values[key];
  11988. if (newValue === undefined) {
  11989. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  11990. continue;
  11991. } // for backward compatability if shading is set in the constructor
  11992. if (key === 'shading') {
  11993. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  11994. this.flatShading = newValue === FlatShading ? true : false;
  11995. continue;
  11996. }
  11997. var currentValue = this[key];
  11998. if (currentValue === undefined) {
  11999. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  12000. continue;
  12001. }
  12002. if (currentValue && currentValue.isColor) {
  12003. currentValue.set(newValue);
  12004. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  12005. currentValue.copy(newValue);
  12006. } else {
  12007. this[key] = newValue;
  12008. }
  12009. }
  12010. },
  12011. toJSON: function toJSON(meta) {
  12012. var isRoot = meta === undefined || typeof meta === 'string';
  12013. if (isRoot) {
  12014. meta = {
  12015. textures: {},
  12016. images: {}
  12017. };
  12018. }
  12019. var data = {
  12020. metadata: {
  12021. version: 4.5,
  12022. type: 'Material',
  12023. generator: 'Material.toJSON'
  12024. }
  12025. }; // standard Material serialization
  12026. data.uuid = this.uuid;
  12027. data.type = this.type;
  12028. if (this.name !== '') data.name = this.name;
  12029. if (this.color && this.color.isColor) data.color = this.color.getHex();
  12030. if (this.roughness !== undefined) data.roughness = this.roughness;
  12031. if (this.metalness !== undefined) data.metalness = this.metalness;
  12032. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  12033. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  12034. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  12035. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  12036. if (this.shininess !== undefined) data.shininess = this.shininess;
  12037. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  12038. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  12039. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  12040. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  12041. }
  12042. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  12043. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  12044. }
  12045. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  12046. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  12047. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12048. }
  12049. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  12050. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  12051. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  12052. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  12053. if (this.aoMap && this.aoMap.isTexture) {
  12054. data.aoMap = this.aoMap.toJSON(meta).uuid;
  12055. data.aoMapIntensity = this.aoMapIntensity;
  12056. }
  12057. if (this.bumpMap && this.bumpMap.isTexture) {
  12058. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  12059. data.bumpScale = this.bumpScale;
  12060. }
  12061. if (this.normalMap && this.normalMap.isTexture) {
  12062. data.normalMap = this.normalMap.toJSON(meta).uuid;
  12063. data.normalMapType = this.normalMapType;
  12064. data.normalScale = this.normalScale.toArray();
  12065. }
  12066. if (this.displacementMap && this.displacementMap.isTexture) {
  12067. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  12068. data.displacementScale = this.displacementScale;
  12069. data.displacementBias = this.displacementBias;
  12070. }
  12071. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  12072. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  12073. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  12074. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  12075. if (this.envMap && this.envMap.isTexture) {
  12076. data.envMap = this.envMap.toJSON(meta).uuid;
  12077. data.reflectivity = this.reflectivity; // Scale behind envMap
  12078. data.refractionRatio = this.refractionRatio;
  12079. if (this.combine !== undefined) data.combine = this.combine;
  12080. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  12081. }
  12082. if (this.gradientMap && this.gradientMap.isTexture) {
  12083. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  12084. }
  12085. if (this.size !== undefined) data.size = this.size;
  12086. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  12087. if (this.blending !== NormalBlending) data.blending = this.blending;
  12088. if (this.flatShading === true) data.flatShading = this.flatShading;
  12089. if (this.side !== FrontSide) data.side = this.side;
  12090. if (this.vertexColors) data.vertexColors = true;
  12091. if (this.opacity < 1) data.opacity = this.opacity;
  12092. if (this.transparent === true) data.transparent = this.transparent;
  12093. data.depthFunc = this.depthFunc;
  12094. data.depthTest = this.depthTest;
  12095. data.depthWrite = this.depthWrite;
  12096. data.stencilWrite = this.stencilWrite;
  12097. data.stencilWriteMask = this.stencilWriteMask;
  12098. data.stencilFunc = this.stencilFunc;
  12099. data.stencilRef = this.stencilRef;
  12100. data.stencilFuncMask = this.stencilFuncMask;
  12101. data.stencilFail = this.stencilFail;
  12102. data.stencilZFail = this.stencilZFail;
  12103. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  12104. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  12105. if (this.polygonOffset === true) data.polygonOffset = true;
  12106. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12107. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12108. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  12109. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  12110. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  12111. if (this.scale !== undefined) data.scale = this.scale;
  12112. if (this.dithering === true) data.dithering = true;
  12113. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  12114. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  12115. if (this.wireframe === true) data.wireframe = this.wireframe;
  12116. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  12117. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  12118. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  12119. if (this.morphTargets === true) data.morphTargets = true;
  12120. if (this.morphNormals === true) data.morphNormals = true;
  12121. if (this.skinning === true) data.skinning = true;
  12122. if (this.visible === false) data.visible = false;
  12123. if (this.toneMapped === false) data.toneMapped = false;
  12124. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  12125. function extractFromCache(cache) {
  12126. var values = [];
  12127. for (var key in cache) {
  12128. var _data = cache[key];
  12129. delete _data.metadata;
  12130. values.push(_data);
  12131. }
  12132. return values;
  12133. }
  12134. if (isRoot) {
  12135. var textures = extractFromCache(meta.textures);
  12136. var images = extractFromCache(meta.images);
  12137. if (textures.length > 0) data.textures = textures;
  12138. if (images.length > 0) data.images = images;
  12139. }
  12140. return data;
  12141. },
  12142. clone: function clone() {
  12143. return new this.constructor().copy(this);
  12144. },
  12145. copy: function copy(source) {
  12146. this.name = source.name;
  12147. this.fog = source.fog;
  12148. this.blending = source.blending;
  12149. this.side = source.side;
  12150. this.flatShading = source.flatShading;
  12151. this.vertexColors = source.vertexColors;
  12152. this.opacity = source.opacity;
  12153. this.transparent = source.transparent;
  12154. this.blendSrc = source.blendSrc;
  12155. this.blendDst = source.blendDst;
  12156. this.blendEquation = source.blendEquation;
  12157. this.blendSrcAlpha = source.blendSrcAlpha;
  12158. this.blendDstAlpha = source.blendDstAlpha;
  12159. this.blendEquationAlpha = source.blendEquationAlpha;
  12160. this.depthFunc = source.depthFunc;
  12161. this.depthTest = source.depthTest;
  12162. this.depthWrite = source.depthWrite;
  12163. this.stencilWriteMask = source.stencilWriteMask;
  12164. this.stencilFunc = source.stencilFunc;
  12165. this.stencilRef = source.stencilRef;
  12166. this.stencilFuncMask = source.stencilFuncMask;
  12167. this.stencilFail = source.stencilFail;
  12168. this.stencilZFail = source.stencilZFail;
  12169. this.stencilZPass = source.stencilZPass;
  12170. this.stencilWrite = source.stencilWrite;
  12171. var srcPlanes = source.clippingPlanes;
  12172. var dstPlanes = null;
  12173. if (srcPlanes !== null) {
  12174. var n = srcPlanes.length;
  12175. dstPlanes = new Array(n);
  12176. for (var i = 0; i !== n; ++i) {
  12177. dstPlanes[i] = srcPlanes[i].clone();
  12178. }
  12179. }
  12180. this.clippingPlanes = dstPlanes;
  12181. this.clipIntersection = source.clipIntersection;
  12182. this.clipShadows = source.clipShadows;
  12183. this.shadowSide = source.shadowSide;
  12184. this.colorWrite = source.colorWrite;
  12185. this.precision = source.precision;
  12186. this.polygonOffset = source.polygonOffset;
  12187. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12188. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12189. this.dithering = source.dithering;
  12190. this.alphaTest = source.alphaTest;
  12191. this.premultipliedAlpha = source.premultipliedAlpha;
  12192. this.visible = source.visible;
  12193. this.toneMapped = source.toneMapped;
  12194. this.userData = JSON.parse(JSON.stringify(source.userData));
  12195. return this;
  12196. },
  12197. dispose: function dispose() {
  12198. this.dispatchEvent({
  12199. type: 'dispose'
  12200. });
  12201. }
  12202. });
  12203. Object.defineProperty(Material.prototype, 'needsUpdate', {
  12204. set: function set(value) {
  12205. if (value === true) this.version++;
  12206. }
  12207. });
  12208. /**
  12209. * parameters = {
  12210. * color: <hex>,
  12211. * opacity: <float>,
  12212. * map: new THREE.Texture( <Image> ),
  12213. *
  12214. * lightMap: new THREE.Texture( <Image> ),
  12215. * lightMapIntensity: <float>
  12216. *
  12217. * aoMap: new THREE.Texture( <Image> ),
  12218. * aoMapIntensity: <float>
  12219. *
  12220. * specularMap: new THREE.Texture( <Image> ),
  12221. *
  12222. * alphaMap: new THREE.Texture( <Image> ),
  12223. *
  12224. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12225. * combine: THREE.Multiply,
  12226. * reflectivity: <float>,
  12227. * refractionRatio: <float>,
  12228. *
  12229. * depthTest: <bool>,
  12230. * depthWrite: <bool>,
  12231. *
  12232. * wireframe: <boolean>,
  12233. * wireframeLinewidth: <float>,
  12234. *
  12235. * skinning: <bool>,
  12236. * morphTargets: <bool>
  12237. * }
  12238. */
  12239. function MeshBasicMaterial(parameters) {
  12240. Material.call(this);
  12241. this.type = 'MeshBasicMaterial';
  12242. this.color = new Color(0xffffff); // emissive
  12243. this.map = null;
  12244. this.lightMap = null;
  12245. this.lightMapIntensity = 1.0;
  12246. this.aoMap = null;
  12247. this.aoMapIntensity = 1.0;
  12248. this.specularMap = null;
  12249. this.alphaMap = null;
  12250. this.envMap = null;
  12251. this.combine = MultiplyOperation;
  12252. this.reflectivity = 1;
  12253. this.refractionRatio = 0.98;
  12254. this.wireframe = false;
  12255. this.wireframeLinewidth = 1;
  12256. this.wireframeLinecap = 'round';
  12257. this.wireframeLinejoin = 'round';
  12258. this.skinning = false;
  12259. this.morphTargets = false;
  12260. this.setValues(parameters);
  12261. }
  12262. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  12263. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  12264. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  12265. MeshBasicMaterial.prototype.copy = function (source) {
  12266. Material.prototype.copy.call(this, source);
  12267. this.color.copy(source.color);
  12268. this.map = source.map;
  12269. this.lightMap = source.lightMap;
  12270. this.lightMapIntensity = source.lightMapIntensity;
  12271. this.aoMap = source.aoMap;
  12272. this.aoMapIntensity = source.aoMapIntensity;
  12273. this.specularMap = source.specularMap;
  12274. this.alphaMap = source.alphaMap;
  12275. this.envMap = source.envMap;
  12276. this.combine = source.combine;
  12277. this.reflectivity = source.reflectivity;
  12278. this.refractionRatio = source.refractionRatio;
  12279. this.wireframe = source.wireframe;
  12280. this.wireframeLinewidth = source.wireframeLinewidth;
  12281. this.wireframeLinecap = source.wireframeLinecap;
  12282. this.wireframeLinejoin = source.wireframeLinejoin;
  12283. this.skinning = source.skinning;
  12284. this.morphTargets = source.morphTargets;
  12285. return this;
  12286. };
  12287. var _vector$3 = new Vector3();
  12288. var _vector2$1 = new Vector2();
  12289. function BufferAttribute(array, itemSize, normalized) {
  12290. if (Array.isArray(array)) {
  12291. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  12292. }
  12293. this.name = '';
  12294. this.array = array;
  12295. this.itemSize = itemSize;
  12296. this.count = array !== undefined ? array.length / itemSize : 0;
  12297. this.normalized = normalized === true;
  12298. this.usage = StaticDrawUsage;
  12299. this.updateRange = {
  12300. offset: 0,
  12301. count: -1
  12302. };
  12303. this.version = 0;
  12304. }
  12305. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  12306. set: function set(value) {
  12307. if (value === true) this.version++;
  12308. }
  12309. });
  12310. Object.assign(BufferAttribute.prototype, {
  12311. isBufferAttribute: true,
  12312. onUploadCallback: function onUploadCallback() {},
  12313. setUsage: function setUsage(value) {
  12314. this.usage = value;
  12315. return this;
  12316. },
  12317. copy: function copy(source) {
  12318. this.name = source.name;
  12319. this.array = new source.array.constructor(source.array);
  12320. this.itemSize = source.itemSize;
  12321. this.count = source.count;
  12322. this.normalized = source.normalized;
  12323. this.usage = source.usage;
  12324. return this;
  12325. },
  12326. copyAt: function copyAt(index1, attribute, index2) {
  12327. index1 *= this.itemSize;
  12328. index2 *= attribute.itemSize;
  12329. for (var i = 0, l = this.itemSize; i < l; i++) {
  12330. this.array[index1 + i] = attribute.array[index2 + i];
  12331. }
  12332. return this;
  12333. },
  12334. copyArray: function copyArray(array) {
  12335. this.array.set(array);
  12336. return this;
  12337. },
  12338. copyColorsArray: function copyColorsArray(colors) {
  12339. var array = this.array;
  12340. var offset = 0;
  12341. for (var i = 0, l = colors.length; i < l; i++) {
  12342. var color = colors[i];
  12343. if (color === undefined) {
  12344. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  12345. color = new Color();
  12346. }
  12347. array[offset++] = color.r;
  12348. array[offset++] = color.g;
  12349. array[offset++] = color.b;
  12350. }
  12351. return this;
  12352. },
  12353. copyVector2sArray: function copyVector2sArray(vectors) {
  12354. var array = this.array;
  12355. var offset = 0;
  12356. for (var i = 0, l = vectors.length; i < l; i++) {
  12357. var vector = vectors[i];
  12358. if (vector === undefined) {
  12359. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  12360. vector = new Vector2();
  12361. }
  12362. array[offset++] = vector.x;
  12363. array[offset++] = vector.y;
  12364. }
  12365. return this;
  12366. },
  12367. copyVector3sArray: function copyVector3sArray(vectors) {
  12368. var array = this.array;
  12369. var offset = 0;
  12370. for (var i = 0, l = vectors.length; i < l; i++) {
  12371. var vector = vectors[i];
  12372. if (vector === undefined) {
  12373. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  12374. vector = new Vector3();
  12375. }
  12376. array[offset++] = vector.x;
  12377. array[offset++] = vector.y;
  12378. array[offset++] = vector.z;
  12379. }
  12380. return this;
  12381. },
  12382. copyVector4sArray: function copyVector4sArray(vectors) {
  12383. var array = this.array;
  12384. var offset = 0;
  12385. for (var i = 0, l = vectors.length; i < l; i++) {
  12386. var vector = vectors[i];
  12387. if (vector === undefined) {
  12388. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  12389. vector = new Vector4();
  12390. }
  12391. array[offset++] = vector.x;
  12392. array[offset++] = vector.y;
  12393. array[offset++] = vector.z;
  12394. array[offset++] = vector.w;
  12395. }
  12396. return this;
  12397. },
  12398. applyMatrix3: function applyMatrix3(m) {
  12399. if (this.itemSize === 2) {
  12400. for (var i = 0, l = this.count; i < l; i++) {
  12401. _vector2$1.fromBufferAttribute(this, i);
  12402. _vector2$1.applyMatrix3(m);
  12403. this.setXY(i, _vector2$1.x, _vector2$1.y);
  12404. }
  12405. } else if (this.itemSize === 3) {
  12406. for (var _i = 0, _l = this.count; _i < _l; _i++) {
  12407. _vector$3.fromBufferAttribute(this, _i);
  12408. _vector$3.applyMatrix3(m);
  12409. this.setXYZ(_i, _vector$3.x, _vector$3.y, _vector$3.z);
  12410. }
  12411. }
  12412. return this;
  12413. },
  12414. applyMatrix4: function applyMatrix4(m) {
  12415. for (var i = 0, l = this.count; i < l; i++) {
  12416. _vector$3.x = this.getX(i);
  12417. _vector$3.y = this.getY(i);
  12418. _vector$3.z = this.getZ(i);
  12419. _vector$3.applyMatrix4(m);
  12420. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12421. }
  12422. return this;
  12423. },
  12424. applyNormalMatrix: function applyNormalMatrix(m) {
  12425. for (var i = 0, l = this.count; i < l; i++) {
  12426. _vector$3.x = this.getX(i);
  12427. _vector$3.y = this.getY(i);
  12428. _vector$3.z = this.getZ(i);
  12429. _vector$3.applyNormalMatrix(m);
  12430. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12431. }
  12432. return this;
  12433. },
  12434. transformDirection: function transformDirection(m) {
  12435. for (var i = 0, l = this.count; i < l; i++) {
  12436. _vector$3.x = this.getX(i);
  12437. _vector$3.y = this.getY(i);
  12438. _vector$3.z = this.getZ(i);
  12439. _vector$3.transformDirection(m);
  12440. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12441. }
  12442. return this;
  12443. },
  12444. set: function set(value, offset) {
  12445. if (offset === void 0) {
  12446. offset = 0;
  12447. }
  12448. this.array.set(value, offset);
  12449. return this;
  12450. },
  12451. getX: function getX(index) {
  12452. return this.array[index * this.itemSize];
  12453. },
  12454. setX: function setX(index, x) {
  12455. this.array[index * this.itemSize] = x;
  12456. return this;
  12457. },
  12458. getY: function getY(index) {
  12459. return this.array[index * this.itemSize + 1];
  12460. },
  12461. setY: function setY(index, y) {
  12462. this.array[index * this.itemSize + 1] = y;
  12463. return this;
  12464. },
  12465. getZ: function getZ(index) {
  12466. return this.array[index * this.itemSize + 2];
  12467. },
  12468. setZ: function setZ(index, z) {
  12469. this.array[index * this.itemSize + 2] = z;
  12470. return this;
  12471. },
  12472. getW: function getW(index) {
  12473. return this.array[index * this.itemSize + 3];
  12474. },
  12475. setW: function setW(index, w) {
  12476. this.array[index * this.itemSize + 3] = w;
  12477. return this;
  12478. },
  12479. setXY: function setXY(index, x, y) {
  12480. index *= this.itemSize;
  12481. this.array[index + 0] = x;
  12482. this.array[index + 1] = y;
  12483. return this;
  12484. },
  12485. setXYZ: function setXYZ(index, x, y, z) {
  12486. index *= this.itemSize;
  12487. this.array[index + 0] = x;
  12488. this.array[index + 1] = y;
  12489. this.array[index + 2] = z;
  12490. return this;
  12491. },
  12492. setXYZW: function setXYZW(index, x, y, z, w) {
  12493. index *= this.itemSize;
  12494. this.array[index + 0] = x;
  12495. this.array[index + 1] = y;
  12496. this.array[index + 2] = z;
  12497. this.array[index + 3] = w;
  12498. return this;
  12499. },
  12500. onUpload: function onUpload(callback) {
  12501. this.onUploadCallback = callback;
  12502. return this;
  12503. },
  12504. clone: function clone() {
  12505. return new this.constructor(this.array, this.itemSize).copy(this);
  12506. },
  12507. toJSON: function toJSON() {
  12508. return {
  12509. itemSize: this.itemSize,
  12510. type: this.array.constructor.name,
  12511. array: Array.prototype.slice.call(this.array),
  12512. normalized: this.normalized
  12513. };
  12514. }
  12515. }); //
  12516. function Int8BufferAttribute(array, itemSize, normalized) {
  12517. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  12518. }
  12519. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12520. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  12521. function Uint8BufferAttribute(array, itemSize, normalized) {
  12522. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  12523. }
  12524. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12525. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  12526. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  12527. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  12528. }
  12529. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12530. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  12531. function Int16BufferAttribute(array, itemSize, normalized) {
  12532. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  12533. }
  12534. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12535. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  12536. function Uint16BufferAttribute(array, itemSize, normalized) {
  12537. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  12538. }
  12539. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12540. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  12541. function Int32BufferAttribute(array, itemSize, normalized) {
  12542. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  12543. }
  12544. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12545. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  12546. function Uint32BufferAttribute(array, itemSize, normalized) {
  12547. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  12548. }
  12549. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12550. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  12551. function Float16BufferAttribute(array, itemSize, normalized) {
  12552. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  12553. }
  12554. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12555. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  12556. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  12557. function Float32BufferAttribute(array, itemSize, normalized) {
  12558. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  12559. }
  12560. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12561. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  12562. function Float64BufferAttribute(array, itemSize, normalized) {
  12563. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  12564. }
  12565. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12566. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; //
  12567. function arrayMax(array) {
  12568. if (array.length === 0) return -Infinity;
  12569. var max = array[0];
  12570. for (var i = 1, l = array.length; i < l; ++i) {
  12571. if (array[i] > max) max = array[i];
  12572. }
  12573. return max;
  12574. }
  12575. var TYPED_ARRAYS = {
  12576. Int8Array: Int8Array,
  12577. Uint8Array: Uint8Array,
  12578. // Workaround for IE11 pre KB2929437. See #11440
  12579. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  12580. Int16Array: Int16Array,
  12581. Uint16Array: Uint16Array,
  12582. Int32Array: Int32Array,
  12583. Uint32Array: Uint32Array,
  12584. Float32Array: Float32Array,
  12585. Float64Array: Float64Array
  12586. };
  12587. function getTypedArray(type, buffer) {
  12588. return new TYPED_ARRAYS[type](buffer);
  12589. }
  12590. var _id = 0;
  12591. var _m1$2 = new Matrix4();
  12592. var _obj = new Object3D();
  12593. var _offset = new Vector3();
  12594. var _box$2 = new Box3();
  12595. var _boxMorphTargets = new Box3();
  12596. var _vector$4 = new Vector3();
  12597. function BufferGeometry() {
  12598. Object.defineProperty(this, 'id', {
  12599. value: _id++
  12600. });
  12601. this.uuid = MathUtils.generateUUID();
  12602. this.name = '';
  12603. this.type = 'BufferGeometry';
  12604. this.index = null;
  12605. this.attributes = {};
  12606. this.morphAttributes = {};
  12607. this.morphTargetsRelative = false;
  12608. this.groups = [];
  12609. this.boundingBox = null;
  12610. this.boundingSphere = null;
  12611. this.drawRange = {
  12612. start: 0,
  12613. count: Infinity
  12614. };
  12615. this.userData = {};
  12616. }
  12617. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  12618. constructor: BufferGeometry,
  12619. isBufferGeometry: true,
  12620. getIndex: function getIndex() {
  12621. return this.index;
  12622. },
  12623. setIndex: function setIndex(index) {
  12624. if (Array.isArray(index)) {
  12625. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  12626. } else {
  12627. this.index = index;
  12628. }
  12629. return this;
  12630. },
  12631. getAttribute: function getAttribute(name) {
  12632. return this.attributes[name];
  12633. },
  12634. setAttribute: function setAttribute(name, attribute) {
  12635. this.attributes[name] = attribute;
  12636. return this;
  12637. },
  12638. deleteAttribute: function deleteAttribute(name) {
  12639. delete this.attributes[name];
  12640. return this;
  12641. },
  12642. hasAttribute: function hasAttribute(name) {
  12643. return this.attributes[name] !== undefined;
  12644. },
  12645. addGroup: function addGroup(start, count, materialIndex) {
  12646. if (materialIndex === void 0) {
  12647. materialIndex = 0;
  12648. }
  12649. this.groups.push({
  12650. start: start,
  12651. count: count,
  12652. materialIndex: materialIndex
  12653. });
  12654. },
  12655. clearGroups: function clearGroups() {
  12656. this.groups = [];
  12657. },
  12658. setDrawRange: function setDrawRange(start, count) {
  12659. this.drawRange.start = start;
  12660. this.drawRange.count = count;
  12661. },
  12662. applyMatrix4: function applyMatrix4(matrix) {
  12663. var position = this.attributes.position;
  12664. if (position !== undefined) {
  12665. position.applyMatrix4(matrix);
  12666. position.needsUpdate = true;
  12667. }
  12668. var normal = this.attributes.normal;
  12669. if (normal !== undefined) {
  12670. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  12671. normal.applyNormalMatrix(normalMatrix);
  12672. normal.needsUpdate = true;
  12673. }
  12674. var tangent = this.attributes.tangent;
  12675. if (tangent !== undefined) {
  12676. tangent.transformDirection(matrix);
  12677. tangent.needsUpdate = true;
  12678. }
  12679. if (this.boundingBox !== null) {
  12680. this.computeBoundingBox();
  12681. }
  12682. if (this.boundingSphere !== null) {
  12683. this.computeBoundingSphere();
  12684. }
  12685. return this;
  12686. },
  12687. rotateX: function rotateX(angle) {
  12688. // rotate geometry around world x-axis
  12689. _m1$2.makeRotationX(angle);
  12690. this.applyMatrix4(_m1$2);
  12691. return this;
  12692. },
  12693. rotateY: function rotateY(angle) {
  12694. // rotate geometry around world y-axis
  12695. _m1$2.makeRotationY(angle);
  12696. this.applyMatrix4(_m1$2);
  12697. return this;
  12698. },
  12699. rotateZ: function rotateZ(angle) {
  12700. // rotate geometry around world z-axis
  12701. _m1$2.makeRotationZ(angle);
  12702. this.applyMatrix4(_m1$2);
  12703. return this;
  12704. },
  12705. translate: function translate(x, y, z) {
  12706. // translate geometry
  12707. _m1$2.makeTranslation(x, y, z);
  12708. this.applyMatrix4(_m1$2);
  12709. return this;
  12710. },
  12711. scale: function scale(x, y, z) {
  12712. // scale geometry
  12713. _m1$2.makeScale(x, y, z);
  12714. this.applyMatrix4(_m1$2);
  12715. return this;
  12716. },
  12717. lookAt: function lookAt(vector) {
  12718. _obj.lookAt(vector);
  12719. _obj.updateMatrix();
  12720. this.applyMatrix4(_obj.matrix);
  12721. return this;
  12722. },
  12723. center: function center() {
  12724. this.computeBoundingBox();
  12725. this.boundingBox.getCenter(_offset).negate();
  12726. this.translate(_offset.x, _offset.y, _offset.z);
  12727. return this;
  12728. },
  12729. setFromPoints: function setFromPoints(points) {
  12730. var position = [];
  12731. for (var i = 0, l = points.length; i < l; i++) {
  12732. var point = points[i];
  12733. position.push(point.x, point.y, point.z || 0);
  12734. }
  12735. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  12736. return this;
  12737. },
  12738. computeBoundingBox: function computeBoundingBox() {
  12739. if (this.boundingBox === null) {
  12740. this.boundingBox = new Box3();
  12741. }
  12742. var position = this.attributes.position;
  12743. var morphAttributesPosition = this.morphAttributes.position;
  12744. if (position && position.isGLBufferAttribute) {
  12745. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  12746. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  12747. return;
  12748. }
  12749. if (position !== undefined) {
  12750. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  12751. if (morphAttributesPosition) {
  12752. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12753. var morphAttribute = morphAttributesPosition[i];
  12754. _box$2.setFromBufferAttribute(morphAttribute);
  12755. if (this.morphTargetsRelative) {
  12756. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  12757. this.boundingBox.expandByPoint(_vector$4);
  12758. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  12759. this.boundingBox.expandByPoint(_vector$4);
  12760. } else {
  12761. this.boundingBox.expandByPoint(_box$2.min);
  12762. this.boundingBox.expandByPoint(_box$2.max);
  12763. }
  12764. }
  12765. }
  12766. } else {
  12767. this.boundingBox.makeEmpty();
  12768. }
  12769. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  12770. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  12771. }
  12772. },
  12773. computeBoundingSphere: function computeBoundingSphere() {
  12774. if (this.boundingSphere === null) {
  12775. this.boundingSphere = new Sphere();
  12776. }
  12777. var position = this.attributes.position;
  12778. var morphAttributesPosition = this.morphAttributes.position;
  12779. if (position && position.isGLBufferAttribute) {
  12780. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  12781. this.boundingSphere.set(new Vector3(), Infinity);
  12782. return;
  12783. }
  12784. if (position) {
  12785. // first, find the center of the bounding sphere
  12786. var center = this.boundingSphere.center;
  12787. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  12788. if (morphAttributesPosition) {
  12789. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12790. var morphAttribute = morphAttributesPosition[i];
  12791. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  12792. if (this.morphTargetsRelative) {
  12793. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  12794. _box$2.expandByPoint(_vector$4);
  12795. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  12796. _box$2.expandByPoint(_vector$4);
  12797. } else {
  12798. _box$2.expandByPoint(_boxMorphTargets.min);
  12799. _box$2.expandByPoint(_boxMorphTargets.max);
  12800. }
  12801. }
  12802. }
  12803. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  12804. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12805. var maxRadiusSq = 0;
  12806. for (var _i = 0, _il = position.count; _i < _il; _i++) {
  12807. _vector$4.fromBufferAttribute(position, _i);
  12808. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12809. } // process morph attributes if present
  12810. if (morphAttributesPosition) {
  12811. for (var _i2 = 0, _il2 = morphAttributesPosition.length; _i2 < _il2; _i2++) {
  12812. var _morphAttribute = morphAttributesPosition[_i2];
  12813. var morphTargetsRelative = this.morphTargetsRelative;
  12814. for (var j = 0, jl = _morphAttribute.count; j < jl; j++) {
  12815. _vector$4.fromBufferAttribute(_morphAttribute, j);
  12816. if (morphTargetsRelative) {
  12817. _offset.fromBufferAttribute(position, j);
  12818. _vector$4.add(_offset);
  12819. }
  12820. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12821. }
  12822. }
  12823. }
  12824. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  12825. if (isNaN(this.boundingSphere.radius)) {
  12826. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  12827. }
  12828. }
  12829. },
  12830. computeFaceNormals: function computeFaceNormals() {// backwards compatibility
  12831. },
  12832. computeTangents: function computeTangents() {
  12833. var index = this.index;
  12834. var attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  12835. // (per vertex tangents)
  12836. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  12837. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  12838. return;
  12839. }
  12840. var indices = index.array;
  12841. var positions = attributes.position.array;
  12842. var normals = attributes.normal.array;
  12843. var uvs = attributes.uv.array;
  12844. var nVertices = positions.length / 3;
  12845. if (attributes.tangent === undefined) {
  12846. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  12847. }
  12848. var tangents = attributes.tangent.array;
  12849. var tan1 = [],
  12850. tan2 = [];
  12851. for (var i = 0; i < nVertices; i++) {
  12852. tan1[i] = new Vector3();
  12853. tan2[i] = new Vector3();
  12854. }
  12855. var vA = new Vector3(),
  12856. vB = new Vector3(),
  12857. vC = new Vector3(),
  12858. uvA = new Vector2(),
  12859. uvB = new Vector2(),
  12860. uvC = new Vector2(),
  12861. sdir = new Vector3(),
  12862. tdir = new Vector3();
  12863. function handleTriangle(a, b, c) {
  12864. vA.fromArray(positions, a * 3);
  12865. vB.fromArray(positions, b * 3);
  12866. vC.fromArray(positions, c * 3);
  12867. uvA.fromArray(uvs, a * 2);
  12868. uvB.fromArray(uvs, b * 2);
  12869. uvC.fromArray(uvs, c * 2);
  12870. vB.sub(vA);
  12871. vC.sub(vA);
  12872. uvB.sub(uvA);
  12873. uvC.sub(uvA);
  12874. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  12875. if (!isFinite(r)) return;
  12876. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  12877. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  12878. tan1[a].add(sdir);
  12879. tan1[b].add(sdir);
  12880. tan1[c].add(sdir);
  12881. tan2[a].add(tdir);
  12882. tan2[b].add(tdir);
  12883. tan2[c].add(tdir);
  12884. }
  12885. var groups = this.groups;
  12886. if (groups.length === 0) {
  12887. groups = [{
  12888. start: 0,
  12889. count: indices.length
  12890. }];
  12891. }
  12892. for (var _i3 = 0, il = groups.length; _i3 < il; ++_i3) {
  12893. var group = groups[_i3];
  12894. var start = group.start;
  12895. var count = group.count;
  12896. for (var j = start, jl = start + count; j < jl; j += 3) {
  12897. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  12898. }
  12899. }
  12900. var tmp = new Vector3(),
  12901. tmp2 = new Vector3();
  12902. var n = new Vector3(),
  12903. n2 = new Vector3();
  12904. function handleVertex(v) {
  12905. n.fromArray(normals, v * 3);
  12906. n2.copy(n);
  12907. var t = tan1[v]; // Gram-Schmidt orthogonalize
  12908. tmp.copy(t);
  12909. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  12910. tmp2.crossVectors(n2, t);
  12911. var test = tmp2.dot(tan2[v]);
  12912. var w = test < 0.0 ? -1.0 : 1.0;
  12913. tangents[v * 4] = tmp.x;
  12914. tangents[v * 4 + 1] = tmp.y;
  12915. tangents[v * 4 + 2] = tmp.z;
  12916. tangents[v * 4 + 3] = w;
  12917. }
  12918. for (var _i4 = 0, _il3 = groups.length; _i4 < _il3; ++_i4) {
  12919. var _group = groups[_i4];
  12920. var _start = _group.start;
  12921. var _count = _group.count;
  12922. for (var _j = _start, _jl = _start + _count; _j < _jl; _j += 3) {
  12923. handleVertex(indices[_j + 0]);
  12924. handleVertex(indices[_j + 1]);
  12925. handleVertex(indices[_j + 2]);
  12926. }
  12927. }
  12928. },
  12929. computeVertexNormals: function computeVertexNormals() {
  12930. var index = this.index;
  12931. var positionAttribute = this.getAttribute('position');
  12932. if (positionAttribute !== undefined) {
  12933. var normalAttribute = this.getAttribute('normal');
  12934. if (normalAttribute === undefined) {
  12935. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  12936. this.setAttribute('normal', normalAttribute);
  12937. } else {
  12938. // reset existing normals to zero
  12939. for (var i = 0, il = normalAttribute.count; i < il; i++) {
  12940. normalAttribute.setXYZ(i, 0, 0, 0);
  12941. }
  12942. }
  12943. var pA = new Vector3(),
  12944. pB = new Vector3(),
  12945. pC = new Vector3();
  12946. var nA = new Vector3(),
  12947. nB = new Vector3(),
  12948. nC = new Vector3();
  12949. var cb = new Vector3(),
  12950. ab = new Vector3(); // indexed elements
  12951. if (index) {
  12952. for (var _i5 = 0, _il4 = index.count; _i5 < _il4; _i5 += 3) {
  12953. var vA = index.getX(_i5 + 0);
  12954. var vB = index.getX(_i5 + 1);
  12955. var vC = index.getX(_i5 + 2);
  12956. pA.fromBufferAttribute(positionAttribute, vA);
  12957. pB.fromBufferAttribute(positionAttribute, vB);
  12958. pC.fromBufferAttribute(positionAttribute, vC);
  12959. cb.subVectors(pC, pB);
  12960. ab.subVectors(pA, pB);
  12961. cb.cross(ab);
  12962. nA.fromBufferAttribute(normalAttribute, vA);
  12963. nB.fromBufferAttribute(normalAttribute, vB);
  12964. nC.fromBufferAttribute(normalAttribute, vC);
  12965. nA.add(cb);
  12966. nB.add(cb);
  12967. nC.add(cb);
  12968. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  12969. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  12970. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  12971. }
  12972. } else {
  12973. // non-indexed elements (unconnected triangle soup)
  12974. for (var _i6 = 0, _il5 = positionAttribute.count; _i6 < _il5; _i6 += 3) {
  12975. pA.fromBufferAttribute(positionAttribute, _i6 + 0);
  12976. pB.fromBufferAttribute(positionAttribute, _i6 + 1);
  12977. pC.fromBufferAttribute(positionAttribute, _i6 + 2);
  12978. cb.subVectors(pC, pB);
  12979. ab.subVectors(pA, pB);
  12980. cb.cross(ab);
  12981. normalAttribute.setXYZ(_i6 + 0, cb.x, cb.y, cb.z);
  12982. normalAttribute.setXYZ(_i6 + 1, cb.x, cb.y, cb.z);
  12983. normalAttribute.setXYZ(_i6 + 2, cb.x, cb.y, cb.z);
  12984. }
  12985. }
  12986. this.normalizeNormals();
  12987. normalAttribute.needsUpdate = true;
  12988. }
  12989. },
  12990. merge: function merge(geometry, offset) {
  12991. if (!(geometry && geometry.isBufferGeometry)) {
  12992. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  12993. return;
  12994. }
  12995. if (offset === undefined) {
  12996. offset = 0;
  12997. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  12998. }
  12999. var attributes = this.attributes;
  13000. for (var key in attributes) {
  13001. if (geometry.attributes[key] === undefined) continue;
  13002. var attribute1 = attributes[key];
  13003. var attributeArray1 = attribute1.array;
  13004. var attribute2 = geometry.attributes[key];
  13005. var attributeArray2 = attribute2.array;
  13006. var attributeOffset = attribute2.itemSize * offset;
  13007. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  13008. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  13009. attributeArray1[j] = attributeArray2[i];
  13010. }
  13011. }
  13012. return this;
  13013. },
  13014. normalizeNormals: function normalizeNormals() {
  13015. var normals = this.attributes.normal;
  13016. for (var i = 0, il = normals.count; i < il; i++) {
  13017. _vector$4.fromBufferAttribute(normals, i);
  13018. _vector$4.normalize();
  13019. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  13020. }
  13021. },
  13022. toNonIndexed: function toNonIndexed() {
  13023. function convertBufferAttribute(attribute, indices) {
  13024. var array = attribute.array;
  13025. var itemSize = attribute.itemSize;
  13026. var normalized = attribute.normalized;
  13027. var array2 = new array.constructor(indices.length * itemSize);
  13028. var index = 0,
  13029. index2 = 0;
  13030. for (var i = 0, l = indices.length; i < l; i++) {
  13031. index = indices[i] * itemSize;
  13032. for (var j = 0; j < itemSize; j++) {
  13033. array2[index2++] = array[index++];
  13034. }
  13035. }
  13036. return new BufferAttribute(array2, itemSize, normalized);
  13037. } //
  13038. if (this.index === null) {
  13039. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  13040. return this;
  13041. }
  13042. var geometry2 = new BufferGeometry();
  13043. var indices = this.index.array;
  13044. var attributes = this.attributes; // attributes
  13045. for (var name in attributes) {
  13046. var attribute = attributes[name];
  13047. var newAttribute = convertBufferAttribute(attribute, indices);
  13048. geometry2.setAttribute(name, newAttribute);
  13049. } // morph attributes
  13050. var morphAttributes = this.morphAttributes;
  13051. for (var _name in morphAttributes) {
  13052. var morphArray = [];
  13053. var morphAttribute = morphAttributes[_name]; // morphAttribute: array of Float32BufferAttributes
  13054. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  13055. var _attribute = morphAttribute[i];
  13056. var _newAttribute = convertBufferAttribute(_attribute, indices);
  13057. morphArray.push(_newAttribute);
  13058. }
  13059. geometry2.morphAttributes[_name] = morphArray;
  13060. }
  13061. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  13062. var groups = this.groups;
  13063. for (var _i7 = 0, l = groups.length; _i7 < l; _i7++) {
  13064. var group = groups[_i7];
  13065. geometry2.addGroup(group.start, group.count, group.materialIndex);
  13066. }
  13067. return geometry2;
  13068. },
  13069. toJSON: function toJSON() {
  13070. var data = {
  13071. metadata: {
  13072. version: 4.5,
  13073. type: 'BufferGeometry',
  13074. generator: 'BufferGeometry.toJSON'
  13075. }
  13076. }; // standard BufferGeometry serialization
  13077. data.uuid = this.uuid;
  13078. data.type = this.type;
  13079. if (this.name !== '') data.name = this.name;
  13080. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  13081. if (this.parameters !== undefined) {
  13082. var parameters = this.parameters;
  13083. for (var key in parameters) {
  13084. if (parameters[key] !== undefined) data[key] = parameters[key];
  13085. }
  13086. return data;
  13087. }
  13088. data.data = {
  13089. attributes: {}
  13090. };
  13091. var index = this.index;
  13092. if (index !== null) {
  13093. data.data.index = {
  13094. type: index.array.constructor.name,
  13095. array: Array.prototype.slice.call(index.array)
  13096. };
  13097. }
  13098. var attributes = this.attributes;
  13099. for (var _key in attributes) {
  13100. var attribute = attributes[_key];
  13101. var attributeData = attribute.toJSON(data.data);
  13102. if (attribute.name !== '') attributeData.name = attribute.name;
  13103. data.data.attributes[_key] = attributeData;
  13104. }
  13105. var morphAttributes = {};
  13106. var hasMorphAttributes = false;
  13107. for (var _key2 in this.morphAttributes) {
  13108. var attributeArray = this.morphAttributes[_key2];
  13109. var array = [];
  13110. for (var i = 0, il = attributeArray.length; i < il; i++) {
  13111. var _attribute2 = attributeArray[i];
  13112. var _attributeData = _attribute2.toJSON(data.data);
  13113. if (_attribute2.name !== '') _attributeData.name = _attribute2.name;
  13114. array.push(_attributeData);
  13115. }
  13116. if (array.length > 0) {
  13117. morphAttributes[_key2] = array;
  13118. hasMorphAttributes = true;
  13119. }
  13120. }
  13121. if (hasMorphAttributes) {
  13122. data.data.morphAttributes = morphAttributes;
  13123. data.data.morphTargetsRelative = this.morphTargetsRelative;
  13124. }
  13125. var groups = this.groups;
  13126. if (groups.length > 0) {
  13127. data.data.groups = JSON.parse(JSON.stringify(groups));
  13128. }
  13129. var boundingSphere = this.boundingSphere;
  13130. if (boundingSphere !== null) {
  13131. data.data.boundingSphere = {
  13132. center: boundingSphere.center.toArray(),
  13133. radius: boundingSphere.radius
  13134. };
  13135. }
  13136. return data;
  13137. },
  13138. clone: function clone() {
  13139. /*
  13140. // Handle primitives
  13141. const parameters = this.parameters;
  13142. if ( parameters !== undefined ) {
  13143. const values = [];
  13144. for ( const key in parameters ) {
  13145. values.push( parameters[ key ] );
  13146. }
  13147. const geometry = Object.create( this.constructor.prototype );
  13148. this.constructor.apply( geometry, values );
  13149. return geometry;
  13150. }
  13151. return new this.constructor().copy( this );
  13152. */
  13153. return new BufferGeometry().copy(this);
  13154. },
  13155. copy: function copy(source) {
  13156. // reset
  13157. this.index = null;
  13158. this.attributes = {};
  13159. this.morphAttributes = {};
  13160. this.groups = [];
  13161. this.boundingBox = null;
  13162. this.boundingSphere = null; // used for storing cloned, shared data
  13163. var data = {}; // name
  13164. this.name = source.name; // index
  13165. var index = source.index;
  13166. if (index !== null) {
  13167. this.setIndex(index.clone(data));
  13168. } // attributes
  13169. var attributes = source.attributes;
  13170. for (var name in attributes) {
  13171. var attribute = attributes[name];
  13172. this.setAttribute(name, attribute.clone(data));
  13173. } // morph attributes
  13174. var morphAttributes = source.morphAttributes;
  13175. for (var _name2 in morphAttributes) {
  13176. var array = [];
  13177. var morphAttribute = morphAttributes[_name2]; // morphAttribute: array of Float32BufferAttributes
  13178. for (var i = 0, l = morphAttribute.length; i < l; i++) {
  13179. array.push(morphAttribute[i].clone(data));
  13180. }
  13181. this.morphAttributes[_name2] = array;
  13182. }
  13183. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  13184. var groups = source.groups;
  13185. for (var _i8 = 0, _l = groups.length; _i8 < _l; _i8++) {
  13186. var group = groups[_i8];
  13187. this.addGroup(group.start, group.count, group.materialIndex);
  13188. } // bounding box
  13189. var boundingBox = source.boundingBox;
  13190. if (boundingBox !== null) {
  13191. this.boundingBox = boundingBox.clone();
  13192. } // bounding sphere
  13193. var boundingSphere = source.boundingSphere;
  13194. if (boundingSphere !== null) {
  13195. this.boundingSphere = boundingSphere.clone();
  13196. } // draw range
  13197. this.drawRange.start = source.drawRange.start;
  13198. this.drawRange.count = source.drawRange.count; // user data
  13199. this.userData = source.userData;
  13200. return this;
  13201. },
  13202. dispose: function dispose() {
  13203. this.dispatchEvent({
  13204. type: 'dispose'
  13205. });
  13206. }
  13207. });
  13208. var _inverseMatrix = new Matrix4();
  13209. var _ray = new Ray();
  13210. var _sphere = new Sphere();
  13211. var _vA = new Vector3();
  13212. var _vB = new Vector3();
  13213. var _vC = new Vector3();
  13214. var _tempA = new Vector3();
  13215. var _tempB = new Vector3();
  13216. var _tempC = new Vector3();
  13217. var _morphA = new Vector3();
  13218. var _morphB = new Vector3();
  13219. var _morphC = new Vector3();
  13220. var _uvA = new Vector2();
  13221. var _uvB = new Vector2();
  13222. var _uvC = new Vector2();
  13223. var _intersectionPoint = new Vector3();
  13224. var _intersectionPointWorld = new Vector3();
  13225. function Mesh(geometry, material) {
  13226. if (geometry === void 0) {
  13227. geometry = new BufferGeometry();
  13228. }
  13229. if (material === void 0) {
  13230. material = new MeshBasicMaterial();
  13231. }
  13232. Object3D.call(this);
  13233. this.type = 'Mesh';
  13234. this.geometry = geometry;
  13235. this.material = material;
  13236. this.updateMorphTargets();
  13237. }
  13238. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  13239. constructor: Mesh,
  13240. isMesh: true,
  13241. copy: function copy(source) {
  13242. Object3D.prototype.copy.call(this, source);
  13243. if (source.morphTargetInfluences !== undefined) {
  13244. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  13245. }
  13246. if (source.morphTargetDictionary !== undefined) {
  13247. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  13248. }
  13249. this.material = source.material;
  13250. this.geometry = source.geometry;
  13251. return this;
  13252. },
  13253. updateMorphTargets: function updateMorphTargets() {
  13254. var geometry = this.geometry;
  13255. if (geometry.isBufferGeometry) {
  13256. var morphAttributes = geometry.morphAttributes;
  13257. var keys = Object.keys(morphAttributes);
  13258. if (keys.length > 0) {
  13259. var morphAttribute = morphAttributes[keys[0]];
  13260. if (morphAttribute !== undefined) {
  13261. this.morphTargetInfluences = [];
  13262. this.morphTargetDictionary = {};
  13263. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  13264. var name = morphAttribute[m].name || String(m);
  13265. this.morphTargetInfluences.push(0);
  13266. this.morphTargetDictionary[name] = m;
  13267. }
  13268. }
  13269. }
  13270. } else {
  13271. var morphTargets = geometry.morphTargets;
  13272. if (morphTargets !== undefined && morphTargets.length > 0) {
  13273. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  13274. }
  13275. }
  13276. },
  13277. raycast: function raycast(raycaster, intersects) {
  13278. var geometry = this.geometry;
  13279. var material = this.material;
  13280. var matrixWorld = this.matrixWorld;
  13281. if (material === undefined) return; // Checking boundingSphere distance to ray
  13282. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  13283. _sphere.copy(geometry.boundingSphere);
  13284. _sphere.applyMatrix4(matrixWorld);
  13285. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  13286. _inverseMatrix.copy(matrixWorld).invert();
  13287. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  13288. if (geometry.boundingBox !== null) {
  13289. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  13290. }
  13291. var intersection;
  13292. if (geometry.isBufferGeometry) {
  13293. var index = geometry.index;
  13294. var position = geometry.attributes.position;
  13295. var morphPosition = geometry.morphAttributes.position;
  13296. var morphTargetsRelative = geometry.morphTargetsRelative;
  13297. var uv = geometry.attributes.uv;
  13298. var uv2 = geometry.attributes.uv2;
  13299. var groups = geometry.groups;
  13300. var drawRange = geometry.drawRange;
  13301. if (index !== null) {
  13302. // indexed buffer geometry
  13303. if (Array.isArray(material)) {
  13304. for (var i = 0, il = groups.length; i < il; i++) {
  13305. var group = groups[i];
  13306. var groupMaterial = material[group.materialIndex];
  13307. var start = Math.max(group.start, drawRange.start);
  13308. var end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  13309. for (var j = start, jl = end; j < jl; j += 3) {
  13310. var a = index.getX(j);
  13311. var b = index.getX(j + 1);
  13312. var c = index.getX(j + 2);
  13313. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  13314. if (intersection) {
  13315. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  13316. intersection.face.materialIndex = group.materialIndex;
  13317. intersects.push(intersection);
  13318. }
  13319. }
  13320. }
  13321. } else {
  13322. var _start = Math.max(0, drawRange.start);
  13323. var _end = Math.min(index.count, drawRange.start + drawRange.count);
  13324. for (var _i = _start, _il = _end; _i < _il; _i += 3) {
  13325. var _a = index.getX(_i);
  13326. var _b = index.getX(_i + 1);
  13327. var _c = index.getX(_i + 2);
  13328. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a, _b, _c);
  13329. if (intersection) {
  13330. intersection.faceIndex = Math.floor(_i / 3); // triangle number in indexed buffer semantics
  13331. intersects.push(intersection);
  13332. }
  13333. }
  13334. }
  13335. } else if (position !== undefined) {
  13336. // non-indexed buffer geometry
  13337. if (Array.isArray(material)) {
  13338. for (var _i2 = 0, _il2 = groups.length; _i2 < _il2; _i2++) {
  13339. var _group = groups[_i2];
  13340. var _groupMaterial = material[_group.materialIndex];
  13341. var _start2 = Math.max(_group.start, drawRange.start);
  13342. var _end2 = Math.min(_group.start + _group.count, drawRange.start + drawRange.count);
  13343. for (var _j = _start2, _jl = _end2; _j < _jl; _j += 3) {
  13344. var _a2 = _j;
  13345. var _b2 = _j + 1;
  13346. var _c2 = _j + 2;
  13347. intersection = checkBufferGeometryIntersection(this, _groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a2, _b2, _c2);
  13348. if (intersection) {
  13349. intersection.faceIndex = Math.floor(_j / 3); // triangle number in non-indexed buffer semantics
  13350. intersection.face.materialIndex = _group.materialIndex;
  13351. intersects.push(intersection);
  13352. }
  13353. }
  13354. }
  13355. } else {
  13356. var _start3 = Math.max(0, drawRange.start);
  13357. var _end3 = Math.min(position.count, drawRange.start + drawRange.count);
  13358. for (var _i3 = _start3, _il3 = _end3; _i3 < _il3; _i3 += 3) {
  13359. var _a3 = _i3;
  13360. var _b3 = _i3 + 1;
  13361. var _c3 = _i3 + 2;
  13362. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a3, _b3, _c3);
  13363. if (intersection) {
  13364. intersection.faceIndex = Math.floor(_i3 / 3); // triangle number in non-indexed buffer semantics
  13365. intersects.push(intersection);
  13366. }
  13367. }
  13368. }
  13369. }
  13370. } else if (geometry.isGeometry) {
  13371. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  13372. }
  13373. }
  13374. });
  13375. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  13376. var intersect;
  13377. if (material.side === BackSide) {
  13378. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  13379. } else {
  13380. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  13381. }
  13382. if (intersect === null) return null;
  13383. _intersectionPointWorld.copy(point);
  13384. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  13385. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  13386. if (distance < raycaster.near || distance > raycaster.far) return null;
  13387. return {
  13388. distance: distance,
  13389. point: _intersectionPointWorld.clone(),
  13390. object: object
  13391. };
  13392. }
  13393. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  13394. _vA.fromBufferAttribute(position, a);
  13395. _vB.fromBufferAttribute(position, b);
  13396. _vC.fromBufferAttribute(position, c);
  13397. var morphInfluences = object.morphTargetInfluences;
  13398. if (material.morphTargets && morphPosition && morphInfluences) {
  13399. _morphA.set(0, 0, 0);
  13400. _morphB.set(0, 0, 0);
  13401. _morphC.set(0, 0, 0);
  13402. for (var i = 0, il = morphPosition.length; i < il; i++) {
  13403. var influence = morphInfluences[i];
  13404. var morphAttribute = morphPosition[i];
  13405. if (influence === 0) continue;
  13406. _tempA.fromBufferAttribute(morphAttribute, a);
  13407. _tempB.fromBufferAttribute(morphAttribute, b);
  13408. _tempC.fromBufferAttribute(morphAttribute, c);
  13409. if (morphTargetsRelative) {
  13410. _morphA.addScaledVector(_tempA, influence);
  13411. _morphB.addScaledVector(_tempB, influence);
  13412. _morphC.addScaledVector(_tempC, influence);
  13413. } else {
  13414. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  13415. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  13416. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  13417. }
  13418. }
  13419. _vA.add(_morphA);
  13420. _vB.add(_morphB);
  13421. _vC.add(_morphC);
  13422. }
  13423. if (object.isSkinnedMesh) {
  13424. object.boneTransform(a, _vA);
  13425. object.boneTransform(b, _vB);
  13426. object.boneTransform(c, _vC);
  13427. }
  13428. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  13429. if (intersection) {
  13430. if (uv) {
  13431. _uvA.fromBufferAttribute(uv, a);
  13432. _uvB.fromBufferAttribute(uv, b);
  13433. _uvC.fromBufferAttribute(uv, c);
  13434. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  13435. }
  13436. if (uv2) {
  13437. _uvA.fromBufferAttribute(uv2, a);
  13438. _uvB.fromBufferAttribute(uv2, b);
  13439. _uvC.fromBufferAttribute(uv2, c);
  13440. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  13441. }
  13442. var face = new Face3(a, b, c);
  13443. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  13444. intersection.face = face;
  13445. }
  13446. return intersection;
  13447. }
  13448. var BoxGeometry = /*#__PURE__*/function (_BufferGeometry) {
  13449. _inheritsLoose(BoxGeometry, _BufferGeometry);
  13450. function BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
  13451. var _this;
  13452. if (width === void 0) {
  13453. width = 1;
  13454. }
  13455. if (height === void 0) {
  13456. height = 1;
  13457. }
  13458. if (depth === void 0) {
  13459. depth = 1;
  13460. }
  13461. if (widthSegments === void 0) {
  13462. widthSegments = 1;
  13463. }
  13464. if (heightSegments === void 0) {
  13465. heightSegments = 1;
  13466. }
  13467. if (depthSegments === void 0) {
  13468. depthSegments = 1;
  13469. }
  13470. _this = _BufferGeometry.call(this) || this;
  13471. _this.type = 'BoxGeometry';
  13472. _this.parameters = {
  13473. width: width,
  13474. height: height,
  13475. depth: depth,
  13476. widthSegments: widthSegments,
  13477. heightSegments: heightSegments,
  13478. depthSegments: depthSegments
  13479. };
  13480. var scope = _assertThisInitialized(_this); // segments
  13481. widthSegments = Math.floor(widthSegments);
  13482. heightSegments = Math.floor(heightSegments);
  13483. depthSegments = Math.floor(depthSegments); // buffers
  13484. var indices = [];
  13485. var vertices = [];
  13486. var normals = [];
  13487. var uvs = []; // helper variables
  13488. var numberOfVertices = 0;
  13489. var groupStart = 0; // build each side of the box geometry
  13490. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  13491. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  13492. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  13493. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  13494. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  13495. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  13496. // build geometry
  13497. _this.setIndex(indices);
  13498. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  13499. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  13500. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  13501. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  13502. var segmentWidth = width / gridX;
  13503. var segmentHeight = height / gridY;
  13504. var widthHalf = width / 2;
  13505. var heightHalf = height / 2;
  13506. var depthHalf = depth / 2;
  13507. var gridX1 = gridX + 1;
  13508. var gridY1 = gridY + 1;
  13509. var vertexCounter = 0;
  13510. var groupCount = 0;
  13511. var vector = new Vector3(); // generate vertices, normals and uvs
  13512. for (var iy = 0; iy < gridY1; iy++) {
  13513. var y = iy * segmentHeight - heightHalf;
  13514. for (var ix = 0; ix < gridX1; ix++) {
  13515. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  13516. vector[u] = x * udir;
  13517. vector[v] = y * vdir;
  13518. vector[w] = depthHalf; // now apply vector to vertex buffer
  13519. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  13520. vector[u] = 0;
  13521. vector[v] = 0;
  13522. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  13523. normals.push(vector.x, vector.y, vector.z); // uvs
  13524. uvs.push(ix / gridX);
  13525. uvs.push(1 - iy / gridY); // counters
  13526. vertexCounter += 1;
  13527. }
  13528. } // indices
  13529. // 1. you need three indices to draw a single face
  13530. // 2. a single segment consists of two faces
  13531. // 3. so we need to generate six (2*3) indices per segment
  13532. for (var _iy = 0; _iy < gridY; _iy++) {
  13533. for (var _ix = 0; _ix < gridX; _ix++) {
  13534. var a = numberOfVertices + _ix + gridX1 * _iy;
  13535. var b = numberOfVertices + _ix + gridX1 * (_iy + 1);
  13536. var c = numberOfVertices + (_ix + 1) + gridX1 * (_iy + 1);
  13537. var d = numberOfVertices + (_ix + 1) + gridX1 * _iy; // faces
  13538. indices.push(a, b, d);
  13539. indices.push(b, c, d); // increase counter
  13540. groupCount += 6;
  13541. }
  13542. } // add a group to the geometry. this will ensure multi material support
  13543. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  13544. groupStart += groupCount; // update total number of vertices
  13545. numberOfVertices += vertexCounter;
  13546. }
  13547. return _this;
  13548. }
  13549. return BoxGeometry;
  13550. }(BufferGeometry);
  13551. /**
  13552. * Uniform Utilities
  13553. */
  13554. function cloneUniforms(src) {
  13555. var dst = {};
  13556. for (var u in src) {
  13557. dst[u] = {};
  13558. for (var p in src[u]) {
  13559. var property = src[u][p];
  13560. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  13561. dst[u][p] = property.clone();
  13562. } else if (Array.isArray(property)) {
  13563. dst[u][p] = property.slice();
  13564. } else {
  13565. dst[u][p] = property;
  13566. }
  13567. }
  13568. }
  13569. return dst;
  13570. }
  13571. function mergeUniforms(uniforms) {
  13572. var merged = {};
  13573. for (var u = 0; u < uniforms.length; u++) {
  13574. var tmp = cloneUniforms(uniforms[u]);
  13575. for (var p in tmp) {
  13576. merged[p] = tmp[p];
  13577. }
  13578. }
  13579. return merged;
  13580. } // Legacy
  13581. var UniformsUtils = {
  13582. clone: cloneUniforms,
  13583. merge: mergeUniforms
  13584. };
  13585. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  13586. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  13587. /**
  13588. * parameters = {
  13589. * defines: { "label" : "value" },
  13590. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13591. *
  13592. * fragmentShader: <string>,
  13593. * vertexShader: <string>,
  13594. *
  13595. * wireframe: <boolean>,
  13596. * wireframeLinewidth: <float>,
  13597. *
  13598. * lights: <bool>,
  13599. *
  13600. * skinning: <bool>,
  13601. * morphTargets: <bool>,
  13602. * morphNormals: <bool>
  13603. * }
  13604. */
  13605. function ShaderMaterial(parameters) {
  13606. Material.call(this);
  13607. this.type = 'ShaderMaterial';
  13608. this.defines = {};
  13609. this.uniforms = {};
  13610. this.vertexShader = default_vertex;
  13611. this.fragmentShader = default_fragment;
  13612. this.linewidth = 1;
  13613. this.wireframe = false;
  13614. this.wireframeLinewidth = 1;
  13615. this.fog = false; // set to use scene fog
  13616. this.lights = false; // set to use scene lights
  13617. this.clipping = false; // set to use user-defined clipping planes
  13618. this.skinning = false; // set to use skinning attribute streams
  13619. this.morphTargets = false; // set to use morph targets
  13620. this.morphNormals = false; // set to use morph normals
  13621. this.extensions = {
  13622. derivatives: false,
  13623. // set to use derivatives
  13624. fragDepth: false,
  13625. // set to use fragment depth values
  13626. drawBuffers: false,
  13627. // set to use draw buffers
  13628. shaderTextureLOD: false // set to use shader texture LOD
  13629. }; // When rendered geometry doesn't include these attributes but the material does,
  13630. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13631. this.defaultAttributeValues = {
  13632. 'color': [1, 1, 1],
  13633. 'uv': [0, 0],
  13634. 'uv2': [0, 0]
  13635. };
  13636. this.index0AttributeName = undefined;
  13637. this.uniformsNeedUpdate = false;
  13638. this.glslVersion = null;
  13639. if (parameters !== undefined) {
  13640. if (parameters.attributes !== undefined) {
  13641. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  13642. }
  13643. this.setValues(parameters);
  13644. }
  13645. }
  13646. ShaderMaterial.prototype = Object.create(Material.prototype);
  13647. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13648. ShaderMaterial.prototype.isShaderMaterial = true;
  13649. ShaderMaterial.prototype.copy = function (source) {
  13650. Material.prototype.copy.call(this, source);
  13651. this.fragmentShader = source.fragmentShader;
  13652. this.vertexShader = source.vertexShader;
  13653. this.uniforms = cloneUniforms(source.uniforms);
  13654. this.defines = Object.assign({}, source.defines);
  13655. this.wireframe = source.wireframe;
  13656. this.wireframeLinewidth = source.wireframeLinewidth;
  13657. this.lights = source.lights;
  13658. this.clipping = source.clipping;
  13659. this.skinning = source.skinning;
  13660. this.morphTargets = source.morphTargets;
  13661. this.morphNormals = source.morphNormals;
  13662. this.extensions = Object.assign({}, source.extensions);
  13663. this.glslVersion = source.glslVersion;
  13664. return this;
  13665. };
  13666. ShaderMaterial.prototype.toJSON = function (meta) {
  13667. var data = Material.prototype.toJSON.call(this, meta);
  13668. data.glslVersion = this.glslVersion;
  13669. data.uniforms = {};
  13670. for (var name in this.uniforms) {
  13671. var uniform = this.uniforms[name];
  13672. var value = uniform.value;
  13673. if (value && value.isTexture) {
  13674. data.uniforms[name] = {
  13675. type: 't',
  13676. value: value.toJSON(meta).uuid
  13677. };
  13678. } else if (value && value.isColor) {
  13679. data.uniforms[name] = {
  13680. type: 'c',
  13681. value: value.getHex()
  13682. };
  13683. } else if (value && value.isVector2) {
  13684. data.uniforms[name] = {
  13685. type: 'v2',
  13686. value: value.toArray()
  13687. };
  13688. } else if (value && value.isVector3) {
  13689. data.uniforms[name] = {
  13690. type: 'v3',
  13691. value: value.toArray()
  13692. };
  13693. } else if (value && value.isVector4) {
  13694. data.uniforms[name] = {
  13695. type: 'v4',
  13696. value: value.toArray()
  13697. };
  13698. } else if (value && value.isMatrix3) {
  13699. data.uniforms[name] = {
  13700. type: 'm3',
  13701. value: value.toArray()
  13702. };
  13703. } else if (value && value.isMatrix4) {
  13704. data.uniforms[name] = {
  13705. type: 'm4',
  13706. value: value.toArray()
  13707. };
  13708. } else {
  13709. data.uniforms[name] = {
  13710. value: value
  13711. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13712. }
  13713. }
  13714. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  13715. data.vertexShader = this.vertexShader;
  13716. data.fragmentShader = this.fragmentShader;
  13717. var extensions = {};
  13718. for (var key in this.extensions) {
  13719. if (this.extensions[key] === true) extensions[key] = true;
  13720. }
  13721. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  13722. return data;
  13723. };
  13724. function Camera() {
  13725. Object3D.call(this);
  13726. this.type = 'Camera';
  13727. this.matrixWorldInverse = new Matrix4();
  13728. this.projectionMatrix = new Matrix4();
  13729. this.projectionMatrixInverse = new Matrix4();
  13730. }
  13731. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  13732. constructor: Camera,
  13733. isCamera: true,
  13734. copy: function copy(source, recursive) {
  13735. Object3D.prototype.copy.call(this, source, recursive);
  13736. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  13737. this.projectionMatrix.copy(source.projectionMatrix);
  13738. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  13739. return this;
  13740. },
  13741. getWorldDirection: function getWorldDirection(target) {
  13742. if (target === undefined) {
  13743. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  13744. target = new Vector3();
  13745. }
  13746. this.updateWorldMatrix(true, false);
  13747. var e = this.matrixWorld.elements;
  13748. return target.set(-e[8], -e[9], -e[10]).normalize();
  13749. },
  13750. updateMatrixWorld: function updateMatrixWorld(force) {
  13751. Object3D.prototype.updateMatrixWorld.call(this, force);
  13752. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13753. },
  13754. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  13755. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  13756. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13757. },
  13758. clone: function clone() {
  13759. return new this.constructor().copy(this);
  13760. }
  13761. });
  13762. function PerspectiveCamera(fov, aspect, near, far) {
  13763. if (fov === void 0) {
  13764. fov = 50;
  13765. }
  13766. if (aspect === void 0) {
  13767. aspect = 1;
  13768. }
  13769. if (near === void 0) {
  13770. near = 0.1;
  13771. }
  13772. if (far === void 0) {
  13773. far = 2000;
  13774. }
  13775. Camera.call(this);
  13776. this.type = 'PerspectiveCamera';
  13777. this.fov = fov;
  13778. this.zoom = 1;
  13779. this.near = near;
  13780. this.far = far;
  13781. this.focus = 10;
  13782. this.aspect = aspect;
  13783. this.view = null;
  13784. this.filmGauge = 35; // width of the film (default in millimeters)
  13785. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13786. this.updateProjectionMatrix();
  13787. }
  13788. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  13789. constructor: PerspectiveCamera,
  13790. isPerspectiveCamera: true,
  13791. copy: function copy(source, recursive) {
  13792. Camera.prototype.copy.call(this, source, recursive);
  13793. this.fov = source.fov;
  13794. this.zoom = source.zoom;
  13795. this.near = source.near;
  13796. this.far = source.far;
  13797. this.focus = source.focus;
  13798. this.aspect = source.aspect;
  13799. this.view = source.view === null ? null : Object.assign({}, source.view);
  13800. this.filmGauge = source.filmGauge;
  13801. this.filmOffset = source.filmOffset;
  13802. return this;
  13803. },
  13804. /**
  13805. * Sets the FOV by focal length in respect to the current .filmGauge.
  13806. *
  13807. * The default film gauge is 35, so that the focal length can be specified for
  13808. * a 35mm (full frame) camera.
  13809. *
  13810. * Values for focal length and film gauge must have the same unit.
  13811. */
  13812. setFocalLength: function setFocalLength(focalLength) {
  13813. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  13814. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13815. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  13816. this.updateProjectionMatrix();
  13817. },
  13818. /**
  13819. * Calculates the focal length from the current .fov and .filmGauge.
  13820. */
  13821. getFocalLength: function getFocalLength() {
  13822. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  13823. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13824. },
  13825. getEffectiveFOV: function getEffectiveFOV() {
  13826. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  13827. },
  13828. getFilmWidth: function getFilmWidth() {
  13829. // film not completely covered in portrait format (aspect < 1)
  13830. return this.filmGauge * Math.min(this.aspect, 1);
  13831. },
  13832. getFilmHeight: function getFilmHeight() {
  13833. // film not completely covered in landscape format (aspect > 1)
  13834. return this.filmGauge / Math.max(this.aspect, 1);
  13835. },
  13836. /**
  13837. * Sets an offset in a larger frustum. This is useful for multi-window or
  13838. * multi-monitor/multi-machine setups.
  13839. *
  13840. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13841. * the monitors are in grid like this
  13842. *
  13843. * +---+---+---+
  13844. * | A | B | C |
  13845. * +---+---+---+
  13846. * | D | E | F |
  13847. * +---+---+---+
  13848. *
  13849. * then for each monitor you would call it like this
  13850. *
  13851. * const w = 1920;
  13852. * const h = 1080;
  13853. * const fullWidth = w * 3;
  13854. * const fullHeight = h * 2;
  13855. *
  13856. * --A--
  13857. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13858. * --B--
  13859. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13860. * --C--
  13861. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13862. * --D--
  13863. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13864. * --E--
  13865. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13866. * --F--
  13867. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13868. *
  13869. * Note there is no reason monitors have to be the same size or in a grid.
  13870. */
  13871. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  13872. this.aspect = fullWidth / fullHeight;
  13873. if (this.view === null) {
  13874. this.view = {
  13875. enabled: true,
  13876. fullWidth: 1,
  13877. fullHeight: 1,
  13878. offsetX: 0,
  13879. offsetY: 0,
  13880. width: 1,
  13881. height: 1
  13882. };
  13883. }
  13884. this.view.enabled = true;
  13885. this.view.fullWidth = fullWidth;
  13886. this.view.fullHeight = fullHeight;
  13887. this.view.offsetX = x;
  13888. this.view.offsetY = y;
  13889. this.view.width = width;
  13890. this.view.height = height;
  13891. this.updateProjectionMatrix();
  13892. },
  13893. clearViewOffset: function clearViewOffset() {
  13894. if (this.view !== null) {
  13895. this.view.enabled = false;
  13896. }
  13897. this.updateProjectionMatrix();
  13898. },
  13899. updateProjectionMatrix: function updateProjectionMatrix() {
  13900. var near = this.near;
  13901. var top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  13902. var height = 2 * top;
  13903. var width = this.aspect * height;
  13904. var left = -0.5 * width;
  13905. var view = this.view;
  13906. if (this.view !== null && this.view.enabled) {
  13907. var fullWidth = view.fullWidth,
  13908. fullHeight = view.fullHeight;
  13909. left += view.offsetX * width / fullWidth;
  13910. top -= view.offsetY * height / fullHeight;
  13911. width *= view.width / fullWidth;
  13912. height *= view.height / fullHeight;
  13913. }
  13914. var skew = this.filmOffset;
  13915. if (skew !== 0) left += near * skew / this.getFilmWidth();
  13916. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  13917. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  13918. },
  13919. toJSON: function toJSON(meta) {
  13920. var data = Object3D.prototype.toJSON.call(this, meta);
  13921. data.object.fov = this.fov;
  13922. data.object.zoom = this.zoom;
  13923. data.object.near = this.near;
  13924. data.object.far = this.far;
  13925. data.object.focus = this.focus;
  13926. data.object.aspect = this.aspect;
  13927. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  13928. data.object.filmGauge = this.filmGauge;
  13929. data.object.filmOffset = this.filmOffset;
  13930. return data;
  13931. }
  13932. });
  13933. var fov = 90,
  13934. aspect = 1;
  13935. function CubeCamera(near, far, renderTarget) {
  13936. Object3D.call(this);
  13937. this.type = 'CubeCamera';
  13938. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  13939. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  13940. return;
  13941. }
  13942. this.renderTarget = renderTarget;
  13943. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  13944. cameraPX.layers = this.layers;
  13945. cameraPX.up.set(0, -1, 0);
  13946. cameraPX.lookAt(new Vector3(1, 0, 0));
  13947. this.add(cameraPX);
  13948. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  13949. cameraNX.layers = this.layers;
  13950. cameraNX.up.set(0, -1, 0);
  13951. cameraNX.lookAt(new Vector3(-1, 0, 0));
  13952. this.add(cameraNX);
  13953. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  13954. cameraPY.layers = this.layers;
  13955. cameraPY.up.set(0, 0, 1);
  13956. cameraPY.lookAt(new Vector3(0, 1, 0));
  13957. this.add(cameraPY);
  13958. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  13959. cameraNY.layers = this.layers;
  13960. cameraNY.up.set(0, 0, -1);
  13961. cameraNY.lookAt(new Vector3(0, -1, 0));
  13962. this.add(cameraNY);
  13963. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  13964. cameraPZ.layers = this.layers;
  13965. cameraPZ.up.set(0, -1, 0);
  13966. cameraPZ.lookAt(new Vector3(0, 0, 1));
  13967. this.add(cameraPZ);
  13968. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  13969. cameraNZ.layers = this.layers;
  13970. cameraNZ.up.set(0, -1, 0);
  13971. cameraNZ.lookAt(new Vector3(0, 0, -1));
  13972. this.add(cameraNZ);
  13973. this.update = function (renderer, scene) {
  13974. if (this.parent === null) this.updateMatrixWorld();
  13975. var currentXrEnabled = renderer.xr.enabled;
  13976. var currentRenderTarget = renderer.getRenderTarget();
  13977. renderer.xr.enabled = false;
  13978. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13979. renderTarget.texture.generateMipmaps = false;
  13980. renderer.setRenderTarget(renderTarget, 0);
  13981. renderer.render(scene, cameraPX);
  13982. renderer.setRenderTarget(renderTarget, 1);
  13983. renderer.render(scene, cameraNX);
  13984. renderer.setRenderTarget(renderTarget, 2);
  13985. renderer.render(scene, cameraPY);
  13986. renderer.setRenderTarget(renderTarget, 3);
  13987. renderer.render(scene, cameraNY);
  13988. renderer.setRenderTarget(renderTarget, 4);
  13989. renderer.render(scene, cameraPZ);
  13990. renderTarget.texture.generateMipmaps = generateMipmaps;
  13991. renderer.setRenderTarget(renderTarget, 5);
  13992. renderer.render(scene, cameraNZ);
  13993. renderer.setRenderTarget(currentRenderTarget);
  13994. renderer.xr.enabled = currentXrEnabled;
  13995. };
  13996. }
  13997. CubeCamera.prototype = Object.create(Object3D.prototype);
  13998. CubeCamera.prototype.constructor = CubeCamera;
  13999. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  14000. images = images !== undefined ? images : [];
  14001. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  14002. format = format !== undefined ? format : RGBFormat;
  14003. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  14004. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  14005. //
  14006. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  14007. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  14008. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  14009. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  14010. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  14011. // when using WebGLCubeRenderTarget.texture as a cube texture.
  14012. this._needsFlipEnvMap = true;
  14013. }
  14014. CubeTexture.prototype = Object.create(Texture.prototype);
  14015. CubeTexture.prototype.constructor = CubeTexture;
  14016. CubeTexture.prototype.isCubeTexture = true;
  14017. Object.defineProperty(CubeTexture.prototype, 'images', {
  14018. get: function get() {
  14019. return this.image;
  14020. },
  14021. set: function set(value) {
  14022. this.image = value;
  14023. }
  14024. });
  14025. var WebGLCubeRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
  14026. _inheritsLoose(WebGLCubeRenderTarget, _WebGLRenderTarget);
  14027. function WebGLCubeRenderTarget(size, options, dummy) {
  14028. var _this;
  14029. if (Number.isInteger(options)) {
  14030. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  14031. options = dummy;
  14032. }
  14033. _this = _WebGLRenderTarget.call(this, size, size, options) || this;
  14034. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLCubeRenderTarget', {
  14035. value: true
  14036. });
  14037. options = options || {};
  14038. _this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  14039. _this.texture._needsFlipEnvMap = false;
  14040. return _this;
  14041. }
  14042. var _proto = WebGLCubeRenderTarget.prototype;
  14043. _proto.fromEquirectangularTexture = function fromEquirectangularTexture(renderer, texture) {
  14044. this.texture.type = texture.type;
  14045. this.texture.format = RGBAFormat; // see #18859
  14046. this.texture.encoding = texture.encoding;
  14047. this.texture.generateMipmaps = texture.generateMipmaps;
  14048. this.texture.minFilter = texture.minFilter;
  14049. this.texture.magFilter = texture.magFilter;
  14050. var shader = {
  14051. uniforms: {
  14052. tEquirect: {
  14053. value: null
  14054. }
  14055. },
  14056. vertexShader:
  14057. /* glsl */
  14058. "\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",
  14059. fragmentShader:
  14060. /* glsl */
  14061. "\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"
  14062. };
  14063. var geometry = new BoxGeometry(5, 5, 5);
  14064. var material = new ShaderMaterial({
  14065. name: 'CubemapFromEquirect',
  14066. uniforms: cloneUniforms(shader.uniforms),
  14067. vertexShader: shader.vertexShader,
  14068. fragmentShader: shader.fragmentShader,
  14069. side: BackSide,
  14070. blending: NoBlending
  14071. });
  14072. material.uniforms.tEquirect.value = texture;
  14073. var mesh = new Mesh(geometry, material);
  14074. var currentMinFilter = texture.minFilter; // Avoid blurred poles
  14075. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  14076. var camera = new CubeCamera(1, 10, this);
  14077. camera.update(renderer, mesh);
  14078. texture.minFilter = currentMinFilter;
  14079. mesh.geometry.dispose();
  14080. mesh.material.dispose();
  14081. return this;
  14082. };
  14083. _proto.clear = function clear(renderer, color, depth, stencil) {
  14084. var currentRenderTarget = renderer.getRenderTarget();
  14085. for (var i = 0; i < 6; i++) {
  14086. renderer.setRenderTarget(this, i);
  14087. renderer.clear(color, depth, stencil);
  14088. }
  14089. renderer.setRenderTarget(currentRenderTarget);
  14090. };
  14091. return WebGLCubeRenderTarget;
  14092. }(WebGLRenderTarget);
  14093. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  14094. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  14095. this.image = {
  14096. data: data || null,
  14097. width: width || 1,
  14098. height: height || 1
  14099. };
  14100. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14101. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14102. this.generateMipmaps = false;
  14103. this.flipY = false;
  14104. this.unpackAlignment = 1;
  14105. this.needsUpdate = true;
  14106. }
  14107. DataTexture.prototype = Object.create(Texture.prototype);
  14108. DataTexture.prototype.constructor = DataTexture;
  14109. DataTexture.prototype.isDataTexture = true;
  14110. var _sphere$1 = /*@__PURE__*/new Sphere();
  14111. var _vector$5 = /*@__PURE__*/new Vector3();
  14112. var Frustum = /*#__PURE__*/function () {
  14113. function Frustum(p0, p1, p2, p3, p4, p5) {
  14114. 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()];
  14115. }
  14116. var _proto = Frustum.prototype;
  14117. _proto.set = function set(p0, p1, p2, p3, p4, p5) {
  14118. var planes = this.planes;
  14119. planes[0].copy(p0);
  14120. planes[1].copy(p1);
  14121. planes[2].copy(p2);
  14122. planes[3].copy(p3);
  14123. planes[4].copy(p4);
  14124. planes[5].copy(p5);
  14125. return this;
  14126. };
  14127. _proto.clone = function clone() {
  14128. return new this.constructor().copy(this);
  14129. };
  14130. _proto.copy = function copy(frustum) {
  14131. var planes = this.planes;
  14132. for (var i = 0; i < 6; i++) {
  14133. planes[i].copy(frustum.planes[i]);
  14134. }
  14135. return this;
  14136. };
  14137. _proto.setFromProjectionMatrix = function setFromProjectionMatrix(m) {
  14138. var planes = this.planes;
  14139. var me = m.elements;
  14140. var me0 = me[0],
  14141. me1 = me[1],
  14142. me2 = me[2],
  14143. me3 = me[3];
  14144. var me4 = me[4],
  14145. me5 = me[5],
  14146. me6 = me[6],
  14147. me7 = me[7];
  14148. var me8 = me[8],
  14149. me9 = me[9],
  14150. me10 = me[10],
  14151. me11 = me[11];
  14152. var me12 = me[12],
  14153. me13 = me[13],
  14154. me14 = me[14],
  14155. me15 = me[15];
  14156. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  14157. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  14158. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  14159. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  14160. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  14161. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  14162. return this;
  14163. };
  14164. _proto.intersectsObject = function intersectsObject(object) {
  14165. var geometry = object.geometry;
  14166. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  14167. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  14168. return this.intersectsSphere(_sphere$1);
  14169. };
  14170. _proto.intersectsSprite = function intersectsSprite(sprite) {
  14171. _sphere$1.center.set(0, 0, 0);
  14172. _sphere$1.radius = 0.7071067811865476;
  14173. _sphere$1.applyMatrix4(sprite.matrixWorld);
  14174. return this.intersectsSphere(_sphere$1);
  14175. };
  14176. _proto.intersectsSphere = function intersectsSphere(sphere) {
  14177. var planes = this.planes;
  14178. var center = sphere.center;
  14179. var negRadius = -sphere.radius;
  14180. for (var i = 0; i < 6; i++) {
  14181. var distance = planes[i].distanceToPoint(center);
  14182. if (distance < negRadius) {
  14183. return false;
  14184. }
  14185. }
  14186. return true;
  14187. };
  14188. _proto.intersectsBox = function intersectsBox(box) {
  14189. var planes = this.planes;
  14190. for (var i = 0; i < 6; i++) {
  14191. var plane = planes[i]; // corner at max distance
  14192. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  14193. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  14194. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  14195. if (plane.distanceToPoint(_vector$5) < 0) {
  14196. return false;
  14197. }
  14198. }
  14199. return true;
  14200. };
  14201. _proto.containsPoint = function containsPoint(point) {
  14202. var planes = this.planes;
  14203. for (var i = 0; i < 6; i++) {
  14204. if (planes[i].distanceToPoint(point) < 0) {
  14205. return false;
  14206. }
  14207. }
  14208. return true;
  14209. };
  14210. return Frustum;
  14211. }();
  14212. function WebGLAnimation() {
  14213. var context = null;
  14214. var isAnimating = false;
  14215. var animationLoop = null;
  14216. var requestId = null;
  14217. function onAnimationFrame(time, frame) {
  14218. animationLoop(time, frame);
  14219. requestId = context.requestAnimationFrame(onAnimationFrame);
  14220. }
  14221. return {
  14222. start: function start() {
  14223. if (isAnimating === true) return;
  14224. if (animationLoop === null) return;
  14225. requestId = context.requestAnimationFrame(onAnimationFrame);
  14226. isAnimating = true;
  14227. },
  14228. stop: function stop() {
  14229. context.cancelAnimationFrame(requestId);
  14230. isAnimating = false;
  14231. },
  14232. setAnimationLoop: function setAnimationLoop(callback) {
  14233. animationLoop = callback;
  14234. },
  14235. setContext: function setContext(value) {
  14236. context = value;
  14237. }
  14238. };
  14239. }
  14240. function WebGLAttributes(gl, capabilities) {
  14241. var isWebGL2 = capabilities.isWebGL2;
  14242. var buffers = new WeakMap();
  14243. function createBuffer(attribute, bufferType) {
  14244. var array = attribute.array;
  14245. var usage = attribute.usage;
  14246. var buffer = gl.createBuffer();
  14247. gl.bindBuffer(bufferType, buffer);
  14248. gl.bufferData(bufferType, array, usage);
  14249. attribute.onUploadCallback();
  14250. var type = 5126;
  14251. if (array instanceof Float32Array) {
  14252. type = 5126;
  14253. } else if (array instanceof Float64Array) {
  14254. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  14255. } else if (array instanceof Uint16Array) {
  14256. if (attribute.isFloat16BufferAttribute) {
  14257. if (isWebGL2) {
  14258. type = 5131;
  14259. } else {
  14260. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  14261. }
  14262. } else {
  14263. type = 5123;
  14264. }
  14265. } else if (array instanceof Int16Array) {
  14266. type = 5122;
  14267. } else if (array instanceof Uint32Array) {
  14268. type = 5125;
  14269. } else if (array instanceof Int32Array) {
  14270. type = 5124;
  14271. } else if (array instanceof Int8Array) {
  14272. type = 5120;
  14273. } else if (array instanceof Uint8Array) {
  14274. type = 5121;
  14275. }
  14276. return {
  14277. buffer: buffer,
  14278. type: type,
  14279. bytesPerElement: array.BYTES_PER_ELEMENT,
  14280. version: attribute.version
  14281. };
  14282. }
  14283. function updateBuffer(buffer, attribute, bufferType) {
  14284. var array = attribute.array;
  14285. var updateRange = attribute.updateRange;
  14286. gl.bindBuffer(bufferType, buffer);
  14287. if (updateRange.count === -1) {
  14288. // Not using update ranges
  14289. gl.bufferSubData(bufferType, 0, array);
  14290. } else {
  14291. if (isWebGL2) {
  14292. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  14293. } else {
  14294. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  14295. }
  14296. updateRange.count = -1; // reset range
  14297. }
  14298. } //
  14299. function get(attribute) {
  14300. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14301. return buffers.get(attribute);
  14302. }
  14303. function remove(attribute) {
  14304. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14305. var data = buffers.get(attribute);
  14306. if (data) {
  14307. gl.deleteBuffer(data.buffer);
  14308. buffers.delete(attribute);
  14309. }
  14310. }
  14311. function update(attribute, bufferType) {
  14312. if (attribute.isGLBufferAttribute) {
  14313. var cached = buffers.get(attribute);
  14314. if (!cached || cached.version < attribute.version) {
  14315. buffers.set(attribute, {
  14316. buffer: attribute.buffer,
  14317. type: attribute.type,
  14318. bytesPerElement: attribute.elementSize,
  14319. version: attribute.version
  14320. });
  14321. }
  14322. return;
  14323. }
  14324. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14325. var data = buffers.get(attribute);
  14326. if (data === undefined) {
  14327. buffers.set(attribute, createBuffer(attribute, bufferType));
  14328. } else if (data.version < attribute.version) {
  14329. updateBuffer(data.buffer, attribute, bufferType);
  14330. data.version = attribute.version;
  14331. }
  14332. }
  14333. return {
  14334. get: get,
  14335. remove: remove,
  14336. update: update
  14337. };
  14338. }
  14339. var PlaneGeometry = /*#__PURE__*/function (_BufferGeometry) {
  14340. _inheritsLoose(PlaneGeometry, _BufferGeometry);
  14341. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  14342. var _this;
  14343. if (width === void 0) {
  14344. width = 1;
  14345. }
  14346. if (height === void 0) {
  14347. height = 1;
  14348. }
  14349. if (widthSegments === void 0) {
  14350. widthSegments = 1;
  14351. }
  14352. if (heightSegments === void 0) {
  14353. heightSegments = 1;
  14354. }
  14355. _this = _BufferGeometry.call(this) || this;
  14356. _this.type = 'PlaneGeometry';
  14357. _this.parameters = {
  14358. width: width,
  14359. height: height,
  14360. widthSegments: widthSegments,
  14361. heightSegments: heightSegments
  14362. };
  14363. var width_half = width / 2;
  14364. var height_half = height / 2;
  14365. var gridX = Math.floor(widthSegments);
  14366. var gridY = Math.floor(heightSegments);
  14367. var gridX1 = gridX + 1;
  14368. var gridY1 = gridY + 1;
  14369. var segment_width = width / gridX;
  14370. var segment_height = height / gridY; //
  14371. var indices = [];
  14372. var vertices = [];
  14373. var normals = [];
  14374. var uvs = [];
  14375. for (var iy = 0; iy < gridY1; iy++) {
  14376. var y = iy * segment_height - height_half;
  14377. for (var ix = 0; ix < gridX1; ix++) {
  14378. var x = ix * segment_width - width_half;
  14379. vertices.push(x, -y, 0);
  14380. normals.push(0, 0, 1);
  14381. uvs.push(ix / gridX);
  14382. uvs.push(1 - iy / gridY);
  14383. }
  14384. }
  14385. for (var _iy = 0; _iy < gridY; _iy++) {
  14386. for (var _ix = 0; _ix < gridX; _ix++) {
  14387. var a = _ix + gridX1 * _iy;
  14388. var b = _ix + gridX1 * (_iy + 1);
  14389. var c = _ix + 1 + gridX1 * (_iy + 1);
  14390. var d = _ix + 1 + gridX1 * _iy;
  14391. indices.push(a, b, d);
  14392. indices.push(b, c, d);
  14393. }
  14394. }
  14395. _this.setIndex(indices);
  14396. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  14397. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  14398. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  14399. return _this;
  14400. }
  14401. return PlaneGeometry;
  14402. }(BufferGeometry);
  14403. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  14404. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  14405. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  14406. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  14407. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  14408. var begin_vertex = "vec3 transformed = vec3( position );";
  14409. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  14410. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\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\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\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\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\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\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\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\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\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\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\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\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\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\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  14411. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\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\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\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;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  14412. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  14413. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  14414. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  14415. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  14416. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  14417. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  14418. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  14419. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  14420. var common = "#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#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\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 ) ); }\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#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\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\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\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  14421. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\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\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\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\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  14422. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  14423. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  14424. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  14425. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  14426. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  14427. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  14428. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\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}\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}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\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}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\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}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\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\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\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}\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}";
  14429. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  14430. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\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";
  14431. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  14432. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  14433. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  14434. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  14435. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  14436. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  14437. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  14438. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  14439. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  14440. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  14441. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  14442. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\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\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\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\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\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\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\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\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\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  14443. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  14444. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  14445. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  14446. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  14447. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  14448. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  14449. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\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\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\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\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\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\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\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\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\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\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  14450. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\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\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\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\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\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\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  14451. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  14452. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  14453. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  14454. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  14455. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  14456. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  14457. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  14458. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  14459. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  14460. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  14461. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  14462. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  14463. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  14464. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  14465. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\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\t#endif\n#endif";
  14466. var normal_fragment_begin = "#ifdef FLAT_SHADED\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#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\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\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  14467. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  14468. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\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\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\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\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  14469. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  14470. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  14471. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  14472. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\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}\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}\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}";
  14473. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  14474. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  14475. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  14476. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  14477. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  14478. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  14479. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\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\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\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\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\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\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\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 );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\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\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\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\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\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\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\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\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\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\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\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  14480. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\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\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\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\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\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\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  14481. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  14482. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\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\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  14483. var skinbase_vertex = "#ifdef USE_SKINNING\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#endif";
  14484. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\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\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\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\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  14485. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  14486. var skinnormal_vertex = "#ifdef USE_SKINNING\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\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  14487. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  14488. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  14489. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  14490. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\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}\nvec3 RRTAndODTFit( vec3 v ) {\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}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  14491. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  14492. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  14493. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  14494. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  14495. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  14496. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  14497. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  14498. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  14499. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  14500. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14501. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  14502. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14503. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  14504. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\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>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  14505. var depth_vert = "#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>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\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\tvHighPrecisionZW = gl_Position.zw;\n}";
  14506. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\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>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  14507. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\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\tvWorldPosition = worldPosition.xyz;\n}";
  14508. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14509. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  14510. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  14511. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\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>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}";
  14512. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14513. var meshbasic_vert = "#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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\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 <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  14514. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\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\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\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14515. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_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\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\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}";
  14516. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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#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>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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\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;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14517. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\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\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\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\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  14518. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\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\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\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14519. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14520. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\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\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\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14521. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14522. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\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\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  14523. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14524. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  14525. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\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>\nvoid main() {\n\t#include <uv_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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  14526. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  14527. var points_vert = "uniform float size;\nuniform float scale;\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>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  14528. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\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>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14529. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_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\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14530. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\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>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14531. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\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\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\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\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14532. var ShaderChunk = {
  14533. alphamap_fragment: alphamap_fragment,
  14534. alphamap_pars_fragment: alphamap_pars_fragment,
  14535. alphatest_fragment: alphatest_fragment,
  14536. aomap_fragment: aomap_fragment,
  14537. aomap_pars_fragment: aomap_pars_fragment,
  14538. begin_vertex: begin_vertex,
  14539. beginnormal_vertex: beginnormal_vertex,
  14540. bsdfs: bsdfs,
  14541. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14542. clipping_planes_fragment: clipping_planes_fragment,
  14543. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14544. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14545. clipping_planes_vertex: clipping_planes_vertex,
  14546. color_fragment: color_fragment,
  14547. color_pars_fragment: color_pars_fragment,
  14548. color_pars_vertex: color_pars_vertex,
  14549. color_vertex: color_vertex,
  14550. common: common,
  14551. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14552. defaultnormal_vertex: defaultnormal_vertex,
  14553. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14554. displacementmap_vertex: displacementmap_vertex,
  14555. emissivemap_fragment: emissivemap_fragment,
  14556. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14557. encodings_fragment: encodings_fragment,
  14558. encodings_pars_fragment: encodings_pars_fragment,
  14559. envmap_fragment: envmap_fragment,
  14560. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14561. envmap_pars_fragment: envmap_pars_fragment,
  14562. envmap_pars_vertex: envmap_pars_vertex,
  14563. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14564. envmap_vertex: envmap_vertex,
  14565. fog_vertex: fog_vertex,
  14566. fog_pars_vertex: fog_pars_vertex,
  14567. fog_fragment: fog_fragment,
  14568. fog_pars_fragment: fog_pars_fragment,
  14569. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14570. lightmap_fragment: lightmap_fragment,
  14571. lightmap_pars_fragment: lightmap_pars_fragment,
  14572. lights_lambert_vertex: lights_lambert_vertex,
  14573. lights_pars_begin: lights_pars_begin,
  14574. lights_toon_fragment: lights_toon_fragment,
  14575. lights_toon_pars_fragment: lights_toon_pars_fragment,
  14576. lights_phong_fragment: lights_phong_fragment,
  14577. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14578. lights_physical_fragment: lights_physical_fragment,
  14579. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14580. lights_fragment_begin: lights_fragment_begin,
  14581. lights_fragment_maps: lights_fragment_maps,
  14582. lights_fragment_end: lights_fragment_end,
  14583. logdepthbuf_fragment: logdepthbuf_fragment,
  14584. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14585. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14586. logdepthbuf_vertex: logdepthbuf_vertex,
  14587. map_fragment: map_fragment,
  14588. map_pars_fragment: map_pars_fragment,
  14589. map_particle_fragment: map_particle_fragment,
  14590. map_particle_pars_fragment: map_particle_pars_fragment,
  14591. metalnessmap_fragment: metalnessmap_fragment,
  14592. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14593. morphnormal_vertex: morphnormal_vertex,
  14594. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14595. morphtarget_vertex: morphtarget_vertex,
  14596. normal_fragment_begin: normal_fragment_begin,
  14597. normal_fragment_maps: normal_fragment_maps,
  14598. normalmap_pars_fragment: normalmap_pars_fragment,
  14599. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14600. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14601. clearcoat_pars_fragment: clearcoat_pars_fragment,
  14602. packing: packing,
  14603. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14604. project_vertex: project_vertex,
  14605. dithering_fragment: dithering_fragment,
  14606. dithering_pars_fragment: dithering_pars_fragment,
  14607. roughnessmap_fragment: roughnessmap_fragment,
  14608. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14609. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14610. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14611. shadowmap_vertex: shadowmap_vertex,
  14612. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14613. skinbase_vertex: skinbase_vertex,
  14614. skinning_pars_vertex: skinning_pars_vertex,
  14615. skinning_vertex: skinning_vertex,
  14616. skinnormal_vertex: skinnormal_vertex,
  14617. specularmap_fragment: specularmap_fragment,
  14618. specularmap_pars_fragment: specularmap_pars_fragment,
  14619. tonemapping_fragment: tonemapping_fragment,
  14620. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14621. transmissionmap_fragment: transmissionmap_fragment,
  14622. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  14623. uv_pars_fragment: uv_pars_fragment,
  14624. uv_pars_vertex: uv_pars_vertex,
  14625. uv_vertex: uv_vertex,
  14626. uv2_pars_fragment: uv2_pars_fragment,
  14627. uv2_pars_vertex: uv2_pars_vertex,
  14628. uv2_vertex: uv2_vertex,
  14629. worldpos_vertex: worldpos_vertex,
  14630. background_frag: background_frag,
  14631. background_vert: background_vert,
  14632. cube_frag: cube_frag,
  14633. cube_vert: cube_vert,
  14634. depth_frag: depth_frag,
  14635. depth_vert: depth_vert,
  14636. distanceRGBA_frag: distanceRGBA_frag,
  14637. distanceRGBA_vert: distanceRGBA_vert,
  14638. equirect_frag: equirect_frag,
  14639. equirect_vert: equirect_vert,
  14640. linedashed_frag: linedashed_frag,
  14641. linedashed_vert: linedashed_vert,
  14642. meshbasic_frag: meshbasic_frag,
  14643. meshbasic_vert: meshbasic_vert,
  14644. meshlambert_frag: meshlambert_frag,
  14645. meshlambert_vert: meshlambert_vert,
  14646. meshmatcap_frag: meshmatcap_frag,
  14647. meshmatcap_vert: meshmatcap_vert,
  14648. meshtoon_frag: meshtoon_frag,
  14649. meshtoon_vert: meshtoon_vert,
  14650. meshphong_frag: meshphong_frag,
  14651. meshphong_vert: meshphong_vert,
  14652. meshphysical_frag: meshphysical_frag,
  14653. meshphysical_vert: meshphysical_vert,
  14654. normal_frag: normal_frag,
  14655. normal_vert: normal_vert,
  14656. points_frag: points_frag,
  14657. points_vert: points_vert,
  14658. shadow_frag: shadow_frag,
  14659. shadow_vert: shadow_vert,
  14660. sprite_frag: sprite_frag,
  14661. sprite_vert: sprite_vert
  14662. };
  14663. /**
  14664. * Uniforms library for shared webgl shaders
  14665. */
  14666. var UniformsLib = {
  14667. common: {
  14668. diffuse: {
  14669. value: new Color(0xeeeeee)
  14670. },
  14671. opacity: {
  14672. value: 1.0
  14673. },
  14674. map: {
  14675. value: null
  14676. },
  14677. uvTransform: {
  14678. value: new Matrix3()
  14679. },
  14680. uv2Transform: {
  14681. value: new Matrix3()
  14682. },
  14683. alphaMap: {
  14684. value: null
  14685. }
  14686. },
  14687. specularmap: {
  14688. specularMap: {
  14689. value: null
  14690. }
  14691. },
  14692. envmap: {
  14693. envMap: {
  14694. value: null
  14695. },
  14696. flipEnvMap: {
  14697. value: -1
  14698. },
  14699. reflectivity: {
  14700. value: 1.0
  14701. },
  14702. refractionRatio: {
  14703. value: 0.98
  14704. },
  14705. maxMipLevel: {
  14706. value: 0
  14707. }
  14708. },
  14709. aomap: {
  14710. aoMap: {
  14711. value: null
  14712. },
  14713. aoMapIntensity: {
  14714. value: 1
  14715. }
  14716. },
  14717. lightmap: {
  14718. lightMap: {
  14719. value: null
  14720. },
  14721. lightMapIntensity: {
  14722. value: 1
  14723. }
  14724. },
  14725. emissivemap: {
  14726. emissiveMap: {
  14727. value: null
  14728. }
  14729. },
  14730. bumpmap: {
  14731. bumpMap: {
  14732. value: null
  14733. },
  14734. bumpScale: {
  14735. value: 1
  14736. }
  14737. },
  14738. normalmap: {
  14739. normalMap: {
  14740. value: null
  14741. },
  14742. normalScale: {
  14743. value: new Vector2(1, 1)
  14744. }
  14745. },
  14746. displacementmap: {
  14747. displacementMap: {
  14748. value: null
  14749. },
  14750. displacementScale: {
  14751. value: 1
  14752. },
  14753. displacementBias: {
  14754. value: 0
  14755. }
  14756. },
  14757. roughnessmap: {
  14758. roughnessMap: {
  14759. value: null
  14760. }
  14761. },
  14762. metalnessmap: {
  14763. metalnessMap: {
  14764. value: null
  14765. }
  14766. },
  14767. gradientmap: {
  14768. gradientMap: {
  14769. value: null
  14770. }
  14771. },
  14772. fog: {
  14773. fogDensity: {
  14774. value: 0.00025
  14775. },
  14776. fogNear: {
  14777. value: 1
  14778. },
  14779. fogFar: {
  14780. value: 2000
  14781. },
  14782. fogColor: {
  14783. value: new Color(0xffffff)
  14784. }
  14785. },
  14786. lights: {
  14787. ambientLightColor: {
  14788. value: []
  14789. },
  14790. lightProbe: {
  14791. value: []
  14792. },
  14793. directionalLights: {
  14794. value: [],
  14795. properties: {
  14796. direction: {},
  14797. color: {}
  14798. }
  14799. },
  14800. directionalLightShadows: {
  14801. value: [],
  14802. properties: {
  14803. shadowBias: {},
  14804. shadowNormalBias: {},
  14805. shadowRadius: {},
  14806. shadowMapSize: {}
  14807. }
  14808. },
  14809. directionalShadowMap: {
  14810. value: []
  14811. },
  14812. directionalShadowMatrix: {
  14813. value: []
  14814. },
  14815. spotLights: {
  14816. value: [],
  14817. properties: {
  14818. color: {},
  14819. position: {},
  14820. direction: {},
  14821. distance: {},
  14822. coneCos: {},
  14823. penumbraCos: {},
  14824. decay: {}
  14825. }
  14826. },
  14827. spotLightShadows: {
  14828. value: [],
  14829. properties: {
  14830. shadowBias: {},
  14831. shadowNormalBias: {},
  14832. shadowRadius: {},
  14833. shadowMapSize: {}
  14834. }
  14835. },
  14836. spotShadowMap: {
  14837. value: []
  14838. },
  14839. spotShadowMatrix: {
  14840. value: []
  14841. },
  14842. pointLights: {
  14843. value: [],
  14844. properties: {
  14845. color: {},
  14846. position: {},
  14847. decay: {},
  14848. distance: {}
  14849. }
  14850. },
  14851. pointLightShadows: {
  14852. value: [],
  14853. properties: {
  14854. shadowBias: {},
  14855. shadowNormalBias: {},
  14856. shadowRadius: {},
  14857. shadowMapSize: {},
  14858. shadowCameraNear: {},
  14859. shadowCameraFar: {}
  14860. }
  14861. },
  14862. pointShadowMap: {
  14863. value: []
  14864. },
  14865. pointShadowMatrix: {
  14866. value: []
  14867. },
  14868. hemisphereLights: {
  14869. value: [],
  14870. properties: {
  14871. direction: {},
  14872. skyColor: {},
  14873. groundColor: {}
  14874. }
  14875. },
  14876. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14877. rectAreaLights: {
  14878. value: [],
  14879. properties: {
  14880. color: {},
  14881. position: {},
  14882. width: {},
  14883. height: {}
  14884. }
  14885. },
  14886. ltc_1: {
  14887. value: null
  14888. },
  14889. ltc_2: {
  14890. value: null
  14891. }
  14892. },
  14893. points: {
  14894. diffuse: {
  14895. value: new Color(0xeeeeee)
  14896. },
  14897. opacity: {
  14898. value: 1.0
  14899. },
  14900. size: {
  14901. value: 1.0
  14902. },
  14903. scale: {
  14904. value: 1.0
  14905. },
  14906. map: {
  14907. value: null
  14908. },
  14909. alphaMap: {
  14910. value: null
  14911. },
  14912. uvTransform: {
  14913. value: new Matrix3()
  14914. }
  14915. },
  14916. sprite: {
  14917. diffuse: {
  14918. value: new Color(0xeeeeee)
  14919. },
  14920. opacity: {
  14921. value: 1.0
  14922. },
  14923. center: {
  14924. value: new Vector2(0.5, 0.5)
  14925. },
  14926. rotation: {
  14927. value: 0.0
  14928. },
  14929. map: {
  14930. value: null
  14931. },
  14932. alphaMap: {
  14933. value: null
  14934. },
  14935. uvTransform: {
  14936. value: new Matrix3()
  14937. }
  14938. }
  14939. };
  14940. var ShaderLib = {
  14941. basic: {
  14942. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  14943. vertexShader: ShaderChunk.meshbasic_vert,
  14944. fragmentShader: ShaderChunk.meshbasic_frag
  14945. },
  14946. lambert: {
  14947. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  14948. emissive: {
  14949. value: new Color(0x000000)
  14950. }
  14951. }]),
  14952. vertexShader: ShaderChunk.meshlambert_vert,
  14953. fragmentShader: ShaderChunk.meshlambert_frag
  14954. },
  14955. phong: {
  14956. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  14957. emissive: {
  14958. value: new Color(0x000000)
  14959. },
  14960. specular: {
  14961. value: new Color(0x111111)
  14962. },
  14963. shininess: {
  14964. value: 30
  14965. }
  14966. }]),
  14967. vertexShader: ShaderChunk.meshphong_vert,
  14968. fragmentShader: ShaderChunk.meshphong_frag
  14969. },
  14970. standard: {
  14971. 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, {
  14972. emissive: {
  14973. value: new Color(0x000000)
  14974. },
  14975. roughness: {
  14976. value: 1.0
  14977. },
  14978. metalness: {
  14979. value: 0.0
  14980. },
  14981. envMapIntensity: {
  14982. value: 1
  14983. } // temporary
  14984. }]),
  14985. vertexShader: ShaderChunk.meshphysical_vert,
  14986. fragmentShader: ShaderChunk.meshphysical_frag
  14987. },
  14988. toon: {
  14989. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  14990. emissive: {
  14991. value: new Color(0x000000)
  14992. }
  14993. }]),
  14994. vertexShader: ShaderChunk.meshtoon_vert,
  14995. fragmentShader: ShaderChunk.meshtoon_frag
  14996. },
  14997. matcap: {
  14998. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  14999. matcap: {
  15000. value: null
  15001. }
  15002. }]),
  15003. vertexShader: ShaderChunk.meshmatcap_vert,
  15004. fragmentShader: ShaderChunk.meshmatcap_frag
  15005. },
  15006. points: {
  15007. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  15008. vertexShader: ShaderChunk.points_vert,
  15009. fragmentShader: ShaderChunk.points_frag
  15010. },
  15011. dashed: {
  15012. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  15013. scale: {
  15014. value: 1
  15015. },
  15016. dashSize: {
  15017. value: 1
  15018. },
  15019. totalSize: {
  15020. value: 2
  15021. }
  15022. }]),
  15023. vertexShader: ShaderChunk.linedashed_vert,
  15024. fragmentShader: ShaderChunk.linedashed_frag
  15025. },
  15026. depth: {
  15027. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  15028. vertexShader: ShaderChunk.depth_vert,
  15029. fragmentShader: ShaderChunk.depth_frag
  15030. },
  15031. normal: {
  15032. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  15033. opacity: {
  15034. value: 1.0
  15035. }
  15036. }]),
  15037. vertexShader: ShaderChunk.normal_vert,
  15038. fragmentShader: ShaderChunk.normal_frag
  15039. },
  15040. sprite: {
  15041. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  15042. vertexShader: ShaderChunk.sprite_vert,
  15043. fragmentShader: ShaderChunk.sprite_frag
  15044. },
  15045. background: {
  15046. uniforms: {
  15047. uvTransform: {
  15048. value: new Matrix3()
  15049. },
  15050. t2D: {
  15051. value: null
  15052. }
  15053. },
  15054. vertexShader: ShaderChunk.background_vert,
  15055. fragmentShader: ShaderChunk.background_frag
  15056. },
  15057. /* -------------------------------------------------------------------------
  15058. // Cube map shader
  15059. ------------------------------------------------------------------------- */
  15060. cube: {
  15061. uniforms: mergeUniforms([UniformsLib.envmap, {
  15062. opacity: {
  15063. value: 1.0
  15064. }
  15065. }]),
  15066. vertexShader: ShaderChunk.cube_vert,
  15067. fragmentShader: ShaderChunk.cube_frag
  15068. },
  15069. equirect: {
  15070. uniforms: {
  15071. tEquirect: {
  15072. value: null
  15073. }
  15074. },
  15075. vertexShader: ShaderChunk.equirect_vert,
  15076. fragmentShader: ShaderChunk.equirect_frag
  15077. },
  15078. distanceRGBA: {
  15079. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  15080. referencePosition: {
  15081. value: new Vector3()
  15082. },
  15083. nearDistance: {
  15084. value: 1
  15085. },
  15086. farDistance: {
  15087. value: 1000
  15088. }
  15089. }]),
  15090. vertexShader: ShaderChunk.distanceRGBA_vert,
  15091. fragmentShader: ShaderChunk.distanceRGBA_frag
  15092. },
  15093. shadow: {
  15094. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  15095. color: {
  15096. value: new Color(0x00000)
  15097. },
  15098. opacity: {
  15099. value: 1.0
  15100. }
  15101. }]),
  15102. vertexShader: ShaderChunk.shadow_vert,
  15103. fragmentShader: ShaderChunk.shadow_frag
  15104. }
  15105. };
  15106. ShaderLib.physical = {
  15107. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  15108. clearcoat: {
  15109. value: 0
  15110. },
  15111. clearcoatMap: {
  15112. value: null
  15113. },
  15114. clearcoatRoughness: {
  15115. value: 0
  15116. },
  15117. clearcoatRoughnessMap: {
  15118. value: null
  15119. },
  15120. clearcoatNormalScale: {
  15121. value: new Vector2(1, 1)
  15122. },
  15123. clearcoatNormalMap: {
  15124. value: null
  15125. },
  15126. sheen: {
  15127. value: new Color(0x000000)
  15128. },
  15129. transmission: {
  15130. value: 0
  15131. },
  15132. transmissionMap: {
  15133. value: null
  15134. }
  15135. }]),
  15136. vertexShader: ShaderChunk.meshphysical_vert,
  15137. fragmentShader: ShaderChunk.meshphysical_frag
  15138. };
  15139. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  15140. var clearColor = new Color(0x000000);
  15141. var clearAlpha = 0;
  15142. var planeMesh;
  15143. var boxMesh;
  15144. var currentBackground = null;
  15145. var currentBackgroundVersion = 0;
  15146. var currentTonemapping = null;
  15147. function render(renderList, scene, camera, forceClear) {
  15148. var background = scene.isScene === true ? scene.background : null;
  15149. if (background && background.isTexture) {
  15150. background = cubemaps.get(background);
  15151. } // Ignore background in AR
  15152. // TODO: Reconsider this.
  15153. var xr = renderer.xr;
  15154. var session = xr.getSession && xr.getSession();
  15155. if (session && session.environmentBlendMode === 'additive') {
  15156. background = null;
  15157. }
  15158. if (background === null) {
  15159. setClear(clearColor, clearAlpha);
  15160. } else if (background && background.isColor) {
  15161. setClear(background, 1);
  15162. forceClear = true;
  15163. }
  15164. if (renderer.autoClear || forceClear) {
  15165. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  15166. }
  15167. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  15168. if (boxMesh === undefined) {
  15169. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  15170. name: 'BackgroundCubeMaterial',
  15171. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  15172. vertexShader: ShaderLib.cube.vertexShader,
  15173. fragmentShader: ShaderLib.cube.fragmentShader,
  15174. side: BackSide,
  15175. depthTest: false,
  15176. depthWrite: false,
  15177. fog: false
  15178. }));
  15179. boxMesh.geometry.deleteAttribute('normal');
  15180. boxMesh.geometry.deleteAttribute('uv');
  15181. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  15182. this.matrixWorld.copyPosition(camera.matrixWorld);
  15183. }; // enable code injection for non-built-in material
  15184. Object.defineProperty(boxMesh.material, 'envMap', {
  15185. get: function get() {
  15186. return this.uniforms.envMap.value;
  15187. }
  15188. });
  15189. objects.update(boxMesh);
  15190. }
  15191. if (background.isWebGLCubeRenderTarget) {
  15192. // TODO Deprecate
  15193. background = background.texture;
  15194. }
  15195. boxMesh.material.uniforms.envMap.value = background;
  15196. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  15197. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  15198. boxMesh.material.needsUpdate = true;
  15199. currentBackground = background;
  15200. currentBackgroundVersion = background.version;
  15201. currentTonemapping = renderer.toneMapping;
  15202. } // push to the pre-sorted opaque render list
  15203. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  15204. } else if (background && background.isTexture) {
  15205. if (planeMesh === undefined) {
  15206. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  15207. name: 'BackgroundMaterial',
  15208. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  15209. vertexShader: ShaderLib.background.vertexShader,
  15210. fragmentShader: ShaderLib.background.fragmentShader,
  15211. side: FrontSide,
  15212. depthTest: false,
  15213. depthWrite: false,
  15214. fog: false
  15215. }));
  15216. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  15217. Object.defineProperty(planeMesh.material, 'map', {
  15218. get: function get() {
  15219. return this.uniforms.t2D.value;
  15220. }
  15221. });
  15222. objects.update(planeMesh);
  15223. }
  15224. planeMesh.material.uniforms.t2D.value = background;
  15225. if (background.matrixAutoUpdate === true) {
  15226. background.updateMatrix();
  15227. }
  15228. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  15229. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  15230. planeMesh.material.needsUpdate = true;
  15231. currentBackground = background;
  15232. currentBackgroundVersion = background.version;
  15233. currentTonemapping = renderer.toneMapping;
  15234. } // push to the pre-sorted opaque render list
  15235. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  15236. }
  15237. }
  15238. function setClear(color, alpha) {
  15239. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  15240. }
  15241. return {
  15242. getClearColor: function getClearColor() {
  15243. return clearColor;
  15244. },
  15245. setClearColor: function setClearColor(color, alpha) {
  15246. if (alpha === void 0) {
  15247. alpha = 1;
  15248. }
  15249. clearColor.set(color);
  15250. clearAlpha = alpha;
  15251. setClear(clearColor, clearAlpha);
  15252. },
  15253. getClearAlpha: function getClearAlpha() {
  15254. return clearAlpha;
  15255. },
  15256. setClearAlpha: function setClearAlpha(alpha) {
  15257. clearAlpha = alpha;
  15258. setClear(clearColor, clearAlpha);
  15259. },
  15260. render: render
  15261. };
  15262. }
  15263. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  15264. var maxVertexAttributes = gl.getParameter(34921);
  15265. var extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  15266. var vaoAvailable = capabilities.isWebGL2 || extension !== null;
  15267. var bindingStates = {};
  15268. var defaultState = createBindingState(null);
  15269. var currentState = defaultState;
  15270. function setup(object, material, program, geometry, index) {
  15271. var updateBuffers = false;
  15272. if (vaoAvailable) {
  15273. var state = getBindingState(geometry, program, material);
  15274. if (currentState !== state) {
  15275. currentState = state;
  15276. bindVertexArrayObject(currentState.object);
  15277. }
  15278. updateBuffers = needsUpdate(geometry, index);
  15279. if (updateBuffers) saveCache(geometry, index);
  15280. } else {
  15281. var wireframe = material.wireframe === true;
  15282. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  15283. currentState.geometry = geometry.id;
  15284. currentState.program = program.id;
  15285. currentState.wireframe = wireframe;
  15286. updateBuffers = true;
  15287. }
  15288. }
  15289. if (object.isInstancedMesh === true) {
  15290. updateBuffers = true;
  15291. }
  15292. if (index !== null) {
  15293. attributes.update(index, 34963);
  15294. }
  15295. if (updateBuffers) {
  15296. setupVertexAttributes(object, material, program, geometry);
  15297. if (index !== null) {
  15298. gl.bindBuffer(34963, attributes.get(index).buffer);
  15299. }
  15300. }
  15301. }
  15302. function createVertexArrayObject() {
  15303. if (capabilities.isWebGL2) return gl.createVertexArray();
  15304. return extension.createVertexArrayOES();
  15305. }
  15306. function bindVertexArrayObject(vao) {
  15307. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  15308. return extension.bindVertexArrayOES(vao);
  15309. }
  15310. function deleteVertexArrayObject(vao) {
  15311. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  15312. return extension.deleteVertexArrayOES(vao);
  15313. }
  15314. function getBindingState(geometry, program, material) {
  15315. var wireframe = material.wireframe === true;
  15316. var programMap = bindingStates[geometry.id];
  15317. if (programMap === undefined) {
  15318. programMap = {};
  15319. bindingStates[geometry.id] = programMap;
  15320. }
  15321. var stateMap = programMap[program.id];
  15322. if (stateMap === undefined) {
  15323. stateMap = {};
  15324. programMap[program.id] = stateMap;
  15325. }
  15326. var state = stateMap[wireframe];
  15327. if (state === undefined) {
  15328. state = createBindingState(createVertexArrayObject());
  15329. stateMap[wireframe] = state;
  15330. }
  15331. return state;
  15332. }
  15333. function createBindingState(vao) {
  15334. var newAttributes = [];
  15335. var enabledAttributes = [];
  15336. var attributeDivisors = [];
  15337. for (var i = 0; i < maxVertexAttributes; i++) {
  15338. newAttributes[i] = 0;
  15339. enabledAttributes[i] = 0;
  15340. attributeDivisors[i] = 0;
  15341. }
  15342. return {
  15343. // for backward compatibility on non-VAO support browser
  15344. geometry: null,
  15345. program: null,
  15346. wireframe: false,
  15347. newAttributes: newAttributes,
  15348. enabledAttributes: enabledAttributes,
  15349. attributeDivisors: attributeDivisors,
  15350. object: vao,
  15351. attributes: {},
  15352. index: null
  15353. };
  15354. }
  15355. function needsUpdate(geometry, index) {
  15356. var cachedAttributes = currentState.attributes;
  15357. var geometryAttributes = geometry.attributes;
  15358. var attributesNum = 0;
  15359. for (var key in geometryAttributes) {
  15360. var cachedAttribute = cachedAttributes[key];
  15361. var geometryAttribute = geometryAttributes[key];
  15362. if (cachedAttribute === undefined) return true;
  15363. if (cachedAttribute.attribute !== geometryAttribute) return true;
  15364. if (cachedAttribute.data !== geometryAttribute.data) return true;
  15365. attributesNum++;
  15366. }
  15367. if (currentState.attributesNum !== attributesNum) return true;
  15368. if (currentState.index !== index) return true;
  15369. return false;
  15370. }
  15371. function saveCache(geometry, index) {
  15372. var cache = {};
  15373. var attributes = geometry.attributes;
  15374. var attributesNum = 0;
  15375. for (var key in attributes) {
  15376. var attribute = attributes[key];
  15377. var data = {};
  15378. data.attribute = attribute;
  15379. if (attribute.data) {
  15380. data.data = attribute.data;
  15381. }
  15382. cache[key] = data;
  15383. attributesNum++;
  15384. }
  15385. currentState.attributes = cache;
  15386. currentState.attributesNum = attributesNum;
  15387. currentState.index = index;
  15388. }
  15389. function initAttributes() {
  15390. var newAttributes = currentState.newAttributes;
  15391. for (var i = 0, il = newAttributes.length; i < il; i++) {
  15392. newAttributes[i] = 0;
  15393. }
  15394. }
  15395. function enableAttribute(attribute) {
  15396. enableAttributeAndDivisor(attribute, 0);
  15397. }
  15398. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  15399. var newAttributes = currentState.newAttributes;
  15400. var enabledAttributes = currentState.enabledAttributes;
  15401. var attributeDivisors = currentState.attributeDivisors;
  15402. newAttributes[attribute] = 1;
  15403. if (enabledAttributes[attribute] === 0) {
  15404. gl.enableVertexAttribArray(attribute);
  15405. enabledAttributes[attribute] = 1;
  15406. }
  15407. if (attributeDivisors[attribute] !== meshPerAttribute) {
  15408. var _extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  15409. _extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  15410. attributeDivisors[attribute] = meshPerAttribute;
  15411. }
  15412. }
  15413. function disableUnusedAttributes() {
  15414. var newAttributes = currentState.newAttributes;
  15415. var enabledAttributes = currentState.enabledAttributes;
  15416. for (var i = 0, il = enabledAttributes.length; i < il; i++) {
  15417. if (enabledAttributes[i] !== newAttributes[i]) {
  15418. gl.disableVertexAttribArray(i);
  15419. enabledAttributes[i] = 0;
  15420. }
  15421. }
  15422. }
  15423. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  15424. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  15425. gl.vertexAttribIPointer(index, size, type, stride, offset);
  15426. } else {
  15427. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  15428. }
  15429. }
  15430. function setupVertexAttributes(object, material, program, geometry) {
  15431. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15432. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15433. }
  15434. initAttributes();
  15435. var geometryAttributes = geometry.attributes;
  15436. var programAttributes = program.getAttributes();
  15437. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15438. for (var name in programAttributes) {
  15439. var programAttribute = programAttributes[name];
  15440. if (programAttribute >= 0) {
  15441. var geometryAttribute = geometryAttributes[name];
  15442. if (geometryAttribute !== undefined) {
  15443. var normalized = geometryAttribute.normalized;
  15444. var size = geometryAttribute.itemSize;
  15445. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15446. if (attribute === undefined) continue;
  15447. var buffer = attribute.buffer;
  15448. var type = attribute.type;
  15449. var bytesPerElement = attribute.bytesPerElement;
  15450. if (geometryAttribute.isInterleavedBufferAttribute) {
  15451. var data = geometryAttribute.data;
  15452. var stride = data.stride;
  15453. var offset = geometryAttribute.offset;
  15454. if (data && data.isInstancedInterleavedBuffer) {
  15455. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15456. if (geometry._maxInstanceCount === undefined) {
  15457. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  15458. }
  15459. } else {
  15460. enableAttribute(programAttribute);
  15461. }
  15462. gl.bindBuffer(34962, buffer);
  15463. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15464. } else {
  15465. if (geometryAttribute.isInstancedBufferAttribute) {
  15466. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15467. if (geometry._maxInstanceCount === undefined) {
  15468. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15469. }
  15470. } else {
  15471. enableAttribute(programAttribute);
  15472. }
  15473. gl.bindBuffer(34962, buffer);
  15474. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15475. }
  15476. } else if (name === 'instanceMatrix') {
  15477. var _attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15478. if (_attribute === undefined) continue;
  15479. var _buffer = _attribute.buffer;
  15480. var _type = _attribute.type;
  15481. enableAttributeAndDivisor(programAttribute + 0, 1);
  15482. enableAttributeAndDivisor(programAttribute + 1, 1);
  15483. enableAttributeAndDivisor(programAttribute + 2, 1);
  15484. enableAttributeAndDivisor(programAttribute + 3, 1);
  15485. gl.bindBuffer(34962, _buffer);
  15486. gl.vertexAttribPointer(programAttribute + 0, 4, _type, false, 64, 0);
  15487. gl.vertexAttribPointer(programAttribute + 1, 4, _type, false, 64, 16);
  15488. gl.vertexAttribPointer(programAttribute + 2, 4, _type, false, 64, 32);
  15489. gl.vertexAttribPointer(programAttribute + 3, 4, _type, false, 64, 48);
  15490. } else if (name === 'instanceColor') {
  15491. var _attribute2 = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  15492. if (_attribute2 === undefined) continue;
  15493. var _buffer2 = _attribute2.buffer;
  15494. var _type2 = _attribute2.type;
  15495. enableAttributeAndDivisor(programAttribute, 1);
  15496. gl.bindBuffer(34962, _buffer2);
  15497. gl.vertexAttribPointer(programAttribute, 3, _type2, false, 12, 0);
  15498. } else if (materialDefaultAttributeValues !== undefined) {
  15499. var value = materialDefaultAttributeValues[name];
  15500. if (value !== undefined) {
  15501. switch (value.length) {
  15502. case 2:
  15503. gl.vertexAttrib2fv(programAttribute, value);
  15504. break;
  15505. case 3:
  15506. gl.vertexAttrib3fv(programAttribute, value);
  15507. break;
  15508. case 4:
  15509. gl.vertexAttrib4fv(programAttribute, value);
  15510. break;
  15511. default:
  15512. gl.vertexAttrib1fv(programAttribute, value);
  15513. }
  15514. }
  15515. }
  15516. }
  15517. }
  15518. disableUnusedAttributes();
  15519. }
  15520. function dispose() {
  15521. reset();
  15522. for (var geometryId in bindingStates) {
  15523. var programMap = bindingStates[geometryId];
  15524. for (var programId in programMap) {
  15525. var stateMap = programMap[programId];
  15526. for (var wireframe in stateMap) {
  15527. deleteVertexArrayObject(stateMap[wireframe].object);
  15528. delete stateMap[wireframe];
  15529. }
  15530. delete programMap[programId];
  15531. }
  15532. delete bindingStates[geometryId];
  15533. }
  15534. }
  15535. function releaseStatesOfGeometry(geometry) {
  15536. if (bindingStates[geometry.id] === undefined) return;
  15537. var programMap = bindingStates[geometry.id];
  15538. for (var programId in programMap) {
  15539. var stateMap = programMap[programId];
  15540. for (var wireframe in stateMap) {
  15541. deleteVertexArrayObject(stateMap[wireframe].object);
  15542. delete stateMap[wireframe];
  15543. }
  15544. delete programMap[programId];
  15545. }
  15546. delete bindingStates[geometry.id];
  15547. }
  15548. function releaseStatesOfProgram(program) {
  15549. for (var geometryId in bindingStates) {
  15550. var programMap = bindingStates[geometryId];
  15551. if (programMap[program.id] === undefined) continue;
  15552. var stateMap = programMap[program.id];
  15553. for (var wireframe in stateMap) {
  15554. deleteVertexArrayObject(stateMap[wireframe].object);
  15555. delete stateMap[wireframe];
  15556. }
  15557. delete programMap[program.id];
  15558. }
  15559. }
  15560. function reset() {
  15561. resetDefaultState();
  15562. if (currentState === defaultState) return;
  15563. currentState = defaultState;
  15564. bindVertexArrayObject(currentState.object);
  15565. } // for backward-compatilibity
  15566. function resetDefaultState() {
  15567. defaultState.geometry = null;
  15568. defaultState.program = null;
  15569. defaultState.wireframe = false;
  15570. }
  15571. return {
  15572. setup: setup,
  15573. reset: reset,
  15574. resetDefaultState: resetDefaultState,
  15575. dispose: dispose,
  15576. releaseStatesOfGeometry: releaseStatesOfGeometry,
  15577. releaseStatesOfProgram: releaseStatesOfProgram,
  15578. initAttributes: initAttributes,
  15579. enableAttribute: enableAttribute,
  15580. disableUnusedAttributes: disableUnusedAttributes
  15581. };
  15582. }
  15583. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  15584. var isWebGL2 = capabilities.isWebGL2;
  15585. var mode;
  15586. function setMode(value) {
  15587. mode = value;
  15588. }
  15589. function render(start, count) {
  15590. gl.drawArrays(mode, start, count);
  15591. info.update(count, mode, 1);
  15592. }
  15593. function renderInstances(start, count, primcount) {
  15594. if (primcount === 0) return;
  15595. var extension, methodName;
  15596. if (isWebGL2) {
  15597. extension = gl;
  15598. methodName = 'drawArraysInstanced';
  15599. } else {
  15600. extension = extensions.get('ANGLE_instanced_arrays');
  15601. methodName = 'drawArraysInstancedANGLE';
  15602. if (extension === null) {
  15603. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  15604. return;
  15605. }
  15606. }
  15607. extension[methodName](mode, start, count, primcount);
  15608. info.update(count, mode, primcount);
  15609. } //
  15610. this.setMode = setMode;
  15611. this.render = render;
  15612. this.renderInstances = renderInstances;
  15613. }
  15614. function WebGLCapabilities(gl, extensions, parameters) {
  15615. var maxAnisotropy;
  15616. function getMaxAnisotropy() {
  15617. if (maxAnisotropy !== undefined) return maxAnisotropy;
  15618. var extension = extensions.get('EXT_texture_filter_anisotropic');
  15619. if (extension !== null) {
  15620. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  15621. } else {
  15622. maxAnisotropy = 0;
  15623. }
  15624. return maxAnisotropy;
  15625. }
  15626. function getMaxPrecision(precision) {
  15627. if (precision === 'highp') {
  15628. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  15629. return 'highp';
  15630. }
  15631. precision = 'mediump';
  15632. }
  15633. if (precision === 'mediump') {
  15634. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  15635. return 'mediump';
  15636. }
  15637. }
  15638. return 'lowp';
  15639. }
  15640. /* eslint-disable no-undef */
  15641. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  15642. /* eslint-enable no-undef */
  15643. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15644. var maxPrecision = getMaxPrecision(precision);
  15645. if (maxPrecision !== precision) {
  15646. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  15647. precision = maxPrecision;
  15648. }
  15649. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  15650. var maxTextures = gl.getParameter(34930);
  15651. var maxVertexTextures = gl.getParameter(35660);
  15652. var maxTextureSize = gl.getParameter(3379);
  15653. var maxCubemapSize = gl.getParameter(34076);
  15654. var maxAttributes = gl.getParameter(34921);
  15655. var maxVertexUniforms = gl.getParameter(36347);
  15656. var maxVaryings = gl.getParameter(36348);
  15657. var maxFragmentUniforms = gl.getParameter(36349);
  15658. var vertexTextures = maxVertexTextures > 0;
  15659. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  15660. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15661. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  15662. return {
  15663. isWebGL2: isWebGL2,
  15664. getMaxAnisotropy: getMaxAnisotropy,
  15665. getMaxPrecision: getMaxPrecision,
  15666. precision: precision,
  15667. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15668. maxTextures: maxTextures,
  15669. maxVertexTextures: maxVertexTextures,
  15670. maxTextureSize: maxTextureSize,
  15671. maxCubemapSize: maxCubemapSize,
  15672. maxAttributes: maxAttributes,
  15673. maxVertexUniforms: maxVertexUniforms,
  15674. maxVaryings: maxVaryings,
  15675. maxFragmentUniforms: maxFragmentUniforms,
  15676. vertexTextures: vertexTextures,
  15677. floatFragmentTextures: floatFragmentTextures,
  15678. floatVertexTextures: floatVertexTextures,
  15679. maxSamples: maxSamples
  15680. };
  15681. }
  15682. function WebGLClipping(properties) {
  15683. var scope = this;
  15684. var globalState = null,
  15685. numGlobalPlanes = 0,
  15686. localClippingEnabled = false,
  15687. renderingShadows = false;
  15688. var plane = new Plane(),
  15689. viewNormalMatrix = new Matrix3(),
  15690. uniform = {
  15691. value: null,
  15692. needsUpdate: false
  15693. };
  15694. this.uniform = uniform;
  15695. this.numPlanes = 0;
  15696. this.numIntersection = 0;
  15697. this.init = function (planes, enableLocalClipping, camera) {
  15698. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  15699. // run another frame in order to reset the state:
  15700. numGlobalPlanes !== 0 || localClippingEnabled;
  15701. localClippingEnabled = enableLocalClipping;
  15702. globalState = projectPlanes(planes, camera, 0);
  15703. numGlobalPlanes = planes.length;
  15704. return enabled;
  15705. };
  15706. this.beginShadows = function () {
  15707. renderingShadows = true;
  15708. projectPlanes(null);
  15709. };
  15710. this.endShadows = function () {
  15711. renderingShadows = false;
  15712. resetGlobalState();
  15713. };
  15714. this.setState = function (material, camera, useCache) {
  15715. var planes = material.clippingPlanes,
  15716. clipIntersection = material.clipIntersection,
  15717. clipShadows = material.clipShadows;
  15718. var materialProperties = properties.get(material);
  15719. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  15720. // there's no local clipping
  15721. if (renderingShadows) {
  15722. // there's no global clipping
  15723. projectPlanes(null);
  15724. } else {
  15725. resetGlobalState();
  15726. }
  15727. } else {
  15728. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15729. lGlobal = nGlobal * 4;
  15730. var dstArray = materialProperties.clippingState || null;
  15731. uniform.value = dstArray; // ensure unique state
  15732. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  15733. for (var i = 0; i !== lGlobal; ++i) {
  15734. dstArray[i] = globalState[i];
  15735. }
  15736. materialProperties.clippingState = dstArray;
  15737. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15738. this.numPlanes += nGlobal;
  15739. }
  15740. };
  15741. function resetGlobalState() {
  15742. if (uniform.value !== globalState) {
  15743. uniform.value = globalState;
  15744. uniform.needsUpdate = numGlobalPlanes > 0;
  15745. }
  15746. scope.numPlanes = numGlobalPlanes;
  15747. scope.numIntersection = 0;
  15748. }
  15749. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  15750. var nPlanes = planes !== null ? planes.length : 0;
  15751. var dstArray = null;
  15752. if (nPlanes !== 0) {
  15753. dstArray = uniform.value;
  15754. if (skipTransform !== true || dstArray === null) {
  15755. var flatSize = dstOffset + nPlanes * 4,
  15756. viewMatrix = camera.matrixWorldInverse;
  15757. viewNormalMatrix.getNormalMatrix(viewMatrix);
  15758. if (dstArray === null || dstArray.length < flatSize) {
  15759. dstArray = new Float32Array(flatSize);
  15760. }
  15761. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  15762. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  15763. plane.normal.toArray(dstArray, i4);
  15764. dstArray[i4 + 3] = plane.constant;
  15765. }
  15766. }
  15767. uniform.value = dstArray;
  15768. uniform.needsUpdate = true;
  15769. }
  15770. scope.numPlanes = nPlanes;
  15771. scope.numIntersection = 0;
  15772. return dstArray;
  15773. }
  15774. }
  15775. function WebGLCubeMaps(renderer) {
  15776. var cubemaps = new WeakMap();
  15777. function mapTextureMapping(texture, mapping) {
  15778. if (mapping === EquirectangularReflectionMapping) {
  15779. texture.mapping = CubeReflectionMapping;
  15780. } else if (mapping === EquirectangularRefractionMapping) {
  15781. texture.mapping = CubeRefractionMapping;
  15782. }
  15783. return texture;
  15784. }
  15785. function get(texture) {
  15786. if (texture && texture.isTexture) {
  15787. var mapping = texture.mapping;
  15788. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  15789. if (cubemaps.has(texture)) {
  15790. var cubemap = cubemaps.get(texture).texture;
  15791. return mapTextureMapping(cubemap, texture.mapping);
  15792. } else {
  15793. var image = texture.image;
  15794. if (image && image.height > 0) {
  15795. var currentRenderList = renderer.getRenderList();
  15796. var currentRenderTarget = renderer.getRenderTarget();
  15797. var renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  15798. renderTarget.fromEquirectangularTexture(renderer, texture);
  15799. cubemaps.set(texture, renderTarget);
  15800. renderer.setRenderTarget(currentRenderTarget);
  15801. renderer.setRenderList(currentRenderList);
  15802. texture.addEventListener('dispose', onTextureDispose);
  15803. return mapTextureMapping(renderTarget.texture, texture.mapping);
  15804. } else {
  15805. // image not yet ready. try the conversion next frame
  15806. return null;
  15807. }
  15808. }
  15809. }
  15810. }
  15811. return texture;
  15812. }
  15813. function onTextureDispose(event) {
  15814. var texture = event.target;
  15815. texture.removeEventListener('dispose', onTextureDispose);
  15816. var cubemap = cubemaps.get(texture);
  15817. if (cubemap !== undefined) {
  15818. cubemaps.delete(texture);
  15819. cubemap.dispose();
  15820. }
  15821. }
  15822. function dispose() {
  15823. cubemaps = new WeakMap();
  15824. }
  15825. return {
  15826. get: get,
  15827. dispose: dispose
  15828. };
  15829. }
  15830. function WebGLExtensions(gl) {
  15831. var extensions = {};
  15832. function getExtension(name) {
  15833. if (extensions[name] !== undefined) {
  15834. return extensions[name];
  15835. }
  15836. var extension;
  15837. switch (name) {
  15838. case 'WEBGL_depth_texture':
  15839. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  15840. break;
  15841. case 'EXT_texture_filter_anisotropic':
  15842. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  15843. break;
  15844. case 'WEBGL_compressed_texture_s3tc':
  15845. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  15846. break;
  15847. case 'WEBGL_compressed_texture_pvrtc':
  15848. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  15849. break;
  15850. default:
  15851. extension = gl.getExtension(name);
  15852. }
  15853. extensions[name] = extension;
  15854. return extension;
  15855. }
  15856. return {
  15857. has: function has(name) {
  15858. return getExtension(name) !== null;
  15859. },
  15860. init: function init(capabilities) {
  15861. if (capabilities.isWebGL2) {
  15862. getExtension('EXT_color_buffer_float');
  15863. } else {
  15864. getExtension('WEBGL_depth_texture');
  15865. getExtension('OES_texture_float');
  15866. getExtension('OES_texture_half_float');
  15867. getExtension('OES_texture_half_float_linear');
  15868. getExtension('OES_standard_derivatives');
  15869. getExtension('OES_element_index_uint');
  15870. getExtension('OES_vertex_array_object');
  15871. getExtension('ANGLE_instanced_arrays');
  15872. }
  15873. getExtension('OES_texture_float_linear');
  15874. getExtension('EXT_color_buffer_half_float');
  15875. },
  15876. get: function get(name) {
  15877. var extension = getExtension(name);
  15878. if (extension === null) {
  15879. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  15880. }
  15881. return extension;
  15882. }
  15883. };
  15884. }
  15885. function WebGLGeometries(gl, attributes, info, bindingStates) {
  15886. var geometries = {};
  15887. var wireframeAttributes = new WeakMap();
  15888. function onGeometryDispose(event) {
  15889. var geometry = event.target;
  15890. if (geometry.index !== null) {
  15891. attributes.remove(geometry.index);
  15892. }
  15893. for (var name in geometry.attributes) {
  15894. attributes.remove(geometry.attributes[name]);
  15895. }
  15896. geometry.removeEventListener('dispose', onGeometryDispose);
  15897. delete geometries[geometry.id];
  15898. var attribute = wireframeAttributes.get(geometry);
  15899. if (attribute) {
  15900. attributes.remove(attribute);
  15901. wireframeAttributes.delete(geometry);
  15902. }
  15903. bindingStates.releaseStatesOfGeometry(geometry);
  15904. if (geometry.isInstancedBufferGeometry === true) {
  15905. delete geometry._maxInstanceCount;
  15906. } //
  15907. info.memory.geometries--;
  15908. }
  15909. function get(object, geometry) {
  15910. if (geometries[geometry.id] === true) return geometry;
  15911. geometry.addEventListener('dispose', onGeometryDispose);
  15912. geometries[geometry.id] = true;
  15913. info.memory.geometries++;
  15914. return geometry;
  15915. }
  15916. function update(geometry) {
  15917. var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  15918. for (var name in geometryAttributes) {
  15919. attributes.update(geometryAttributes[name], 34962);
  15920. } // morph targets
  15921. var morphAttributes = geometry.morphAttributes;
  15922. for (var _name in morphAttributes) {
  15923. var array = morphAttributes[_name];
  15924. for (var i = 0, l = array.length; i < l; i++) {
  15925. attributes.update(array[i], 34962);
  15926. }
  15927. }
  15928. }
  15929. function updateWireframeAttribute(geometry) {
  15930. var indices = [];
  15931. var geometryIndex = geometry.index;
  15932. var geometryPosition = geometry.attributes.position;
  15933. var version = 0;
  15934. if (geometryIndex !== null) {
  15935. var array = geometryIndex.array;
  15936. version = geometryIndex.version;
  15937. for (var i = 0, l = array.length; i < l; i += 3) {
  15938. var a = array[i + 0];
  15939. var b = array[i + 1];
  15940. var c = array[i + 2];
  15941. indices.push(a, b, b, c, c, a);
  15942. }
  15943. } else {
  15944. var _array = geometryPosition.array;
  15945. version = geometryPosition.version;
  15946. for (var _i = 0, _l = _array.length / 3 - 1; _i < _l; _i += 3) {
  15947. var _a = _i + 0;
  15948. var _b = _i + 1;
  15949. var _c = _i + 2;
  15950. indices.push(_a, _b, _b, _c, _c, _a);
  15951. }
  15952. }
  15953. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  15954. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  15955. //
  15956. var previousAttribute = wireframeAttributes.get(geometry);
  15957. if (previousAttribute) attributes.remove(previousAttribute); //
  15958. wireframeAttributes.set(geometry, attribute);
  15959. }
  15960. function getWireframeAttribute(geometry) {
  15961. var currentAttribute = wireframeAttributes.get(geometry);
  15962. if (currentAttribute) {
  15963. var geometryIndex = geometry.index;
  15964. if (geometryIndex !== null) {
  15965. // if the attribute is obsolete, create a new one
  15966. if (currentAttribute.version < geometryIndex.version) {
  15967. updateWireframeAttribute(geometry);
  15968. }
  15969. }
  15970. } else {
  15971. updateWireframeAttribute(geometry);
  15972. }
  15973. return wireframeAttributes.get(geometry);
  15974. }
  15975. return {
  15976. get: get,
  15977. update: update,
  15978. getWireframeAttribute: getWireframeAttribute
  15979. };
  15980. }
  15981. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  15982. var isWebGL2 = capabilities.isWebGL2;
  15983. var mode;
  15984. function setMode(value) {
  15985. mode = value;
  15986. }
  15987. var type, bytesPerElement;
  15988. function setIndex(value) {
  15989. type = value.type;
  15990. bytesPerElement = value.bytesPerElement;
  15991. }
  15992. function render(start, count) {
  15993. gl.drawElements(mode, count, type, start * bytesPerElement);
  15994. info.update(count, mode, 1);
  15995. }
  15996. function renderInstances(start, count, primcount) {
  15997. if (primcount === 0) return;
  15998. var extension, methodName;
  15999. if (isWebGL2) {
  16000. extension = gl;
  16001. methodName = 'drawElementsInstanced';
  16002. } else {
  16003. extension = extensions.get('ANGLE_instanced_arrays');
  16004. methodName = 'drawElementsInstancedANGLE';
  16005. if (extension === null) {
  16006. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  16007. return;
  16008. }
  16009. }
  16010. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  16011. info.update(count, mode, primcount);
  16012. } //
  16013. this.setMode = setMode;
  16014. this.setIndex = setIndex;
  16015. this.render = render;
  16016. this.renderInstances = renderInstances;
  16017. }
  16018. function WebGLInfo(gl) {
  16019. var memory = {
  16020. geometries: 0,
  16021. textures: 0
  16022. };
  16023. var render = {
  16024. frame: 0,
  16025. calls: 0,
  16026. triangles: 0,
  16027. points: 0,
  16028. lines: 0
  16029. };
  16030. function update(count, mode, instanceCount) {
  16031. render.calls++;
  16032. switch (mode) {
  16033. case 4:
  16034. render.triangles += instanceCount * (count / 3);
  16035. break;
  16036. case 1:
  16037. render.lines += instanceCount * (count / 2);
  16038. break;
  16039. case 3:
  16040. render.lines += instanceCount * (count - 1);
  16041. break;
  16042. case 2:
  16043. render.lines += instanceCount * count;
  16044. break;
  16045. case 0:
  16046. render.points += instanceCount * count;
  16047. break;
  16048. default:
  16049. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  16050. break;
  16051. }
  16052. }
  16053. function reset() {
  16054. render.frame++;
  16055. render.calls = 0;
  16056. render.triangles = 0;
  16057. render.points = 0;
  16058. render.lines = 0;
  16059. }
  16060. return {
  16061. memory: memory,
  16062. render: render,
  16063. programs: null,
  16064. autoReset: true,
  16065. reset: reset,
  16066. update: update
  16067. };
  16068. }
  16069. function numericalSort(a, b) {
  16070. return a[0] - b[0];
  16071. }
  16072. function absNumericalSort(a, b) {
  16073. return Math.abs(b[1]) - Math.abs(a[1]);
  16074. }
  16075. function WebGLMorphtargets(gl) {
  16076. var influencesList = {};
  16077. var morphInfluences = new Float32Array(8);
  16078. var workInfluences = [];
  16079. for (var i = 0; i < 8; i++) {
  16080. workInfluences[i] = [i, 0];
  16081. }
  16082. function update(object, geometry, material, program) {
  16083. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  16084. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  16085. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  16086. var influences = influencesList[geometry.id];
  16087. if (influences === undefined) {
  16088. // initialise list
  16089. influences = [];
  16090. for (var _i = 0; _i < length; _i++) {
  16091. influences[_i] = [_i, 0];
  16092. }
  16093. influencesList[geometry.id] = influences;
  16094. } // Collect influences
  16095. for (var _i2 = 0; _i2 < length; _i2++) {
  16096. var influence = influences[_i2];
  16097. influence[0] = _i2;
  16098. influence[1] = objectInfluences[_i2];
  16099. }
  16100. influences.sort(absNumericalSort);
  16101. for (var _i3 = 0; _i3 < 8; _i3++) {
  16102. if (_i3 < length && influences[_i3][1]) {
  16103. workInfluences[_i3][0] = influences[_i3][0];
  16104. workInfluences[_i3][1] = influences[_i3][1];
  16105. } else {
  16106. workInfluences[_i3][0] = Number.MAX_SAFE_INTEGER;
  16107. workInfluences[_i3][1] = 0;
  16108. }
  16109. }
  16110. workInfluences.sort(numericalSort);
  16111. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  16112. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  16113. var morphInfluencesSum = 0;
  16114. for (var _i4 = 0; _i4 < 8; _i4++) {
  16115. var _influence = workInfluences[_i4];
  16116. var index = _influence[0];
  16117. var value = _influence[1];
  16118. if (index !== Number.MAX_SAFE_INTEGER && value) {
  16119. if (morphTargets && geometry.getAttribute('morphTarget' + _i4) !== morphTargets[index]) {
  16120. geometry.setAttribute('morphTarget' + _i4, morphTargets[index]);
  16121. }
  16122. if (morphNormals && geometry.getAttribute('morphNormal' + _i4) !== morphNormals[index]) {
  16123. geometry.setAttribute('morphNormal' + _i4, morphNormals[index]);
  16124. }
  16125. morphInfluences[_i4] = value;
  16126. morphInfluencesSum += value;
  16127. } else {
  16128. if (morphTargets && geometry.hasAttribute('morphTarget' + _i4) === true) {
  16129. geometry.deleteAttribute('morphTarget' + _i4);
  16130. }
  16131. if (morphNormals && geometry.hasAttribute('morphNormal' + _i4) === true) {
  16132. geometry.deleteAttribute('morphNormal' + _i4);
  16133. }
  16134. morphInfluences[_i4] = 0;
  16135. }
  16136. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  16137. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  16138. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  16139. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  16140. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  16141. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  16142. }
  16143. return {
  16144. update: update
  16145. };
  16146. }
  16147. function WebGLObjects(gl, geometries, attributes, info) {
  16148. var updateMap = new WeakMap();
  16149. function update(object) {
  16150. var frame = info.render.frame;
  16151. var geometry = object.geometry;
  16152. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  16153. if (updateMap.get(buffergeometry) !== frame) {
  16154. geometries.update(buffergeometry);
  16155. updateMap.set(buffergeometry, frame);
  16156. }
  16157. if (object.isInstancedMesh) {
  16158. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  16159. object.addEventListener('dispose', onInstancedMeshDispose);
  16160. }
  16161. attributes.update(object.instanceMatrix, 34962);
  16162. if (object.instanceColor !== null) {
  16163. attributes.update(object.instanceColor, 34962);
  16164. }
  16165. }
  16166. return buffergeometry;
  16167. }
  16168. function dispose() {
  16169. updateMap = new WeakMap();
  16170. }
  16171. function onInstancedMeshDispose(event) {
  16172. var instancedMesh = event.target;
  16173. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  16174. attributes.remove(instancedMesh.instanceMatrix);
  16175. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  16176. }
  16177. return {
  16178. update: update,
  16179. dispose: dispose
  16180. };
  16181. }
  16182. function DataTexture2DArray(data, width, height, depth) {
  16183. if (data === void 0) {
  16184. data = null;
  16185. }
  16186. if (width === void 0) {
  16187. width = 1;
  16188. }
  16189. if (height === void 0) {
  16190. height = 1;
  16191. }
  16192. if (depth === void 0) {
  16193. depth = 1;
  16194. }
  16195. Texture.call(this, null);
  16196. this.image = {
  16197. data: data,
  16198. width: width,
  16199. height: height,
  16200. depth: depth
  16201. };
  16202. this.magFilter = NearestFilter;
  16203. this.minFilter = NearestFilter;
  16204. this.wrapR = ClampToEdgeWrapping;
  16205. this.generateMipmaps = false;
  16206. this.flipY = false;
  16207. this.needsUpdate = true;
  16208. }
  16209. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  16210. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  16211. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  16212. function DataTexture3D(data, width, height, depth) {
  16213. if (data === void 0) {
  16214. data = null;
  16215. }
  16216. if (width === void 0) {
  16217. width = 1;
  16218. }
  16219. if (height === void 0) {
  16220. height = 1;
  16221. }
  16222. if (depth === void 0) {
  16223. depth = 1;
  16224. }
  16225. // We're going to add .setXXX() methods for setting properties later.
  16226. // Users can still set in DataTexture3D directly.
  16227. //
  16228. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  16229. // texture.anisotropy = 16;
  16230. //
  16231. // See #14839
  16232. Texture.call(this, null);
  16233. this.image = {
  16234. data: data,
  16235. width: width,
  16236. height: height,
  16237. depth: depth
  16238. };
  16239. this.magFilter = NearestFilter;
  16240. this.minFilter = NearestFilter;
  16241. this.wrapR = ClampToEdgeWrapping;
  16242. this.generateMipmaps = false;
  16243. this.flipY = false;
  16244. this.needsUpdate = true;
  16245. }
  16246. DataTexture3D.prototype = Object.create(Texture.prototype);
  16247. DataTexture3D.prototype.constructor = DataTexture3D;
  16248. DataTexture3D.prototype.isDataTexture3D = true;
  16249. /**
  16250. * Uniforms of a program.
  16251. * Those form a tree structure with a special top-level container for the root,
  16252. * which you get by calling 'new WebGLUniforms( gl, program )'.
  16253. *
  16254. *
  16255. * Properties of inner nodes including the top-level container:
  16256. *
  16257. * .seq - array of nested uniforms
  16258. * .map - nested uniforms by name
  16259. *
  16260. *
  16261. * Methods of all nodes except the top-level container:
  16262. *
  16263. * .setValue( gl, value, [textures] )
  16264. *
  16265. * uploads a uniform value(s)
  16266. * the 'textures' parameter is needed for sampler uniforms
  16267. *
  16268. *
  16269. * Static methods of the top-level container (textures factorizations):
  16270. *
  16271. * .upload( gl, seq, values, textures )
  16272. *
  16273. * sets uniforms in 'seq' to 'values[id].value'
  16274. *
  16275. * .seqWithValue( seq, values ) : filteredSeq
  16276. *
  16277. * filters 'seq' entries with corresponding entry in values
  16278. *
  16279. *
  16280. * Methods of the top-level container (textures factorizations):
  16281. *
  16282. * .setValue( gl, name, value, textures )
  16283. *
  16284. * sets uniform with name 'name' to 'value'
  16285. *
  16286. * .setOptional( gl, obj, prop )
  16287. *
  16288. * like .set for an optional property of the object
  16289. *
  16290. */
  16291. var emptyTexture = new Texture();
  16292. var emptyTexture2dArray = new DataTexture2DArray();
  16293. var emptyTexture3d = new DataTexture3D();
  16294. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  16295. // Array Caches (provide typed arrays for temporary by size)
  16296. var arrayCacheF32 = [];
  16297. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  16298. var mat4array = new Float32Array(16);
  16299. var mat3array = new Float32Array(9);
  16300. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  16301. function flatten(array, nBlocks, blockSize) {
  16302. var firstElem = array[0];
  16303. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  16304. // see http://jacksondunstan.com/articles/983
  16305. var n = nBlocks * blockSize;
  16306. var r = arrayCacheF32[n];
  16307. if (r === undefined) {
  16308. r = new Float32Array(n);
  16309. arrayCacheF32[n] = r;
  16310. }
  16311. if (nBlocks !== 0) {
  16312. firstElem.toArray(r, 0);
  16313. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  16314. offset += blockSize;
  16315. array[i].toArray(r, offset);
  16316. }
  16317. }
  16318. return r;
  16319. }
  16320. function arraysEqual(a, b) {
  16321. if (a.length !== b.length) return false;
  16322. for (var i = 0, l = a.length; i < l; i++) {
  16323. if (a[i] !== b[i]) return false;
  16324. }
  16325. return true;
  16326. }
  16327. function copyArray(a, b) {
  16328. for (var i = 0, l = b.length; i < l; i++) {
  16329. a[i] = b[i];
  16330. }
  16331. } // Texture unit allocation
  16332. function allocTexUnits(textures, n) {
  16333. var r = arrayCacheI32[n];
  16334. if (r === undefined) {
  16335. r = new Int32Array(n);
  16336. arrayCacheI32[n] = r;
  16337. }
  16338. for (var i = 0; i !== n; ++i) {
  16339. r[i] = textures.allocateTextureUnit();
  16340. }
  16341. return r;
  16342. } // --- Setters ---
  16343. // Note: Defining these methods externally, because they come in a bunch
  16344. // and this way their names minify.
  16345. // Single scalar
  16346. function setValueV1f(gl, v) {
  16347. var cache = this.cache;
  16348. if (cache[0] === v) return;
  16349. gl.uniform1f(this.addr, v);
  16350. cache[0] = v;
  16351. } // Single float vector (from flat array or THREE.VectorN)
  16352. function setValueV2f(gl, v) {
  16353. var cache = this.cache;
  16354. if (v.x !== undefined) {
  16355. if (cache[0] !== v.x || cache[1] !== v.y) {
  16356. gl.uniform2f(this.addr, v.x, v.y);
  16357. cache[0] = v.x;
  16358. cache[1] = v.y;
  16359. }
  16360. } else {
  16361. if (arraysEqual(cache, v)) return;
  16362. gl.uniform2fv(this.addr, v);
  16363. copyArray(cache, v);
  16364. }
  16365. }
  16366. function setValueV3f(gl, v) {
  16367. var cache = this.cache;
  16368. if (v.x !== undefined) {
  16369. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  16370. gl.uniform3f(this.addr, v.x, v.y, v.z);
  16371. cache[0] = v.x;
  16372. cache[1] = v.y;
  16373. cache[2] = v.z;
  16374. }
  16375. } else if (v.r !== undefined) {
  16376. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  16377. gl.uniform3f(this.addr, v.r, v.g, v.b);
  16378. cache[0] = v.r;
  16379. cache[1] = v.g;
  16380. cache[2] = v.b;
  16381. }
  16382. } else {
  16383. if (arraysEqual(cache, v)) return;
  16384. gl.uniform3fv(this.addr, v);
  16385. copyArray(cache, v);
  16386. }
  16387. }
  16388. function setValueV4f(gl, v) {
  16389. var cache = this.cache;
  16390. if (v.x !== undefined) {
  16391. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  16392. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  16393. cache[0] = v.x;
  16394. cache[1] = v.y;
  16395. cache[2] = v.z;
  16396. cache[3] = v.w;
  16397. }
  16398. } else {
  16399. if (arraysEqual(cache, v)) return;
  16400. gl.uniform4fv(this.addr, v);
  16401. copyArray(cache, v);
  16402. }
  16403. } // Single matrix (from flat array or MatrixN)
  16404. function setValueM2(gl, v) {
  16405. var cache = this.cache;
  16406. var elements = v.elements;
  16407. if (elements === undefined) {
  16408. if (arraysEqual(cache, v)) return;
  16409. gl.uniformMatrix2fv(this.addr, false, v);
  16410. copyArray(cache, v);
  16411. } else {
  16412. if (arraysEqual(cache, elements)) return;
  16413. mat2array.set(elements);
  16414. gl.uniformMatrix2fv(this.addr, false, mat2array);
  16415. copyArray(cache, elements);
  16416. }
  16417. }
  16418. function setValueM3(gl, v) {
  16419. var cache = this.cache;
  16420. var elements = v.elements;
  16421. if (elements === undefined) {
  16422. if (arraysEqual(cache, v)) return;
  16423. gl.uniformMatrix3fv(this.addr, false, v);
  16424. copyArray(cache, v);
  16425. } else {
  16426. if (arraysEqual(cache, elements)) return;
  16427. mat3array.set(elements);
  16428. gl.uniformMatrix3fv(this.addr, false, mat3array);
  16429. copyArray(cache, elements);
  16430. }
  16431. }
  16432. function setValueM4(gl, v) {
  16433. var cache = this.cache;
  16434. var elements = v.elements;
  16435. if (elements === undefined) {
  16436. if (arraysEqual(cache, v)) return;
  16437. gl.uniformMatrix4fv(this.addr, false, v);
  16438. copyArray(cache, v);
  16439. } else {
  16440. if (arraysEqual(cache, elements)) return;
  16441. mat4array.set(elements);
  16442. gl.uniformMatrix4fv(this.addr, false, mat4array);
  16443. copyArray(cache, elements);
  16444. }
  16445. } // Single texture (2D / Cube)
  16446. function setValueT1(gl, v, textures) {
  16447. var cache = this.cache;
  16448. var unit = textures.allocateTextureUnit();
  16449. if (cache[0] !== unit) {
  16450. gl.uniform1i(this.addr, unit);
  16451. cache[0] = unit;
  16452. }
  16453. textures.safeSetTexture2D(v || emptyTexture, unit);
  16454. }
  16455. function setValueT2DArray1(gl, v, textures) {
  16456. var cache = this.cache;
  16457. var unit = textures.allocateTextureUnit();
  16458. if (cache[0] !== unit) {
  16459. gl.uniform1i(this.addr, unit);
  16460. cache[0] = unit;
  16461. }
  16462. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  16463. }
  16464. function setValueT3D1(gl, v, textures) {
  16465. var cache = this.cache;
  16466. var unit = textures.allocateTextureUnit();
  16467. if (cache[0] !== unit) {
  16468. gl.uniform1i(this.addr, unit);
  16469. cache[0] = unit;
  16470. }
  16471. textures.setTexture3D(v || emptyTexture3d, unit);
  16472. }
  16473. function setValueT6(gl, v, textures) {
  16474. var cache = this.cache;
  16475. var unit = textures.allocateTextureUnit();
  16476. if (cache[0] !== unit) {
  16477. gl.uniform1i(this.addr, unit);
  16478. cache[0] = unit;
  16479. }
  16480. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  16481. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16482. function setValueV1i(gl, v) {
  16483. var cache = this.cache;
  16484. if (cache[0] === v) return;
  16485. gl.uniform1i(this.addr, v);
  16486. cache[0] = v;
  16487. }
  16488. function setValueV2i(gl, v) {
  16489. var cache = this.cache;
  16490. if (arraysEqual(cache, v)) return;
  16491. gl.uniform2iv(this.addr, v);
  16492. copyArray(cache, v);
  16493. }
  16494. function setValueV3i(gl, v) {
  16495. var cache = this.cache;
  16496. if (arraysEqual(cache, v)) return;
  16497. gl.uniform3iv(this.addr, v);
  16498. copyArray(cache, v);
  16499. }
  16500. function setValueV4i(gl, v) {
  16501. var cache = this.cache;
  16502. if (arraysEqual(cache, v)) return;
  16503. gl.uniform4iv(this.addr, v);
  16504. copyArray(cache, v);
  16505. } // uint
  16506. function setValueV1ui(gl, v) {
  16507. var cache = this.cache;
  16508. if (cache[0] === v) return;
  16509. gl.uniform1ui(this.addr, v);
  16510. cache[0] = v;
  16511. } // Helper to pick the right setter for the singular case
  16512. function getSingularSetter(type) {
  16513. switch (type) {
  16514. case 0x1406:
  16515. return setValueV1f;
  16516. // FLOAT
  16517. case 0x8b50:
  16518. return setValueV2f;
  16519. // _VEC2
  16520. case 0x8b51:
  16521. return setValueV3f;
  16522. // _VEC3
  16523. case 0x8b52:
  16524. return setValueV4f;
  16525. // _VEC4
  16526. case 0x8b5a:
  16527. return setValueM2;
  16528. // _MAT2
  16529. case 0x8b5b:
  16530. return setValueM3;
  16531. // _MAT3
  16532. case 0x8b5c:
  16533. return setValueM4;
  16534. // _MAT4
  16535. case 0x1404:
  16536. case 0x8b56:
  16537. return setValueV1i;
  16538. // INT, BOOL
  16539. case 0x8b53:
  16540. case 0x8b57:
  16541. return setValueV2i;
  16542. // _VEC2
  16543. case 0x8b54:
  16544. case 0x8b58:
  16545. return setValueV3i;
  16546. // _VEC3
  16547. case 0x8b55:
  16548. case 0x8b59:
  16549. return setValueV4i;
  16550. // _VEC4
  16551. case 0x1405:
  16552. return setValueV1ui;
  16553. // UINT
  16554. case 0x8b5e: // SAMPLER_2D
  16555. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16556. case 0x8dca: // INT_SAMPLER_2D
  16557. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16558. case 0x8b62:
  16559. // SAMPLER_2D_SHADOW
  16560. return setValueT1;
  16561. case 0x8b5f: // SAMPLER_3D
  16562. case 0x8dcb: // INT_SAMPLER_3D
  16563. case 0x8dd3:
  16564. // UNSIGNED_INT_SAMPLER_3D
  16565. return setValueT3D1;
  16566. case 0x8b60: // SAMPLER_CUBE
  16567. case 0x8dcc: // INT_SAMPLER_CUBE
  16568. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16569. case 0x8dc5:
  16570. // SAMPLER_CUBE_SHADOW
  16571. return setValueT6;
  16572. case 0x8dc1: // SAMPLER_2D_ARRAY
  16573. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  16574. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  16575. case 0x8dc4:
  16576. // SAMPLER_2D_ARRAY_SHADOW
  16577. return setValueT2DArray1;
  16578. }
  16579. } // Array of scalars
  16580. function setValueV1fArray(gl, v) {
  16581. gl.uniform1fv(this.addr, v);
  16582. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16583. function setValueV1iArray(gl, v) {
  16584. gl.uniform1iv(this.addr, v);
  16585. }
  16586. function setValueV2iArray(gl, v) {
  16587. gl.uniform2iv(this.addr, v);
  16588. }
  16589. function setValueV3iArray(gl, v) {
  16590. gl.uniform3iv(this.addr, v);
  16591. }
  16592. function setValueV4iArray(gl, v) {
  16593. gl.uniform4iv(this.addr, v);
  16594. } // Array of vectors (flat or from THREE classes)
  16595. function setValueV2fArray(gl, v) {
  16596. var data = flatten(v, this.size, 2);
  16597. gl.uniform2fv(this.addr, data);
  16598. }
  16599. function setValueV3fArray(gl, v) {
  16600. var data = flatten(v, this.size, 3);
  16601. gl.uniform3fv(this.addr, data);
  16602. }
  16603. function setValueV4fArray(gl, v) {
  16604. var data = flatten(v, this.size, 4);
  16605. gl.uniform4fv(this.addr, data);
  16606. } // Array of matrices (flat or from THREE clases)
  16607. function setValueM2Array(gl, v) {
  16608. var data = flatten(v, this.size, 4);
  16609. gl.uniformMatrix2fv(this.addr, false, data);
  16610. }
  16611. function setValueM3Array(gl, v) {
  16612. var data = flatten(v, this.size, 9);
  16613. gl.uniformMatrix3fv(this.addr, false, data);
  16614. }
  16615. function setValueM4Array(gl, v) {
  16616. var data = flatten(v, this.size, 16);
  16617. gl.uniformMatrix4fv(this.addr, false, data);
  16618. } // Array of textures (2D / Cube)
  16619. function setValueT1Array(gl, v, textures) {
  16620. var n = v.length;
  16621. var units = allocTexUnits(textures, n);
  16622. gl.uniform1iv(this.addr, units);
  16623. for (var i = 0; i !== n; ++i) {
  16624. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  16625. }
  16626. }
  16627. function setValueT6Array(gl, v, textures) {
  16628. var n = v.length;
  16629. var units = allocTexUnits(textures, n);
  16630. gl.uniform1iv(this.addr, units);
  16631. for (var i = 0; i !== n; ++i) {
  16632. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  16633. }
  16634. } // Helper to pick the right setter for a pure (bottom-level) array
  16635. function getPureArraySetter(type) {
  16636. switch (type) {
  16637. case 0x1406:
  16638. return setValueV1fArray;
  16639. // FLOAT
  16640. case 0x8b50:
  16641. return setValueV2fArray;
  16642. // _VEC2
  16643. case 0x8b51:
  16644. return setValueV3fArray;
  16645. // _VEC3
  16646. case 0x8b52:
  16647. return setValueV4fArray;
  16648. // _VEC4
  16649. case 0x8b5a:
  16650. return setValueM2Array;
  16651. // _MAT2
  16652. case 0x8b5b:
  16653. return setValueM3Array;
  16654. // _MAT3
  16655. case 0x8b5c:
  16656. return setValueM4Array;
  16657. // _MAT4
  16658. case 0x1404:
  16659. case 0x8b56:
  16660. return setValueV1iArray;
  16661. // INT, BOOL
  16662. case 0x8b53:
  16663. case 0x8b57:
  16664. return setValueV2iArray;
  16665. // _VEC2
  16666. case 0x8b54:
  16667. case 0x8b58:
  16668. return setValueV3iArray;
  16669. // _VEC3
  16670. case 0x8b55:
  16671. case 0x8b59:
  16672. return setValueV4iArray;
  16673. // _VEC4
  16674. case 0x8b5e: // SAMPLER_2D
  16675. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16676. case 0x8dca: // INT_SAMPLER_2D
  16677. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16678. case 0x8b62:
  16679. // SAMPLER_2D_SHADOW
  16680. return setValueT1Array;
  16681. case 0x8b60: // SAMPLER_CUBE
  16682. case 0x8dcc: // INT_SAMPLER_CUBE
  16683. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16684. case 0x8dc5:
  16685. // SAMPLER_CUBE_SHADOW
  16686. return setValueT6Array;
  16687. }
  16688. } // --- Uniform Classes ---
  16689. function SingleUniform(id, activeInfo, addr) {
  16690. this.id = id;
  16691. this.addr = addr;
  16692. this.cache = [];
  16693. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16694. }
  16695. function PureArrayUniform(id, activeInfo, addr) {
  16696. this.id = id;
  16697. this.addr = addr;
  16698. this.cache = [];
  16699. this.size = activeInfo.size;
  16700. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16701. }
  16702. PureArrayUniform.prototype.updateCache = function (data) {
  16703. var cache = this.cache;
  16704. if (data instanceof Float32Array && cache.length !== data.length) {
  16705. this.cache = new Float32Array(data.length);
  16706. }
  16707. copyArray(cache, data);
  16708. };
  16709. function StructuredUniform(id) {
  16710. this.id = id;
  16711. this.seq = [];
  16712. this.map = {};
  16713. }
  16714. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  16715. var seq = this.seq;
  16716. for (var i = 0, n = seq.length; i !== n; ++i) {
  16717. var u = seq[i];
  16718. u.setValue(gl, value[u.id], textures);
  16719. }
  16720. }; // --- Top-level ---
  16721. // Parser - builds up the property tree from the path strings
  16722. var RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  16723. // - the identifier (member name or array index)
  16724. // - followed by an optional right bracket (found when array index)
  16725. // - followed by an optional left bracket or dot (type of subscript)
  16726. //
  16727. // Note: These portions can be read in a non-overlapping fashion and
  16728. // allow straightforward parsing of the hierarchy that WebGL encodes
  16729. // in the uniform names.
  16730. function addUniform(container, uniformObject) {
  16731. container.seq.push(uniformObject);
  16732. container.map[uniformObject.id] = uniformObject;
  16733. }
  16734. function parseUniform(activeInfo, addr, container) {
  16735. var path = activeInfo.name,
  16736. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  16737. RePathPart.lastIndex = 0;
  16738. while (true) {
  16739. var match = RePathPart.exec(path),
  16740. matchEnd = RePathPart.lastIndex;
  16741. var id = match[1];
  16742. var idIsIndex = match[2] === ']',
  16743. subscript = match[3];
  16744. if (idIsIndex) id = id | 0; // convert to integer
  16745. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  16746. // bare name or "pure" bottom-level array "[0]" suffix
  16747. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  16748. break;
  16749. } else {
  16750. // step into inner node / create it in case it doesn't exist
  16751. var map = container.map;
  16752. var next = map[id];
  16753. if (next === undefined) {
  16754. next = new StructuredUniform(id);
  16755. addUniform(container, next);
  16756. }
  16757. container = next;
  16758. }
  16759. }
  16760. } // Root Container
  16761. function WebGLUniforms(gl, program) {
  16762. this.seq = [];
  16763. this.map = {};
  16764. var n = gl.getProgramParameter(program, 35718);
  16765. for (var i = 0; i < n; ++i) {
  16766. var info = gl.getActiveUniform(program, i),
  16767. addr = gl.getUniformLocation(program, info.name);
  16768. parseUniform(info, addr, this);
  16769. }
  16770. }
  16771. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  16772. var u = this.map[name];
  16773. if (u !== undefined) u.setValue(gl, value, textures);
  16774. };
  16775. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  16776. var v = object[name];
  16777. if (v !== undefined) this.setValue(gl, name, v);
  16778. }; // Static interface
  16779. WebGLUniforms.upload = function (gl, seq, values, textures) {
  16780. for (var i = 0, n = seq.length; i !== n; ++i) {
  16781. var u = seq[i],
  16782. v = values[u.id];
  16783. if (v.needsUpdate !== false) {
  16784. // note: always updating when .needsUpdate is undefined
  16785. u.setValue(gl, v.value, textures);
  16786. }
  16787. }
  16788. };
  16789. WebGLUniforms.seqWithValue = function (seq, values) {
  16790. var r = [];
  16791. for (var i = 0, n = seq.length; i !== n; ++i) {
  16792. var u = seq[i];
  16793. if (u.id in values) r.push(u);
  16794. }
  16795. return r;
  16796. };
  16797. function WebGLShader(gl, type, string) {
  16798. var shader = gl.createShader(type);
  16799. gl.shaderSource(shader, string);
  16800. gl.compileShader(shader);
  16801. return shader;
  16802. }
  16803. var programIdCount = 0;
  16804. function addLineNumbers(string) {
  16805. var lines = string.split('\n');
  16806. for (var i = 0; i < lines.length; i++) {
  16807. lines[i] = i + 1 + ': ' + lines[i];
  16808. }
  16809. return lines.join('\n');
  16810. }
  16811. function getEncodingComponents(encoding) {
  16812. switch (encoding) {
  16813. case LinearEncoding:
  16814. return ['Linear', '( value )'];
  16815. case sRGBEncoding:
  16816. return ['sRGB', '( value )'];
  16817. case RGBEEncoding:
  16818. return ['RGBE', '( value )'];
  16819. case RGBM7Encoding:
  16820. return ['RGBM', '( value, 7.0 )'];
  16821. case RGBM16Encoding:
  16822. return ['RGBM', '( value, 16.0 )'];
  16823. case RGBDEncoding:
  16824. return ['RGBD', '( value, 256.0 )'];
  16825. case GammaEncoding:
  16826. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  16827. case LogLuvEncoding:
  16828. return ['LogLuv', '( value )'];
  16829. default:
  16830. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  16831. return ['Linear', '( value )'];
  16832. }
  16833. }
  16834. function getShaderErrors(gl, shader, type) {
  16835. var status = gl.getShaderParameter(shader, 35713);
  16836. var log = gl.getShaderInfoLog(shader).trim();
  16837. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  16838. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16839. var source = gl.getShaderSource(shader);
  16840. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  16841. }
  16842. function getTexelDecodingFunction(functionName, encoding) {
  16843. var components = getEncodingComponents(encoding);
  16844. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  16845. }
  16846. function getTexelEncodingFunction(functionName, encoding) {
  16847. var components = getEncodingComponents(encoding);
  16848. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  16849. }
  16850. function getToneMappingFunction(functionName, toneMapping) {
  16851. var toneMappingName;
  16852. switch (toneMapping) {
  16853. case LinearToneMapping:
  16854. toneMappingName = 'Linear';
  16855. break;
  16856. case ReinhardToneMapping:
  16857. toneMappingName = 'Reinhard';
  16858. break;
  16859. case CineonToneMapping:
  16860. toneMappingName = 'OptimizedCineon';
  16861. break;
  16862. case ACESFilmicToneMapping:
  16863. toneMappingName = 'ACESFilmic';
  16864. break;
  16865. case CustomToneMapping:
  16866. toneMappingName = 'Custom';
  16867. break;
  16868. default:
  16869. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  16870. toneMappingName = 'Linear';
  16871. }
  16872. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16873. }
  16874. function generateExtensions(parameters) {
  16875. 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' : ''];
  16876. return chunks.filter(filterEmptyLine).join('\n');
  16877. }
  16878. function generateDefines(defines) {
  16879. var chunks = [];
  16880. for (var name in defines) {
  16881. var value = defines[name];
  16882. if (value === false) continue;
  16883. chunks.push('#define ' + name + ' ' + value);
  16884. }
  16885. return chunks.join('\n');
  16886. }
  16887. function fetchAttributeLocations(gl, program) {
  16888. var attributes = {};
  16889. var n = gl.getProgramParameter(program, 35721);
  16890. for (var i = 0; i < n; i++) {
  16891. var info = gl.getActiveAttrib(program, i);
  16892. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16893. attributes[name] = gl.getAttribLocation(program, name);
  16894. }
  16895. return attributes;
  16896. }
  16897. function filterEmptyLine(string) {
  16898. return string !== '';
  16899. }
  16900. function replaceLightNums(string, parameters) {
  16901. 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);
  16902. }
  16903. function replaceClippingPlaneNums(string, parameters) {
  16904. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  16905. } // Resolve Includes
  16906. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16907. function resolveIncludes(string) {
  16908. return string.replace(includePattern, includeReplacer);
  16909. }
  16910. function includeReplacer(match, include) {
  16911. var string = ShaderChunk[include];
  16912. if (string === undefined) {
  16913. throw new Error('Can not resolve #include <' + include + '>');
  16914. }
  16915. return resolveIncludes(string);
  16916. } // Unroll Loops
  16917. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16918. 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;
  16919. function unrollLoops(string) {
  16920. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  16921. }
  16922. function deprecatedLoopReplacer(match, start, end, snippet) {
  16923. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  16924. return loopReplacer(match, start, end, snippet);
  16925. }
  16926. function loopReplacer(match, start, end, snippet) {
  16927. var string = '';
  16928. for (var i = parseInt(start); i < parseInt(end); i++) {
  16929. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  16930. }
  16931. return string;
  16932. } //
  16933. function generatePrecision(parameters) {
  16934. var precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  16935. if (parameters.precision === 'highp') {
  16936. precisionstring += '\n#define HIGH_PRECISION';
  16937. } else if (parameters.precision === 'mediump') {
  16938. precisionstring += '\n#define MEDIUM_PRECISION';
  16939. } else if (parameters.precision === 'lowp') {
  16940. precisionstring += '\n#define LOW_PRECISION';
  16941. }
  16942. return precisionstring;
  16943. }
  16944. function generateShadowMapTypeDefine(parameters) {
  16945. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16946. if (parameters.shadowMapType === PCFShadowMap) {
  16947. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16948. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  16949. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16950. } else if (parameters.shadowMapType === VSMShadowMap) {
  16951. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16952. }
  16953. return shadowMapTypeDefine;
  16954. }
  16955. function generateEnvMapTypeDefine(parameters) {
  16956. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16957. if (parameters.envMap) {
  16958. switch (parameters.envMapMode) {
  16959. case CubeReflectionMapping:
  16960. case CubeRefractionMapping:
  16961. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16962. break;
  16963. case CubeUVReflectionMapping:
  16964. case CubeUVRefractionMapping:
  16965. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16966. break;
  16967. }
  16968. }
  16969. return envMapTypeDefine;
  16970. }
  16971. function generateEnvMapModeDefine(parameters) {
  16972. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16973. if (parameters.envMap) {
  16974. switch (parameters.envMapMode) {
  16975. case CubeRefractionMapping:
  16976. case CubeUVRefractionMapping:
  16977. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16978. break;
  16979. }
  16980. }
  16981. return envMapModeDefine;
  16982. }
  16983. function generateEnvMapBlendingDefine(parameters) {
  16984. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16985. if (parameters.envMap) {
  16986. switch (parameters.combine) {
  16987. case MultiplyOperation:
  16988. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16989. break;
  16990. case MixOperation:
  16991. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16992. break;
  16993. case AddOperation:
  16994. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16995. break;
  16996. }
  16997. }
  16998. return envMapBlendingDefine;
  16999. }
  17000. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  17001. var gl = renderer.getContext();
  17002. var defines = parameters.defines;
  17003. var vertexShader = parameters.vertexShader;
  17004. var fragmentShader = parameters.fragmentShader;
  17005. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  17006. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  17007. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  17008. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  17009. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  17010. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  17011. var customDefines = generateDefines(defines);
  17012. var program = gl.createProgram();
  17013. var prefixVertex, prefixFragment;
  17014. var versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  17015. if (parameters.isRawShaderMaterial) {
  17016. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  17017. if (prefixVertex.length > 0) {
  17018. prefixVertex += '\n';
  17019. }
  17020. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  17021. if (prefixFragment.length > 0) {
  17022. prefixFragment += '\n';
  17023. }
  17024. } else {
  17025. 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');
  17026. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  17027. '#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
  17028. 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
  17029. 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');
  17030. }
  17031. vertexShader = resolveIncludes(vertexShader);
  17032. vertexShader = replaceLightNums(vertexShader, parameters);
  17033. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  17034. fragmentShader = resolveIncludes(fragmentShader);
  17035. fragmentShader = replaceLightNums(fragmentShader, parameters);
  17036. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  17037. vertexShader = unrollLoops(vertexShader);
  17038. fragmentShader = unrollLoops(fragmentShader);
  17039. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  17040. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  17041. versionString = '#version 300 es\n';
  17042. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  17043. 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;
  17044. }
  17045. var vertexGlsl = versionString + prefixVertex + vertexShader;
  17046. var fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  17047. // console.log( '*FRAGMENT*', fragmentGlsl );
  17048. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  17049. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  17050. gl.attachShader(program, glVertexShader);
  17051. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  17052. if (parameters.index0AttributeName !== undefined) {
  17053. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  17054. } else if (parameters.morphTargets === true) {
  17055. // programs with morphTargets displace position out of attribute 0
  17056. gl.bindAttribLocation(program, 0, 'position');
  17057. }
  17058. gl.linkProgram(program); // check for link errors
  17059. if (renderer.debug.checkShaderErrors) {
  17060. var programLog = gl.getProgramInfoLog(program).trim();
  17061. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  17062. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  17063. var runnable = true;
  17064. var haveDiagnostics = true;
  17065. if (gl.getProgramParameter(program, 35714) === false) {
  17066. runnable = false;
  17067. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  17068. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  17069. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  17070. } else if (programLog !== '') {
  17071. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  17072. } else if (vertexLog === '' || fragmentLog === '') {
  17073. haveDiagnostics = false;
  17074. }
  17075. if (haveDiagnostics) {
  17076. this.diagnostics = {
  17077. runnable: runnable,
  17078. programLog: programLog,
  17079. vertexShader: {
  17080. log: vertexLog,
  17081. prefix: prefixVertex
  17082. },
  17083. fragmentShader: {
  17084. log: fragmentLog,
  17085. prefix: prefixFragment
  17086. }
  17087. };
  17088. }
  17089. } // Clean up
  17090. // Crashes in iOS9 and iOS10. #18402
  17091. // gl.detachShader( program, glVertexShader );
  17092. // gl.detachShader( program, glFragmentShader );
  17093. gl.deleteShader(glVertexShader);
  17094. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  17095. var cachedUniforms;
  17096. this.getUniforms = function () {
  17097. if (cachedUniforms === undefined) {
  17098. cachedUniforms = new WebGLUniforms(gl, program);
  17099. }
  17100. return cachedUniforms;
  17101. }; // set up caching for attribute locations
  17102. var cachedAttributes;
  17103. this.getAttributes = function () {
  17104. if (cachedAttributes === undefined) {
  17105. cachedAttributes = fetchAttributeLocations(gl, program);
  17106. }
  17107. return cachedAttributes;
  17108. }; // free resource
  17109. this.destroy = function () {
  17110. bindingStates.releaseStatesOfProgram(this);
  17111. gl.deleteProgram(program);
  17112. this.program = undefined;
  17113. }; //
  17114. this.name = parameters.shaderName;
  17115. this.id = programIdCount++;
  17116. this.cacheKey = cacheKey;
  17117. this.usedTimes = 1;
  17118. this.program = program;
  17119. this.vertexShader = glVertexShader;
  17120. this.fragmentShader = glFragmentShader;
  17121. return this;
  17122. }
  17123. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  17124. var programs = [];
  17125. var isWebGL2 = capabilities.isWebGL2;
  17126. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  17127. var floatVertexTextures = capabilities.floatVertexTextures;
  17128. var maxVertexUniforms = capabilities.maxVertexUniforms;
  17129. var vertexTextures = capabilities.vertexTextures;
  17130. var precision = capabilities.precision;
  17131. var shaderIDs = {
  17132. MeshDepthMaterial: 'depth',
  17133. MeshDistanceMaterial: 'distanceRGBA',
  17134. MeshNormalMaterial: 'normal',
  17135. MeshBasicMaterial: 'basic',
  17136. MeshLambertMaterial: 'lambert',
  17137. MeshPhongMaterial: 'phong',
  17138. MeshToonMaterial: 'toon',
  17139. MeshStandardMaterial: 'physical',
  17140. MeshPhysicalMaterial: 'physical',
  17141. MeshMatcapMaterial: 'matcap',
  17142. LineBasicMaterial: 'basic',
  17143. LineDashedMaterial: 'dashed',
  17144. PointsMaterial: 'points',
  17145. ShadowMaterial: 'shadow',
  17146. SpriteMaterial: 'sprite'
  17147. };
  17148. 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'];
  17149. function getMaxBones(object) {
  17150. var skeleton = object.skeleton;
  17151. var bones = skeleton.bones;
  17152. if (floatVertexTextures) {
  17153. return 1024;
  17154. } else {
  17155. // default for when object is not specified
  17156. // ( for example when prebuilding shader to be used with multiple objects )
  17157. //
  17158. // - leave some extra space for other uniforms
  17159. // - limit here is ANGLE's 254 max uniform vectors
  17160. // (up to 54 should be safe)
  17161. var nVertexUniforms = maxVertexUniforms;
  17162. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  17163. var maxBones = Math.min(nVertexMatrices, bones.length);
  17164. if (maxBones < bones.length) {
  17165. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  17166. return 0;
  17167. }
  17168. return maxBones;
  17169. }
  17170. }
  17171. function getTextureEncodingFromMap(map) {
  17172. var encoding;
  17173. if (map && map.isTexture) {
  17174. encoding = map.encoding;
  17175. } else if (map && map.isWebGLRenderTarget) {
  17176. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  17177. encoding = map.texture.encoding;
  17178. } else {
  17179. encoding = LinearEncoding;
  17180. }
  17181. return encoding;
  17182. }
  17183. function getParameters(material, lights, shadows, scene, object) {
  17184. var fog = scene.fog;
  17185. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  17186. var envMap = cubemaps.get(material.envMap || environment);
  17187. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  17188. // (not to blow over maxLights budget)
  17189. var maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  17190. if (material.precision !== null) {
  17191. precision = capabilities.getMaxPrecision(material.precision);
  17192. if (precision !== material.precision) {
  17193. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  17194. }
  17195. }
  17196. var vertexShader, fragmentShader;
  17197. if (shaderID) {
  17198. var shader = ShaderLib[shaderID];
  17199. vertexShader = shader.vertexShader;
  17200. fragmentShader = shader.fragmentShader;
  17201. } else {
  17202. vertexShader = material.vertexShader;
  17203. fragmentShader = material.fragmentShader;
  17204. }
  17205. var currentRenderTarget = renderer.getRenderTarget();
  17206. var parameters = {
  17207. isWebGL2: isWebGL2,
  17208. shaderID: shaderID,
  17209. shaderName: material.type,
  17210. vertexShader: vertexShader,
  17211. fragmentShader: fragmentShader,
  17212. defines: material.defines,
  17213. isRawShaderMaterial: material.isRawShaderMaterial === true,
  17214. glslVersion: material.glslVersion,
  17215. precision: precision,
  17216. instancing: object.isInstancedMesh === true,
  17217. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  17218. supportsVertexTextures: vertexTextures,
  17219. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  17220. map: !!material.map,
  17221. mapEncoding: getTextureEncodingFromMap(material.map),
  17222. matcap: !!material.matcap,
  17223. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  17224. envMap: !!envMap,
  17225. envMapMode: envMap && envMap.mapping,
  17226. envMapEncoding: getTextureEncodingFromMap(envMap),
  17227. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  17228. lightMap: !!material.lightMap,
  17229. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  17230. aoMap: !!material.aoMap,
  17231. emissiveMap: !!material.emissiveMap,
  17232. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  17233. bumpMap: !!material.bumpMap,
  17234. normalMap: !!material.normalMap,
  17235. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  17236. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  17237. clearcoatMap: !!material.clearcoatMap,
  17238. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  17239. clearcoatNormalMap: !!material.clearcoatNormalMap,
  17240. displacementMap: !!material.displacementMap,
  17241. roughnessMap: !!material.roughnessMap,
  17242. metalnessMap: !!material.metalnessMap,
  17243. specularMap: !!material.specularMap,
  17244. alphaMap: !!material.alphaMap,
  17245. gradientMap: !!material.gradientMap,
  17246. sheen: !!material.sheen,
  17247. transmissionMap: !!material.transmissionMap,
  17248. combine: material.combine,
  17249. vertexTangents: material.normalMap && material.vertexTangents,
  17250. vertexColors: material.vertexColors,
  17251. 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,
  17252. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  17253. fog: !!fog,
  17254. useFog: material.fog,
  17255. fogExp2: fog && fog.isFogExp2,
  17256. flatShading: material.flatShading,
  17257. sizeAttenuation: material.sizeAttenuation,
  17258. logarithmicDepthBuffer: logarithmicDepthBuffer,
  17259. skinning: material.skinning && maxBones > 0,
  17260. maxBones: maxBones,
  17261. useVertexTexture: floatVertexTextures,
  17262. morphTargets: material.morphTargets,
  17263. morphNormals: material.morphNormals,
  17264. maxMorphTargets: renderer.maxMorphTargets,
  17265. maxMorphNormals: renderer.maxMorphNormals,
  17266. numDirLights: lights.directional.length,
  17267. numPointLights: lights.point.length,
  17268. numSpotLights: lights.spot.length,
  17269. numRectAreaLights: lights.rectArea.length,
  17270. numHemiLights: lights.hemi.length,
  17271. numDirLightShadows: lights.directionalShadowMap.length,
  17272. numPointLightShadows: lights.pointShadowMap.length,
  17273. numSpotLightShadows: lights.spotShadowMap.length,
  17274. numClippingPlanes: clipping.numPlanes,
  17275. numClipIntersection: clipping.numIntersection,
  17276. dithering: material.dithering,
  17277. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  17278. shadowMapType: renderer.shadowMap.type,
  17279. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  17280. physicallyCorrectLights: renderer.physicallyCorrectLights,
  17281. premultipliedAlpha: material.premultipliedAlpha,
  17282. alphaTest: material.alphaTest,
  17283. doubleSided: material.side === DoubleSide,
  17284. flipSided: material.side === BackSide,
  17285. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  17286. index0AttributeName: material.index0AttributeName,
  17287. extensionDerivatives: material.extensions && material.extensions.derivatives,
  17288. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  17289. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  17290. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  17291. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  17292. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  17293. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  17294. customProgramCacheKey: material.customProgramCacheKey()
  17295. };
  17296. return parameters;
  17297. }
  17298. function getProgramCacheKey(parameters) {
  17299. var array = [];
  17300. if (parameters.shaderID) {
  17301. array.push(parameters.shaderID);
  17302. } else {
  17303. array.push(parameters.fragmentShader);
  17304. array.push(parameters.vertexShader);
  17305. }
  17306. if (parameters.defines !== undefined) {
  17307. for (var name in parameters.defines) {
  17308. array.push(name);
  17309. array.push(parameters.defines[name]);
  17310. }
  17311. }
  17312. if (parameters.isRawShaderMaterial === false) {
  17313. for (var i = 0; i < parameterNames.length; i++) {
  17314. array.push(parameters[parameterNames[i]]);
  17315. }
  17316. array.push(renderer.outputEncoding);
  17317. array.push(renderer.gammaFactor);
  17318. }
  17319. array.push(parameters.customProgramCacheKey);
  17320. return array.join();
  17321. }
  17322. function getUniforms(material) {
  17323. var shaderID = shaderIDs[material.type];
  17324. var uniforms;
  17325. if (shaderID) {
  17326. var shader = ShaderLib[shaderID];
  17327. uniforms = UniformsUtils.clone(shader.uniforms);
  17328. } else {
  17329. uniforms = material.uniforms;
  17330. }
  17331. return uniforms;
  17332. }
  17333. function acquireProgram(parameters, cacheKey) {
  17334. var program; // Check if code has been already compiled
  17335. for (var p = 0, pl = programs.length; p < pl; p++) {
  17336. var preexistingProgram = programs[p];
  17337. if (preexistingProgram.cacheKey === cacheKey) {
  17338. program = preexistingProgram;
  17339. ++program.usedTimes;
  17340. break;
  17341. }
  17342. }
  17343. if (program === undefined) {
  17344. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  17345. programs.push(program);
  17346. }
  17347. return program;
  17348. }
  17349. function releaseProgram(program) {
  17350. if (--program.usedTimes === 0) {
  17351. // Remove from unordered set
  17352. var i = programs.indexOf(program);
  17353. programs[i] = programs[programs.length - 1];
  17354. programs.pop(); // Free WebGL resources
  17355. program.destroy();
  17356. }
  17357. }
  17358. return {
  17359. getParameters: getParameters,
  17360. getProgramCacheKey: getProgramCacheKey,
  17361. getUniforms: getUniforms,
  17362. acquireProgram: acquireProgram,
  17363. releaseProgram: releaseProgram,
  17364. // Exposed for resource monitoring & error feedback via renderer.info:
  17365. programs: programs
  17366. };
  17367. }
  17368. function WebGLProperties() {
  17369. var properties = new WeakMap();
  17370. function get(object) {
  17371. var map = properties.get(object);
  17372. if (map === undefined) {
  17373. map = {};
  17374. properties.set(object, map);
  17375. }
  17376. return map;
  17377. }
  17378. function remove(object) {
  17379. properties.delete(object);
  17380. }
  17381. function update(object, key, value) {
  17382. properties.get(object)[key] = value;
  17383. }
  17384. function dispose() {
  17385. properties = new WeakMap();
  17386. }
  17387. return {
  17388. get: get,
  17389. remove: remove,
  17390. update: update,
  17391. dispose: dispose
  17392. };
  17393. }
  17394. function painterSortStable(a, b) {
  17395. if (a.groupOrder !== b.groupOrder) {
  17396. return a.groupOrder - b.groupOrder;
  17397. } else if (a.renderOrder !== b.renderOrder) {
  17398. return a.renderOrder - b.renderOrder;
  17399. } else if (a.program !== b.program) {
  17400. return a.program.id - b.program.id;
  17401. } else if (a.material.id !== b.material.id) {
  17402. return a.material.id - b.material.id;
  17403. } else if (a.z !== b.z) {
  17404. return a.z - b.z;
  17405. } else {
  17406. return a.id - b.id;
  17407. }
  17408. }
  17409. function reversePainterSortStable(a, b) {
  17410. if (a.groupOrder !== b.groupOrder) {
  17411. return a.groupOrder - b.groupOrder;
  17412. } else if (a.renderOrder !== b.renderOrder) {
  17413. return a.renderOrder - b.renderOrder;
  17414. } else if (a.z !== b.z) {
  17415. return b.z - a.z;
  17416. } else {
  17417. return a.id - b.id;
  17418. }
  17419. }
  17420. function WebGLRenderList(properties) {
  17421. var renderItems = [];
  17422. var renderItemsIndex = 0;
  17423. var opaque = [];
  17424. var transparent = [];
  17425. var defaultProgram = {
  17426. id: -1
  17427. };
  17428. function init() {
  17429. renderItemsIndex = 0;
  17430. opaque.length = 0;
  17431. transparent.length = 0;
  17432. }
  17433. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  17434. var renderItem = renderItems[renderItemsIndex];
  17435. var materialProperties = properties.get(material);
  17436. if (renderItem === undefined) {
  17437. renderItem = {
  17438. id: object.id,
  17439. object: object,
  17440. geometry: geometry,
  17441. material: material,
  17442. program: materialProperties.program || defaultProgram,
  17443. groupOrder: groupOrder,
  17444. renderOrder: object.renderOrder,
  17445. z: z,
  17446. group: group
  17447. };
  17448. renderItems[renderItemsIndex] = renderItem;
  17449. } else {
  17450. renderItem.id = object.id;
  17451. renderItem.object = object;
  17452. renderItem.geometry = geometry;
  17453. renderItem.material = material;
  17454. renderItem.program = materialProperties.program || defaultProgram;
  17455. renderItem.groupOrder = groupOrder;
  17456. renderItem.renderOrder = object.renderOrder;
  17457. renderItem.z = z;
  17458. renderItem.group = group;
  17459. }
  17460. renderItemsIndex++;
  17461. return renderItem;
  17462. }
  17463. function push(object, geometry, material, groupOrder, z, group) {
  17464. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17465. (material.transparent === true ? transparent : opaque).push(renderItem);
  17466. }
  17467. function unshift(object, geometry, material, groupOrder, z, group) {
  17468. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17469. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  17470. }
  17471. function sort(customOpaqueSort, customTransparentSort) {
  17472. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  17473. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  17474. }
  17475. function finish() {
  17476. // Clear references from inactive renderItems in the list
  17477. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  17478. var renderItem = renderItems[i];
  17479. if (renderItem.id === null) break;
  17480. renderItem.id = null;
  17481. renderItem.object = null;
  17482. renderItem.geometry = null;
  17483. renderItem.material = null;
  17484. renderItem.program = null;
  17485. renderItem.group = null;
  17486. }
  17487. }
  17488. return {
  17489. opaque: opaque,
  17490. transparent: transparent,
  17491. init: init,
  17492. push: push,
  17493. unshift: unshift,
  17494. finish: finish,
  17495. sort: sort
  17496. };
  17497. }
  17498. function WebGLRenderLists(properties) {
  17499. var lists = new WeakMap();
  17500. function get(scene, camera) {
  17501. var cameras = lists.get(scene);
  17502. var list;
  17503. if (cameras === undefined) {
  17504. list = new WebGLRenderList(properties);
  17505. lists.set(scene, new WeakMap());
  17506. lists.get(scene).set(camera, list);
  17507. } else {
  17508. list = cameras.get(camera);
  17509. if (list === undefined) {
  17510. list = new WebGLRenderList(properties);
  17511. cameras.set(camera, list);
  17512. }
  17513. }
  17514. return list;
  17515. }
  17516. function dispose() {
  17517. lists = new WeakMap();
  17518. }
  17519. return {
  17520. get: get,
  17521. dispose: dispose
  17522. };
  17523. }
  17524. function UniformsCache() {
  17525. var lights = {};
  17526. return {
  17527. get: function get(light) {
  17528. if (lights[light.id] !== undefined) {
  17529. return lights[light.id];
  17530. }
  17531. var uniforms;
  17532. switch (light.type) {
  17533. case 'DirectionalLight':
  17534. uniforms = {
  17535. direction: new Vector3(),
  17536. color: new Color()
  17537. };
  17538. break;
  17539. case 'SpotLight':
  17540. uniforms = {
  17541. position: new Vector3(),
  17542. direction: new Vector3(),
  17543. color: new Color(),
  17544. distance: 0,
  17545. coneCos: 0,
  17546. penumbraCos: 0,
  17547. decay: 0
  17548. };
  17549. break;
  17550. case 'PointLight':
  17551. uniforms = {
  17552. position: new Vector3(),
  17553. color: new Color(),
  17554. distance: 0,
  17555. decay: 0
  17556. };
  17557. break;
  17558. case 'HemisphereLight':
  17559. uniforms = {
  17560. direction: new Vector3(),
  17561. skyColor: new Color(),
  17562. groundColor: new Color()
  17563. };
  17564. break;
  17565. case 'RectAreaLight':
  17566. uniforms = {
  17567. color: new Color(),
  17568. position: new Vector3(),
  17569. halfWidth: new Vector3(),
  17570. halfHeight: new Vector3()
  17571. };
  17572. break;
  17573. }
  17574. lights[light.id] = uniforms;
  17575. return uniforms;
  17576. }
  17577. };
  17578. }
  17579. function ShadowUniformsCache() {
  17580. var lights = {};
  17581. return {
  17582. get: function get(light) {
  17583. if (lights[light.id] !== undefined) {
  17584. return lights[light.id];
  17585. }
  17586. var uniforms;
  17587. switch (light.type) {
  17588. case 'DirectionalLight':
  17589. uniforms = {
  17590. shadowBias: 0,
  17591. shadowNormalBias: 0,
  17592. shadowRadius: 1,
  17593. shadowMapSize: new Vector2()
  17594. };
  17595. break;
  17596. case 'SpotLight':
  17597. uniforms = {
  17598. shadowBias: 0,
  17599. shadowNormalBias: 0,
  17600. shadowRadius: 1,
  17601. shadowMapSize: new Vector2()
  17602. };
  17603. break;
  17604. case 'PointLight':
  17605. uniforms = {
  17606. shadowBias: 0,
  17607. shadowNormalBias: 0,
  17608. shadowRadius: 1,
  17609. shadowMapSize: new Vector2(),
  17610. shadowCameraNear: 1,
  17611. shadowCameraFar: 1000
  17612. };
  17613. break;
  17614. // TODO (abelnation): set RectAreaLight shadow uniforms
  17615. }
  17616. lights[light.id] = uniforms;
  17617. return uniforms;
  17618. }
  17619. };
  17620. }
  17621. var nextVersion = 0;
  17622. function shadowCastingLightsFirst(lightA, lightB) {
  17623. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  17624. }
  17625. function WebGLLights(extensions, capabilities) {
  17626. var cache = new UniformsCache();
  17627. var shadowCache = ShadowUniformsCache();
  17628. var state = {
  17629. version: 0,
  17630. hash: {
  17631. directionalLength: -1,
  17632. pointLength: -1,
  17633. spotLength: -1,
  17634. rectAreaLength: -1,
  17635. hemiLength: -1,
  17636. numDirectionalShadows: -1,
  17637. numPointShadows: -1,
  17638. numSpotShadows: -1
  17639. },
  17640. ambient: [0, 0, 0],
  17641. probe: [],
  17642. directional: [],
  17643. directionalShadow: [],
  17644. directionalShadowMap: [],
  17645. directionalShadowMatrix: [],
  17646. spot: [],
  17647. spotShadow: [],
  17648. spotShadowMap: [],
  17649. spotShadowMatrix: [],
  17650. rectArea: [],
  17651. rectAreaLTC1: null,
  17652. rectAreaLTC2: null,
  17653. point: [],
  17654. pointShadow: [],
  17655. pointShadowMap: [],
  17656. pointShadowMatrix: [],
  17657. hemi: []
  17658. };
  17659. for (var i = 0; i < 9; i++) {
  17660. state.probe.push(new Vector3());
  17661. }
  17662. var vector3 = new Vector3();
  17663. var matrix4 = new Matrix4();
  17664. var matrix42 = new Matrix4();
  17665. function setup(lights) {
  17666. var r = 0,
  17667. g = 0,
  17668. b = 0;
  17669. for (var _i = 0; _i < 9; _i++) {
  17670. state.probe[_i].set(0, 0, 0);
  17671. }
  17672. var directionalLength = 0;
  17673. var pointLength = 0;
  17674. var spotLength = 0;
  17675. var rectAreaLength = 0;
  17676. var hemiLength = 0;
  17677. var numDirectionalShadows = 0;
  17678. var numPointShadows = 0;
  17679. var numSpotShadows = 0;
  17680. lights.sort(shadowCastingLightsFirst);
  17681. for (var _i2 = 0, l = lights.length; _i2 < l; _i2++) {
  17682. var light = lights[_i2];
  17683. var color = light.color;
  17684. var intensity = light.intensity;
  17685. var distance = light.distance;
  17686. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  17687. if (light.isAmbientLight) {
  17688. r += color.r * intensity;
  17689. g += color.g * intensity;
  17690. b += color.b * intensity;
  17691. } else if (light.isLightProbe) {
  17692. for (var j = 0; j < 9; j++) {
  17693. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  17694. }
  17695. } else if (light.isDirectionalLight) {
  17696. var uniforms = cache.get(light);
  17697. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  17698. if (light.castShadow) {
  17699. var shadow = light.shadow;
  17700. var shadowUniforms = shadowCache.get(light);
  17701. shadowUniforms.shadowBias = shadow.bias;
  17702. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17703. shadowUniforms.shadowRadius = shadow.radius;
  17704. shadowUniforms.shadowMapSize = shadow.mapSize;
  17705. state.directionalShadow[directionalLength] = shadowUniforms;
  17706. state.directionalShadowMap[directionalLength] = shadowMap;
  17707. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  17708. numDirectionalShadows++;
  17709. }
  17710. state.directional[directionalLength] = uniforms;
  17711. directionalLength++;
  17712. } else if (light.isSpotLight) {
  17713. var _uniforms = cache.get(light);
  17714. _uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17715. _uniforms.color.copy(color).multiplyScalar(intensity);
  17716. _uniforms.distance = distance;
  17717. _uniforms.coneCos = Math.cos(light.angle);
  17718. _uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  17719. _uniforms.decay = light.decay;
  17720. if (light.castShadow) {
  17721. var _shadow = light.shadow;
  17722. var _shadowUniforms = shadowCache.get(light);
  17723. _shadowUniforms.shadowBias = _shadow.bias;
  17724. _shadowUniforms.shadowNormalBias = _shadow.normalBias;
  17725. _shadowUniforms.shadowRadius = _shadow.radius;
  17726. _shadowUniforms.shadowMapSize = _shadow.mapSize;
  17727. state.spotShadow[spotLength] = _shadowUniforms;
  17728. state.spotShadowMap[spotLength] = shadowMap;
  17729. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  17730. numSpotShadows++;
  17731. }
  17732. state.spot[spotLength] = _uniforms;
  17733. spotLength++;
  17734. } else if (light.isRectAreaLight) {
  17735. var _uniforms2 = cache.get(light); // (a) intensity is the total visible light emitted
  17736. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17737. // (b) intensity is the brightness of the light
  17738. _uniforms2.color.copy(color).multiplyScalar(intensity);
  17739. _uniforms2.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17740. _uniforms2.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17741. state.rectArea[rectAreaLength] = _uniforms2;
  17742. rectAreaLength++;
  17743. } else if (light.isPointLight) {
  17744. var _uniforms3 = cache.get(light);
  17745. _uniforms3.color.copy(light.color).multiplyScalar(light.intensity);
  17746. _uniforms3.distance = light.distance;
  17747. _uniforms3.decay = light.decay;
  17748. if (light.castShadow) {
  17749. var _shadow2 = light.shadow;
  17750. var _shadowUniforms2 = shadowCache.get(light);
  17751. _shadowUniforms2.shadowBias = _shadow2.bias;
  17752. _shadowUniforms2.shadowNormalBias = _shadow2.normalBias;
  17753. _shadowUniforms2.shadowRadius = _shadow2.radius;
  17754. _shadowUniforms2.shadowMapSize = _shadow2.mapSize;
  17755. _shadowUniforms2.shadowCameraNear = _shadow2.camera.near;
  17756. _shadowUniforms2.shadowCameraFar = _shadow2.camera.far;
  17757. state.pointShadow[pointLength] = _shadowUniforms2;
  17758. state.pointShadowMap[pointLength] = shadowMap;
  17759. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  17760. numPointShadows++;
  17761. }
  17762. state.point[pointLength] = _uniforms3;
  17763. pointLength++;
  17764. } else if (light.isHemisphereLight) {
  17765. var _uniforms4 = cache.get(light);
  17766. _uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);
  17767. _uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  17768. state.hemi[hemiLength] = _uniforms4;
  17769. hemiLength++;
  17770. }
  17771. }
  17772. if (rectAreaLength > 0) {
  17773. if (capabilities.isWebGL2) {
  17774. // WebGL 2
  17775. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17776. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17777. } else {
  17778. // WebGL 1
  17779. if (extensions.has('OES_texture_float_linear') === true) {
  17780. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17781. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17782. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  17783. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  17784. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  17785. } else {
  17786. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  17787. }
  17788. }
  17789. }
  17790. state.ambient[0] = r;
  17791. state.ambient[1] = g;
  17792. state.ambient[2] = b;
  17793. var hash = state.hash;
  17794. 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) {
  17795. state.directional.length = directionalLength;
  17796. state.spot.length = spotLength;
  17797. state.rectArea.length = rectAreaLength;
  17798. state.point.length = pointLength;
  17799. state.hemi.length = hemiLength;
  17800. state.directionalShadow.length = numDirectionalShadows;
  17801. state.directionalShadowMap.length = numDirectionalShadows;
  17802. state.pointShadow.length = numPointShadows;
  17803. state.pointShadowMap.length = numPointShadows;
  17804. state.spotShadow.length = numSpotShadows;
  17805. state.spotShadowMap.length = numSpotShadows;
  17806. state.directionalShadowMatrix.length = numDirectionalShadows;
  17807. state.pointShadowMatrix.length = numPointShadows;
  17808. state.spotShadowMatrix.length = numSpotShadows;
  17809. hash.directionalLength = directionalLength;
  17810. hash.pointLength = pointLength;
  17811. hash.spotLength = spotLength;
  17812. hash.rectAreaLength = rectAreaLength;
  17813. hash.hemiLength = hemiLength;
  17814. hash.numDirectionalShadows = numDirectionalShadows;
  17815. hash.numPointShadows = numPointShadows;
  17816. hash.numSpotShadows = numSpotShadows;
  17817. state.version = nextVersion++;
  17818. }
  17819. }
  17820. function setupView(lights, camera) {
  17821. var directionalLength = 0;
  17822. var pointLength = 0;
  17823. var spotLength = 0;
  17824. var rectAreaLength = 0;
  17825. var hemiLength = 0;
  17826. var viewMatrix = camera.matrixWorldInverse;
  17827. for (var _i3 = 0, l = lights.length; _i3 < l; _i3++) {
  17828. var light = lights[_i3];
  17829. if (light.isDirectionalLight) {
  17830. var uniforms = state.directional[directionalLength];
  17831. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17832. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17833. uniforms.direction.sub(vector3);
  17834. uniforms.direction.transformDirection(viewMatrix);
  17835. directionalLength++;
  17836. } else if (light.isSpotLight) {
  17837. var _uniforms5 = state.spot[spotLength];
  17838. _uniforms5.position.setFromMatrixPosition(light.matrixWorld);
  17839. _uniforms5.position.applyMatrix4(viewMatrix);
  17840. _uniforms5.direction.setFromMatrixPosition(light.matrixWorld);
  17841. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17842. _uniforms5.direction.sub(vector3);
  17843. _uniforms5.direction.transformDirection(viewMatrix);
  17844. spotLength++;
  17845. } else if (light.isRectAreaLight) {
  17846. var _uniforms6 = state.rectArea[rectAreaLength];
  17847. _uniforms6.position.setFromMatrixPosition(light.matrixWorld);
  17848. _uniforms6.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  17849. matrix42.identity();
  17850. matrix4.copy(light.matrixWorld);
  17851. matrix4.premultiply(viewMatrix);
  17852. matrix42.extractRotation(matrix4);
  17853. _uniforms6.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17854. _uniforms6.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17855. _uniforms6.halfWidth.applyMatrix4(matrix42);
  17856. _uniforms6.halfHeight.applyMatrix4(matrix42);
  17857. rectAreaLength++;
  17858. } else if (light.isPointLight) {
  17859. var _uniforms7 = state.point[pointLength];
  17860. _uniforms7.position.setFromMatrixPosition(light.matrixWorld);
  17861. _uniforms7.position.applyMatrix4(viewMatrix);
  17862. pointLength++;
  17863. } else if (light.isHemisphereLight) {
  17864. var _uniforms8 = state.hemi[hemiLength];
  17865. _uniforms8.direction.setFromMatrixPosition(light.matrixWorld);
  17866. _uniforms8.direction.transformDirection(viewMatrix);
  17867. _uniforms8.direction.normalize();
  17868. hemiLength++;
  17869. }
  17870. }
  17871. }
  17872. return {
  17873. setup: setup,
  17874. setupView: setupView,
  17875. state: state
  17876. };
  17877. }
  17878. function WebGLRenderState(extensions, capabilities) {
  17879. var lights = new WebGLLights(extensions, capabilities);
  17880. var lightsArray = [];
  17881. var shadowsArray = [];
  17882. function init() {
  17883. lightsArray.length = 0;
  17884. shadowsArray.length = 0;
  17885. }
  17886. function pushLight(light) {
  17887. lightsArray.push(light);
  17888. }
  17889. function pushShadow(shadowLight) {
  17890. shadowsArray.push(shadowLight);
  17891. }
  17892. function setupLights() {
  17893. lights.setup(lightsArray);
  17894. }
  17895. function setupLightsView(camera) {
  17896. lights.setupView(lightsArray, camera);
  17897. }
  17898. var state = {
  17899. lightsArray: lightsArray,
  17900. shadowsArray: shadowsArray,
  17901. lights: lights
  17902. };
  17903. return {
  17904. init: init,
  17905. state: state,
  17906. setupLights: setupLights,
  17907. setupLightsView: setupLightsView,
  17908. pushLight: pushLight,
  17909. pushShadow: pushShadow
  17910. };
  17911. }
  17912. function WebGLRenderStates(extensions, capabilities) {
  17913. var renderStates = new WeakMap();
  17914. function get(scene, renderCallDepth) {
  17915. if (renderCallDepth === void 0) {
  17916. renderCallDepth = 0;
  17917. }
  17918. var renderState;
  17919. if (renderStates.has(scene) === false) {
  17920. renderState = new WebGLRenderState(extensions, capabilities);
  17921. renderStates.set(scene, []);
  17922. renderStates.get(scene).push(renderState);
  17923. } else {
  17924. if (renderCallDepth >= renderStates.get(scene).length) {
  17925. renderState = new WebGLRenderState(extensions, capabilities);
  17926. renderStates.get(scene).push(renderState);
  17927. } else {
  17928. renderState = renderStates.get(scene)[renderCallDepth];
  17929. }
  17930. }
  17931. return renderState;
  17932. }
  17933. function dispose() {
  17934. renderStates = new WeakMap();
  17935. }
  17936. return {
  17937. get: get,
  17938. dispose: dispose
  17939. };
  17940. }
  17941. /**
  17942. * parameters = {
  17943. *
  17944. * opacity: <float>,
  17945. *
  17946. * map: new THREE.Texture( <Image> ),
  17947. *
  17948. * alphaMap: new THREE.Texture( <Image> ),
  17949. *
  17950. * displacementMap: new THREE.Texture( <Image> ),
  17951. * displacementScale: <float>,
  17952. * displacementBias: <float>,
  17953. *
  17954. * wireframe: <boolean>,
  17955. * wireframeLinewidth: <float>
  17956. * }
  17957. */
  17958. function MeshDepthMaterial(parameters) {
  17959. Material.call(this);
  17960. this.type = 'MeshDepthMaterial';
  17961. this.depthPacking = BasicDepthPacking;
  17962. this.skinning = false;
  17963. this.morphTargets = false;
  17964. this.map = null;
  17965. this.alphaMap = null;
  17966. this.displacementMap = null;
  17967. this.displacementScale = 1;
  17968. this.displacementBias = 0;
  17969. this.wireframe = false;
  17970. this.wireframeLinewidth = 1;
  17971. this.fog = false;
  17972. this.setValues(parameters);
  17973. }
  17974. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  17975. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17976. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17977. MeshDepthMaterial.prototype.copy = function (source) {
  17978. Material.prototype.copy.call(this, source);
  17979. this.depthPacking = source.depthPacking;
  17980. this.skinning = source.skinning;
  17981. this.morphTargets = source.morphTargets;
  17982. this.map = source.map;
  17983. this.alphaMap = source.alphaMap;
  17984. this.displacementMap = source.displacementMap;
  17985. this.displacementScale = source.displacementScale;
  17986. this.displacementBias = source.displacementBias;
  17987. this.wireframe = source.wireframe;
  17988. this.wireframeLinewidth = source.wireframeLinewidth;
  17989. return this;
  17990. };
  17991. /**
  17992. * parameters = {
  17993. *
  17994. * referencePosition: <float>,
  17995. * nearDistance: <float>,
  17996. * farDistance: <float>,
  17997. *
  17998. * skinning: <bool>,
  17999. * morphTargets: <bool>,
  18000. *
  18001. * map: new THREE.Texture( <Image> ),
  18002. *
  18003. * alphaMap: new THREE.Texture( <Image> ),
  18004. *
  18005. * displacementMap: new THREE.Texture( <Image> ),
  18006. * displacementScale: <float>,
  18007. * displacementBias: <float>
  18008. *
  18009. * }
  18010. */
  18011. function MeshDistanceMaterial(parameters) {
  18012. Material.call(this);
  18013. this.type = 'MeshDistanceMaterial';
  18014. this.referencePosition = new Vector3();
  18015. this.nearDistance = 1;
  18016. this.farDistance = 1000;
  18017. this.skinning = false;
  18018. this.morphTargets = false;
  18019. this.map = null;
  18020. this.alphaMap = null;
  18021. this.displacementMap = null;
  18022. this.displacementScale = 1;
  18023. this.displacementBias = 0;
  18024. this.fog = false;
  18025. this.setValues(parameters);
  18026. }
  18027. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  18028. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  18029. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  18030. MeshDistanceMaterial.prototype.copy = function (source) {
  18031. Material.prototype.copy.call(this, source);
  18032. this.referencePosition.copy(source.referencePosition);
  18033. this.nearDistance = source.nearDistance;
  18034. this.farDistance = source.farDistance;
  18035. this.skinning = source.skinning;
  18036. this.morphTargets = source.morphTargets;
  18037. this.map = source.map;
  18038. this.alphaMap = source.alphaMap;
  18039. this.displacementMap = source.displacementMap;
  18040. this.displacementScale = source.displacementScale;
  18041. this.displacementBias = source.displacementBias;
  18042. return this;
  18043. };
  18044. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\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\t\t#else\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\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  18045. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  18046. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  18047. var _frustum = new Frustum();
  18048. var _shadowMapSize = new Vector2(),
  18049. _viewportSize = new Vector2(),
  18050. _viewport = new Vector4(),
  18051. _depthMaterials = [],
  18052. _distanceMaterials = [],
  18053. _materialCache = {};
  18054. var shadowSide = {
  18055. 0: BackSide,
  18056. 1: FrontSide,
  18057. 2: DoubleSide
  18058. };
  18059. var shadowMaterialVertical = new ShaderMaterial({
  18060. defines: {
  18061. SAMPLE_RATE: 2.0 / 8.0,
  18062. HALF_SAMPLE_RATE: 1.0 / 8.0
  18063. },
  18064. uniforms: {
  18065. shadow_pass: {
  18066. value: null
  18067. },
  18068. resolution: {
  18069. value: new Vector2()
  18070. },
  18071. radius: {
  18072. value: 4.0
  18073. }
  18074. },
  18075. vertexShader: vsm_vert,
  18076. fragmentShader: vsm_frag
  18077. });
  18078. var shadowMaterialHorizontal = shadowMaterialVertical.clone();
  18079. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  18080. var fullScreenTri = new BufferGeometry();
  18081. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  18082. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  18083. var scope = this;
  18084. this.enabled = false;
  18085. this.autoUpdate = true;
  18086. this.needsUpdate = false;
  18087. this.type = PCFShadowMap;
  18088. this.render = function (lights, scene, camera) {
  18089. if (scope.enabled === false) return;
  18090. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  18091. if (lights.length === 0) return;
  18092. var currentRenderTarget = _renderer.getRenderTarget();
  18093. var activeCubeFace = _renderer.getActiveCubeFace();
  18094. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  18095. var _state = _renderer.state; // Set GL state for depth map.
  18096. _state.setBlending(NoBlending);
  18097. _state.buffers.color.setClear(1, 1, 1, 1);
  18098. _state.buffers.depth.setTest(true);
  18099. _state.setScissorTest(false); // render depth map
  18100. for (var i = 0, il = lights.length; i < il; i++) {
  18101. var light = lights[i];
  18102. var shadow = light.shadow;
  18103. if (shadow === undefined) {
  18104. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  18105. continue;
  18106. }
  18107. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  18108. _shadowMapSize.copy(shadow.mapSize);
  18109. var shadowFrameExtents = shadow.getFrameExtents();
  18110. _shadowMapSize.multiply(shadowFrameExtents);
  18111. _viewportSize.copy(shadow.mapSize);
  18112. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  18113. if (_shadowMapSize.x > maxTextureSize) {
  18114. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  18115. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  18116. shadow.mapSize.x = _viewportSize.x;
  18117. }
  18118. if (_shadowMapSize.y > maxTextureSize) {
  18119. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  18120. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  18121. shadow.mapSize.y = _viewportSize.y;
  18122. }
  18123. }
  18124. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18125. var pars = {
  18126. minFilter: LinearFilter,
  18127. magFilter: LinearFilter,
  18128. format: RGBAFormat
  18129. };
  18130. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18131. shadow.map.texture.name = light.name + '.shadowMap';
  18132. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18133. shadow.camera.updateProjectionMatrix();
  18134. }
  18135. if (shadow.map === null) {
  18136. var _pars = {
  18137. minFilter: NearestFilter,
  18138. magFilter: NearestFilter,
  18139. format: RGBAFormat
  18140. };
  18141. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, _pars);
  18142. shadow.map.texture.name = light.name + '.shadowMap';
  18143. shadow.camera.updateProjectionMatrix();
  18144. }
  18145. _renderer.setRenderTarget(shadow.map);
  18146. _renderer.clear();
  18147. var viewportCount = shadow.getViewportCount();
  18148. for (var vp = 0; vp < viewportCount; vp++) {
  18149. var viewport = shadow.getViewport(vp);
  18150. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  18151. _state.viewport(_viewport);
  18152. shadow.updateMatrices(light, vp);
  18153. _frustum = shadow.getFrustum();
  18154. renderObject(scene, camera, shadow.camera, light, this.type);
  18155. } // do blur pass for VSM
  18156. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18157. VSMPass(shadow, camera);
  18158. }
  18159. shadow.needsUpdate = false;
  18160. }
  18161. scope.needsUpdate = false;
  18162. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  18163. };
  18164. function VSMPass(shadow, camera) {
  18165. var geometry = _objects.update(fullScreenMesh); // vertical pass
  18166. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  18167. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  18168. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  18169. _renderer.setRenderTarget(shadow.mapPass);
  18170. _renderer.clear();
  18171. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  18172. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  18173. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  18174. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  18175. _renderer.setRenderTarget(shadow.map);
  18176. _renderer.clear();
  18177. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  18178. }
  18179. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  18180. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  18181. var material = _depthMaterials[index];
  18182. if (material === undefined) {
  18183. material = new MeshDepthMaterial({
  18184. depthPacking: RGBADepthPacking,
  18185. morphTargets: useMorphing,
  18186. skinning: useSkinning
  18187. });
  18188. _depthMaterials[index] = material;
  18189. }
  18190. return material;
  18191. }
  18192. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  18193. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  18194. var material = _distanceMaterials[index];
  18195. if (material === undefined) {
  18196. material = new MeshDistanceMaterial({
  18197. morphTargets: useMorphing,
  18198. skinning: useSkinning
  18199. });
  18200. _distanceMaterials[index] = material;
  18201. }
  18202. return material;
  18203. }
  18204. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  18205. var result = null;
  18206. var getMaterialVariant = getDepthMaterialVariant;
  18207. var customMaterial = object.customDepthMaterial;
  18208. if (light.isPointLight === true) {
  18209. getMaterialVariant = getDistanceMaterialVariant;
  18210. customMaterial = object.customDistanceMaterial;
  18211. }
  18212. if (customMaterial === undefined) {
  18213. var useMorphing = false;
  18214. if (material.morphTargets === true) {
  18215. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  18216. }
  18217. var useSkinning = false;
  18218. if (object.isSkinnedMesh === true) {
  18219. if (material.skinning === true) {
  18220. useSkinning = true;
  18221. } else {
  18222. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  18223. }
  18224. }
  18225. var useInstancing = object.isInstancedMesh === true;
  18226. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  18227. } else {
  18228. result = customMaterial;
  18229. }
  18230. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  18231. // in this case we need a unique material instance reflecting the
  18232. // appropriate state
  18233. var keyA = result.uuid,
  18234. keyB = material.uuid;
  18235. var materialsForVariant = _materialCache[keyA];
  18236. if (materialsForVariant === undefined) {
  18237. materialsForVariant = {};
  18238. _materialCache[keyA] = materialsForVariant;
  18239. }
  18240. var cachedMaterial = materialsForVariant[keyB];
  18241. if (cachedMaterial === undefined) {
  18242. cachedMaterial = result.clone();
  18243. materialsForVariant[keyB] = cachedMaterial;
  18244. }
  18245. result = cachedMaterial;
  18246. }
  18247. result.visible = material.visible;
  18248. result.wireframe = material.wireframe;
  18249. if (type === VSMShadowMap) {
  18250. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  18251. } else {
  18252. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  18253. }
  18254. result.clipShadows = material.clipShadows;
  18255. result.clippingPlanes = material.clippingPlanes;
  18256. result.clipIntersection = material.clipIntersection;
  18257. result.wireframeLinewidth = material.wireframeLinewidth;
  18258. result.linewidth = material.linewidth;
  18259. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  18260. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  18261. result.nearDistance = shadowCameraNear;
  18262. result.farDistance = shadowCameraFar;
  18263. }
  18264. return result;
  18265. }
  18266. function renderObject(object, camera, shadowCamera, light, type) {
  18267. if (object.visible === false) return;
  18268. var visible = object.layers.test(camera.layers);
  18269. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  18270. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  18271. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  18272. var geometry = _objects.update(object);
  18273. var material = object.material;
  18274. if (Array.isArray(material)) {
  18275. var groups = geometry.groups;
  18276. for (var k = 0, kl = groups.length; k < kl; k++) {
  18277. var group = groups[k];
  18278. var groupMaterial = material[group.materialIndex];
  18279. if (groupMaterial && groupMaterial.visible) {
  18280. var depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  18281. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  18282. }
  18283. }
  18284. } else if (material.visible) {
  18285. var _depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  18286. _renderer.renderBufferDirect(shadowCamera, null, geometry, _depthMaterial, object, null);
  18287. }
  18288. }
  18289. }
  18290. var children = object.children;
  18291. for (var i = 0, l = children.length; i < l; i++) {
  18292. renderObject(children[i], camera, shadowCamera, light, type);
  18293. }
  18294. }
  18295. }
  18296. function WebGLState(gl, extensions, capabilities) {
  18297. var _equationToGL, _factorToGL;
  18298. var isWebGL2 = capabilities.isWebGL2;
  18299. function ColorBuffer() {
  18300. var locked = false;
  18301. var color = new Vector4();
  18302. var currentColorMask = null;
  18303. var currentColorClear = new Vector4(0, 0, 0, 0);
  18304. return {
  18305. setMask: function setMask(colorMask) {
  18306. if (currentColorMask !== colorMask && !locked) {
  18307. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  18308. currentColorMask = colorMask;
  18309. }
  18310. },
  18311. setLocked: function setLocked(lock) {
  18312. locked = lock;
  18313. },
  18314. setClear: function setClear(r, g, b, a, premultipliedAlpha) {
  18315. if (premultipliedAlpha === true) {
  18316. r *= a;
  18317. g *= a;
  18318. b *= a;
  18319. }
  18320. color.set(r, g, b, a);
  18321. if (currentColorClear.equals(color) === false) {
  18322. gl.clearColor(r, g, b, a);
  18323. currentColorClear.copy(color);
  18324. }
  18325. },
  18326. reset: function reset() {
  18327. locked = false;
  18328. currentColorMask = null;
  18329. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  18330. }
  18331. };
  18332. }
  18333. function DepthBuffer() {
  18334. var locked = false;
  18335. var currentDepthMask = null;
  18336. var currentDepthFunc = null;
  18337. var currentDepthClear = null;
  18338. return {
  18339. setTest: function setTest(depthTest) {
  18340. if (depthTest) {
  18341. enable(2929);
  18342. } else {
  18343. disable(2929);
  18344. }
  18345. },
  18346. setMask: function setMask(depthMask) {
  18347. if (currentDepthMask !== depthMask && !locked) {
  18348. gl.depthMask(depthMask);
  18349. currentDepthMask = depthMask;
  18350. }
  18351. },
  18352. setFunc: function setFunc(depthFunc) {
  18353. if (currentDepthFunc !== depthFunc) {
  18354. if (depthFunc) {
  18355. switch (depthFunc) {
  18356. case NeverDepth:
  18357. gl.depthFunc(512);
  18358. break;
  18359. case AlwaysDepth:
  18360. gl.depthFunc(519);
  18361. break;
  18362. case LessDepth:
  18363. gl.depthFunc(513);
  18364. break;
  18365. case LessEqualDepth:
  18366. gl.depthFunc(515);
  18367. break;
  18368. case EqualDepth:
  18369. gl.depthFunc(514);
  18370. break;
  18371. case GreaterEqualDepth:
  18372. gl.depthFunc(518);
  18373. break;
  18374. case GreaterDepth:
  18375. gl.depthFunc(516);
  18376. break;
  18377. case NotEqualDepth:
  18378. gl.depthFunc(517);
  18379. break;
  18380. default:
  18381. gl.depthFunc(515);
  18382. }
  18383. } else {
  18384. gl.depthFunc(515);
  18385. }
  18386. currentDepthFunc = depthFunc;
  18387. }
  18388. },
  18389. setLocked: function setLocked(lock) {
  18390. locked = lock;
  18391. },
  18392. setClear: function setClear(depth) {
  18393. if (currentDepthClear !== depth) {
  18394. gl.clearDepth(depth);
  18395. currentDepthClear = depth;
  18396. }
  18397. },
  18398. reset: function reset() {
  18399. locked = false;
  18400. currentDepthMask = null;
  18401. currentDepthFunc = null;
  18402. currentDepthClear = null;
  18403. }
  18404. };
  18405. }
  18406. function StencilBuffer() {
  18407. var locked = false;
  18408. var currentStencilMask = null;
  18409. var currentStencilFunc = null;
  18410. var currentStencilRef = null;
  18411. var currentStencilFuncMask = null;
  18412. var currentStencilFail = null;
  18413. var currentStencilZFail = null;
  18414. var currentStencilZPass = null;
  18415. var currentStencilClear = null;
  18416. return {
  18417. setTest: function setTest(stencilTest) {
  18418. if (!locked) {
  18419. if (stencilTest) {
  18420. enable(2960);
  18421. } else {
  18422. disable(2960);
  18423. }
  18424. }
  18425. },
  18426. setMask: function setMask(stencilMask) {
  18427. if (currentStencilMask !== stencilMask && !locked) {
  18428. gl.stencilMask(stencilMask);
  18429. currentStencilMask = stencilMask;
  18430. }
  18431. },
  18432. setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {
  18433. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  18434. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  18435. currentStencilFunc = stencilFunc;
  18436. currentStencilRef = stencilRef;
  18437. currentStencilFuncMask = stencilMask;
  18438. }
  18439. },
  18440. setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {
  18441. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  18442. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  18443. currentStencilFail = stencilFail;
  18444. currentStencilZFail = stencilZFail;
  18445. currentStencilZPass = stencilZPass;
  18446. }
  18447. },
  18448. setLocked: function setLocked(lock) {
  18449. locked = lock;
  18450. },
  18451. setClear: function setClear(stencil) {
  18452. if (currentStencilClear !== stencil) {
  18453. gl.clearStencil(stencil);
  18454. currentStencilClear = stencil;
  18455. }
  18456. },
  18457. reset: function reset() {
  18458. locked = false;
  18459. currentStencilMask = null;
  18460. currentStencilFunc = null;
  18461. currentStencilRef = null;
  18462. currentStencilFuncMask = null;
  18463. currentStencilFail = null;
  18464. currentStencilZFail = null;
  18465. currentStencilZPass = null;
  18466. currentStencilClear = null;
  18467. }
  18468. };
  18469. } //
  18470. var colorBuffer = new ColorBuffer();
  18471. var depthBuffer = new DepthBuffer();
  18472. var stencilBuffer = new StencilBuffer();
  18473. var enabledCapabilities = {};
  18474. var currentProgram = null;
  18475. var currentBlendingEnabled = null;
  18476. var currentBlending = null;
  18477. var currentBlendEquation = null;
  18478. var currentBlendSrc = null;
  18479. var currentBlendDst = null;
  18480. var currentBlendEquationAlpha = null;
  18481. var currentBlendSrcAlpha = null;
  18482. var currentBlendDstAlpha = null;
  18483. var currentPremultipledAlpha = false;
  18484. var currentFlipSided = null;
  18485. var currentCullFace = null;
  18486. var currentLineWidth = null;
  18487. var currentPolygonOffsetFactor = null;
  18488. var currentPolygonOffsetUnits = null;
  18489. var maxTextures = gl.getParameter(35661);
  18490. var lineWidthAvailable = false;
  18491. var version = 0;
  18492. var glVersion = gl.getParameter(7938);
  18493. if (glVersion.indexOf('WebGL') !== -1) {
  18494. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  18495. lineWidthAvailable = version >= 1.0;
  18496. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  18497. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  18498. lineWidthAvailable = version >= 2.0;
  18499. }
  18500. var currentTextureSlot = null;
  18501. var currentBoundTextures = {};
  18502. var currentScissor = new Vector4();
  18503. var currentViewport = new Vector4();
  18504. function createTexture(type, target, count) {
  18505. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  18506. var texture = gl.createTexture();
  18507. gl.bindTexture(type, texture);
  18508. gl.texParameteri(type, 10241, 9728);
  18509. gl.texParameteri(type, 10240, 9728);
  18510. for (var i = 0; i < count; i++) {
  18511. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  18512. }
  18513. return texture;
  18514. }
  18515. var emptyTextures = {};
  18516. emptyTextures[3553] = createTexture(3553, 3553, 1);
  18517. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  18518. colorBuffer.setClear(0, 0, 0, 1);
  18519. depthBuffer.setClear(1);
  18520. stencilBuffer.setClear(0);
  18521. enable(2929);
  18522. depthBuffer.setFunc(LessEqualDepth);
  18523. setFlipSided(false);
  18524. setCullFace(CullFaceBack);
  18525. enable(2884);
  18526. setBlending(NoBlending); //
  18527. function enable(id) {
  18528. if (enabledCapabilities[id] !== true) {
  18529. gl.enable(id);
  18530. enabledCapabilities[id] = true;
  18531. }
  18532. }
  18533. function disable(id) {
  18534. if (enabledCapabilities[id] !== false) {
  18535. gl.disable(id);
  18536. enabledCapabilities[id] = false;
  18537. }
  18538. }
  18539. function useProgram(program) {
  18540. if (currentProgram !== program) {
  18541. gl.useProgram(program);
  18542. currentProgram = program;
  18543. return true;
  18544. }
  18545. return false;
  18546. }
  18547. var equationToGL = (_equationToGL = {}, _equationToGL[AddEquation] = 32774, _equationToGL[SubtractEquation] = 32778, _equationToGL[ReverseSubtractEquation] = 32779, _equationToGL);
  18548. if (isWebGL2) {
  18549. equationToGL[MinEquation] = 32775;
  18550. equationToGL[MaxEquation] = 32776;
  18551. } else {
  18552. var extension = extensions.get('EXT_blend_minmax');
  18553. if (extension !== null) {
  18554. equationToGL[MinEquation] = extension.MIN_EXT;
  18555. equationToGL[MaxEquation] = extension.MAX_EXT;
  18556. }
  18557. }
  18558. 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);
  18559. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  18560. if (blending === NoBlending) {
  18561. if (currentBlendingEnabled) {
  18562. disable(3042);
  18563. currentBlendingEnabled = false;
  18564. }
  18565. return;
  18566. }
  18567. if (!currentBlendingEnabled) {
  18568. enable(3042);
  18569. currentBlendingEnabled = true;
  18570. }
  18571. if (blending !== CustomBlending) {
  18572. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  18573. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  18574. gl.blendEquation(32774);
  18575. currentBlendEquation = AddEquation;
  18576. currentBlendEquationAlpha = AddEquation;
  18577. }
  18578. if (premultipliedAlpha) {
  18579. switch (blending) {
  18580. case NormalBlending:
  18581. gl.blendFuncSeparate(1, 771, 1, 771);
  18582. break;
  18583. case AdditiveBlending:
  18584. gl.blendFunc(1, 1);
  18585. break;
  18586. case SubtractiveBlending:
  18587. gl.blendFuncSeparate(0, 0, 769, 771);
  18588. break;
  18589. case MultiplyBlending:
  18590. gl.blendFuncSeparate(0, 768, 0, 770);
  18591. break;
  18592. default:
  18593. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18594. break;
  18595. }
  18596. } else {
  18597. switch (blending) {
  18598. case NormalBlending:
  18599. gl.blendFuncSeparate(770, 771, 1, 771);
  18600. break;
  18601. case AdditiveBlending:
  18602. gl.blendFunc(770, 1);
  18603. break;
  18604. case SubtractiveBlending:
  18605. gl.blendFunc(0, 769);
  18606. break;
  18607. case MultiplyBlending:
  18608. gl.blendFunc(0, 768);
  18609. break;
  18610. default:
  18611. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18612. break;
  18613. }
  18614. }
  18615. currentBlendSrc = null;
  18616. currentBlendDst = null;
  18617. currentBlendSrcAlpha = null;
  18618. currentBlendDstAlpha = null;
  18619. currentBlending = blending;
  18620. currentPremultipledAlpha = premultipliedAlpha;
  18621. }
  18622. return;
  18623. } // custom blending
  18624. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18625. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18626. blendDstAlpha = blendDstAlpha || blendDst;
  18627. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  18628. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  18629. currentBlendEquation = blendEquation;
  18630. currentBlendEquationAlpha = blendEquationAlpha;
  18631. }
  18632. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  18633. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  18634. currentBlendSrc = blendSrc;
  18635. currentBlendDst = blendDst;
  18636. currentBlendSrcAlpha = blendSrcAlpha;
  18637. currentBlendDstAlpha = blendDstAlpha;
  18638. }
  18639. currentBlending = blending;
  18640. currentPremultipledAlpha = null;
  18641. }
  18642. function setMaterial(material, frontFaceCW) {
  18643. material.side === DoubleSide ? disable(2884) : enable(2884);
  18644. var flipSided = material.side === BackSide;
  18645. if (frontFaceCW) flipSided = !flipSided;
  18646. setFlipSided(flipSided);
  18647. 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);
  18648. depthBuffer.setFunc(material.depthFunc);
  18649. depthBuffer.setTest(material.depthTest);
  18650. depthBuffer.setMask(material.depthWrite);
  18651. colorBuffer.setMask(material.colorWrite);
  18652. var stencilWrite = material.stencilWrite;
  18653. stencilBuffer.setTest(stencilWrite);
  18654. if (stencilWrite) {
  18655. stencilBuffer.setMask(material.stencilWriteMask);
  18656. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  18657. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  18658. }
  18659. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  18660. } //
  18661. function setFlipSided(flipSided) {
  18662. if (currentFlipSided !== flipSided) {
  18663. if (flipSided) {
  18664. gl.frontFace(2304);
  18665. } else {
  18666. gl.frontFace(2305);
  18667. }
  18668. currentFlipSided = flipSided;
  18669. }
  18670. }
  18671. function setCullFace(cullFace) {
  18672. if (cullFace !== CullFaceNone) {
  18673. enable(2884);
  18674. if (cullFace !== currentCullFace) {
  18675. if (cullFace === CullFaceBack) {
  18676. gl.cullFace(1029);
  18677. } else if (cullFace === CullFaceFront) {
  18678. gl.cullFace(1028);
  18679. } else {
  18680. gl.cullFace(1032);
  18681. }
  18682. }
  18683. } else {
  18684. disable(2884);
  18685. }
  18686. currentCullFace = cullFace;
  18687. }
  18688. function setLineWidth(width) {
  18689. if (width !== currentLineWidth) {
  18690. if (lineWidthAvailable) gl.lineWidth(width);
  18691. currentLineWidth = width;
  18692. }
  18693. }
  18694. function setPolygonOffset(polygonOffset, factor, units) {
  18695. if (polygonOffset) {
  18696. enable(32823);
  18697. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  18698. gl.polygonOffset(factor, units);
  18699. currentPolygonOffsetFactor = factor;
  18700. currentPolygonOffsetUnits = units;
  18701. }
  18702. } else {
  18703. disable(32823);
  18704. }
  18705. }
  18706. function setScissorTest(scissorTest) {
  18707. if (scissorTest) {
  18708. enable(3089);
  18709. } else {
  18710. disable(3089);
  18711. }
  18712. } // texture
  18713. function activeTexture(webglSlot) {
  18714. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  18715. if (currentTextureSlot !== webglSlot) {
  18716. gl.activeTexture(webglSlot);
  18717. currentTextureSlot = webglSlot;
  18718. }
  18719. }
  18720. function bindTexture(webglType, webglTexture) {
  18721. if (currentTextureSlot === null) {
  18722. activeTexture();
  18723. }
  18724. var boundTexture = currentBoundTextures[currentTextureSlot];
  18725. if (boundTexture === undefined) {
  18726. boundTexture = {
  18727. type: undefined,
  18728. texture: undefined
  18729. };
  18730. currentBoundTextures[currentTextureSlot] = boundTexture;
  18731. }
  18732. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  18733. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  18734. boundTexture.type = webglType;
  18735. boundTexture.texture = webglTexture;
  18736. }
  18737. }
  18738. function unbindTexture() {
  18739. var boundTexture = currentBoundTextures[currentTextureSlot];
  18740. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  18741. gl.bindTexture(boundTexture.type, null);
  18742. boundTexture.type = undefined;
  18743. boundTexture.texture = undefined;
  18744. }
  18745. }
  18746. function compressedTexImage2D() {
  18747. try {
  18748. gl.compressedTexImage2D.apply(gl, arguments);
  18749. } catch (error) {
  18750. console.error('THREE.WebGLState:', error);
  18751. }
  18752. }
  18753. function texImage2D() {
  18754. try {
  18755. gl.texImage2D.apply(gl, arguments);
  18756. } catch (error) {
  18757. console.error('THREE.WebGLState:', error);
  18758. }
  18759. }
  18760. function texImage3D() {
  18761. try {
  18762. gl.texImage3D.apply(gl, arguments);
  18763. } catch (error) {
  18764. console.error('THREE.WebGLState:', error);
  18765. }
  18766. } //
  18767. function scissor(scissor) {
  18768. if (currentScissor.equals(scissor) === false) {
  18769. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  18770. currentScissor.copy(scissor);
  18771. }
  18772. }
  18773. function viewport(viewport) {
  18774. if (currentViewport.equals(viewport) === false) {
  18775. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  18776. currentViewport.copy(viewport);
  18777. }
  18778. } //
  18779. function reset() {
  18780. enabledCapabilities = {};
  18781. currentTextureSlot = null;
  18782. currentBoundTextures = {};
  18783. currentProgram = null;
  18784. currentBlendingEnabled = null;
  18785. currentBlending = null;
  18786. currentBlendEquation = null;
  18787. currentBlendSrc = null;
  18788. currentBlendDst = null;
  18789. currentBlendEquationAlpha = null;
  18790. currentBlendSrcAlpha = null;
  18791. currentBlendDstAlpha = null;
  18792. currentPremultipledAlpha = false;
  18793. currentFlipSided = null;
  18794. currentCullFace = null;
  18795. currentLineWidth = null;
  18796. currentPolygonOffsetFactor = null;
  18797. currentPolygonOffsetUnits = null;
  18798. colorBuffer.reset();
  18799. depthBuffer.reset();
  18800. stencilBuffer.reset();
  18801. }
  18802. return {
  18803. buffers: {
  18804. color: colorBuffer,
  18805. depth: depthBuffer,
  18806. stencil: stencilBuffer
  18807. },
  18808. enable: enable,
  18809. disable: disable,
  18810. useProgram: useProgram,
  18811. setBlending: setBlending,
  18812. setMaterial: setMaterial,
  18813. setFlipSided: setFlipSided,
  18814. setCullFace: setCullFace,
  18815. setLineWidth: setLineWidth,
  18816. setPolygonOffset: setPolygonOffset,
  18817. setScissorTest: setScissorTest,
  18818. activeTexture: activeTexture,
  18819. bindTexture: bindTexture,
  18820. unbindTexture: unbindTexture,
  18821. compressedTexImage2D: compressedTexImage2D,
  18822. texImage2D: texImage2D,
  18823. texImage3D: texImage3D,
  18824. scissor: scissor,
  18825. viewport: viewport,
  18826. reset: reset
  18827. };
  18828. }
  18829. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  18830. var _wrappingToGL, _filterToGL;
  18831. var isWebGL2 = capabilities.isWebGL2;
  18832. var maxTextures = capabilities.maxTextures;
  18833. var maxCubemapSize = capabilities.maxCubemapSize;
  18834. var maxTextureSize = capabilities.maxTextureSize;
  18835. var maxSamples = capabilities.maxSamples;
  18836. var _videoTextures = new WeakMap();
  18837. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18838. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18839. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18840. var useOffscreenCanvas = false;
  18841. try {
  18842. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  18843. } catch (err) {// Ignore any errors
  18844. }
  18845. function createCanvas(width, height) {
  18846. // Use OffscreenCanvas when available. Specially needed in web workers
  18847. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  18848. }
  18849. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  18850. var scale = 1; // handle case if texture exceeds max size
  18851. if (image.width > maxSize || image.height > maxSize) {
  18852. scale = maxSize / Math.max(image.width, image.height);
  18853. } // only perform resize if necessary
  18854. if (scale < 1 || needsPowerOfTwo === true) {
  18855. // only perform resize for certain image types
  18856. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  18857. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  18858. var width = floor(scale * image.width);
  18859. var height = floor(scale * image.height);
  18860. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  18861. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  18862. canvas.width = width;
  18863. canvas.height = height;
  18864. var context = canvas.getContext('2d');
  18865. context.drawImage(image, 0, 0, width, height);
  18866. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  18867. return canvas;
  18868. } else {
  18869. if ('data' in image) {
  18870. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  18871. }
  18872. return image;
  18873. }
  18874. }
  18875. return image;
  18876. }
  18877. function isPowerOfTwo(image) {
  18878. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  18879. }
  18880. function textureNeedsPowerOfTwo(texture) {
  18881. if (isWebGL2) return false;
  18882. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18883. }
  18884. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  18885. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18886. }
  18887. function generateMipmap(target, texture, width, height) {
  18888. _gl.generateMipmap(target);
  18889. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18890. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  18891. }
  18892. function getInternalFormat(internalFormatName, glFormat, glType) {
  18893. if (isWebGL2 === false) return glFormat;
  18894. if (internalFormatName !== null) {
  18895. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  18896. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  18897. }
  18898. var internalFormat = glFormat;
  18899. if (glFormat === 6403) {
  18900. if (glType === 5126) internalFormat = 33326;
  18901. if (glType === 5131) internalFormat = 33325;
  18902. if (glType === 5121) internalFormat = 33321;
  18903. }
  18904. if (glFormat === 6407) {
  18905. if (glType === 5126) internalFormat = 34837;
  18906. if (glType === 5131) internalFormat = 34843;
  18907. if (glType === 5121) internalFormat = 32849;
  18908. }
  18909. if (glFormat === 6408) {
  18910. if (glType === 5126) internalFormat = 34836;
  18911. if (glType === 5131) internalFormat = 34842;
  18912. if (glType === 5121) internalFormat = 32856;
  18913. }
  18914. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  18915. extensions.get('EXT_color_buffer_float');
  18916. }
  18917. return internalFormat;
  18918. } // Fallback filters for non-power-of-2 textures
  18919. function filterFallback(f) {
  18920. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  18921. return 9728;
  18922. }
  18923. return 9729;
  18924. } //
  18925. function onTextureDispose(event) {
  18926. var texture = event.target;
  18927. texture.removeEventListener('dispose', onTextureDispose);
  18928. deallocateTexture(texture);
  18929. if (texture.isVideoTexture) {
  18930. _videoTextures.delete(texture);
  18931. }
  18932. info.memory.textures--;
  18933. }
  18934. function onRenderTargetDispose(event) {
  18935. var renderTarget = event.target;
  18936. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  18937. deallocateRenderTarget(renderTarget);
  18938. info.memory.textures--;
  18939. } //
  18940. function deallocateTexture(texture) {
  18941. var textureProperties = properties.get(texture);
  18942. if (textureProperties.__webglInit === undefined) return;
  18943. _gl.deleteTexture(textureProperties.__webglTexture);
  18944. properties.remove(texture);
  18945. }
  18946. function deallocateRenderTarget(renderTarget) {
  18947. var renderTargetProperties = properties.get(renderTarget);
  18948. var textureProperties = properties.get(renderTarget.texture);
  18949. if (!renderTarget) return;
  18950. if (textureProperties.__webglTexture !== undefined) {
  18951. _gl.deleteTexture(textureProperties.__webglTexture);
  18952. }
  18953. if (renderTarget.depthTexture) {
  18954. renderTarget.depthTexture.dispose();
  18955. }
  18956. if (renderTarget.isWebGLCubeRenderTarget) {
  18957. for (var i = 0; i < 6; i++) {
  18958. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  18959. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  18960. }
  18961. } else {
  18962. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  18963. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  18964. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  18965. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  18966. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  18967. }
  18968. properties.remove(renderTarget.texture);
  18969. properties.remove(renderTarget);
  18970. } //
  18971. var textureUnits = 0;
  18972. function resetTextureUnits() {
  18973. textureUnits = 0;
  18974. }
  18975. function allocateTextureUnit() {
  18976. var textureUnit = textureUnits;
  18977. if (textureUnit >= maxTextures) {
  18978. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  18979. }
  18980. textureUnits += 1;
  18981. return textureUnit;
  18982. } //
  18983. function setTexture2D(texture, slot) {
  18984. var textureProperties = properties.get(texture);
  18985. if (texture.isVideoTexture) updateVideoTexture(texture);
  18986. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18987. var image = texture.image;
  18988. if (image === undefined) {
  18989. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  18990. } else if (image.complete === false) {
  18991. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  18992. } else {
  18993. uploadTexture(textureProperties, texture, slot);
  18994. return;
  18995. }
  18996. }
  18997. state.activeTexture(33984 + slot);
  18998. state.bindTexture(3553, textureProperties.__webglTexture);
  18999. }
  19000. function setTexture2DArray(texture, slot) {
  19001. var textureProperties = properties.get(texture);
  19002. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19003. uploadTexture(textureProperties, texture, slot);
  19004. return;
  19005. }
  19006. state.activeTexture(33984 + slot);
  19007. state.bindTexture(35866, textureProperties.__webglTexture);
  19008. }
  19009. function setTexture3D(texture, slot) {
  19010. var textureProperties = properties.get(texture);
  19011. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19012. uploadTexture(textureProperties, texture, slot);
  19013. return;
  19014. }
  19015. state.activeTexture(33984 + slot);
  19016. state.bindTexture(32879, textureProperties.__webglTexture);
  19017. }
  19018. function setTextureCube(texture, slot) {
  19019. var textureProperties = properties.get(texture);
  19020. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19021. uploadCubeTexture(textureProperties, texture, slot);
  19022. return;
  19023. }
  19024. state.activeTexture(33984 + slot);
  19025. state.bindTexture(34067, textureProperties.__webglTexture);
  19026. }
  19027. var wrappingToGL = (_wrappingToGL = {}, _wrappingToGL[RepeatWrapping] = 10497, _wrappingToGL[ClampToEdgeWrapping] = 33071, _wrappingToGL[MirroredRepeatWrapping] = 33648, _wrappingToGL);
  19028. var filterToGL = (_filterToGL = {}, _filterToGL[NearestFilter] = 9728, _filterToGL[NearestMipmapNearestFilter] = 9984, _filterToGL[NearestMipmapLinearFilter] = 9986, _filterToGL[LinearFilter] = 9729, _filterToGL[LinearMipmapNearestFilter] = 9985, _filterToGL[LinearMipmapLinearFilter] = 9987, _filterToGL);
  19029. function setTextureParameters(textureType, texture, supportsMips) {
  19030. if (supportsMips) {
  19031. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  19032. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  19033. if (textureType === 32879 || textureType === 35866) {
  19034. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  19035. }
  19036. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  19037. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  19038. } else {
  19039. _gl.texParameteri(textureType, 10242, 33071);
  19040. _gl.texParameteri(textureType, 10243, 33071);
  19041. if (textureType === 32879 || textureType === 35866) {
  19042. _gl.texParameteri(textureType, 32882, 33071);
  19043. }
  19044. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  19045. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  19046. }
  19047. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  19048. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  19049. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  19050. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  19051. }
  19052. }
  19053. var extension = extensions.get('EXT_texture_filter_anisotropic');
  19054. if (extension) {
  19055. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  19056. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  19057. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  19058. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  19059. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  19060. }
  19061. }
  19062. }
  19063. function initTexture(textureProperties, texture) {
  19064. if (textureProperties.__webglInit === undefined) {
  19065. textureProperties.__webglInit = true;
  19066. texture.addEventListener('dispose', onTextureDispose);
  19067. textureProperties.__webglTexture = _gl.createTexture();
  19068. info.memory.textures++;
  19069. }
  19070. }
  19071. function uploadTexture(textureProperties, texture, slot) {
  19072. var textureType = 3553;
  19073. if (texture.isDataTexture2DArray) textureType = 35866;
  19074. if (texture.isDataTexture3D) textureType = 32879;
  19075. initTexture(textureProperties, texture);
  19076. state.activeTexture(33984 + slot);
  19077. state.bindTexture(textureType, textureProperties.__webglTexture);
  19078. _gl.pixelStorei(37440, texture.flipY);
  19079. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  19080. _gl.pixelStorei(3317, texture.unpackAlignment);
  19081. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  19082. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  19083. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  19084. glFormat = utils.convert(texture.format);
  19085. var glType = utils.convert(texture.type),
  19086. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  19087. setTextureParameters(textureType, texture, supportsMips);
  19088. var mipmap;
  19089. var mipmaps = texture.mipmaps;
  19090. if (texture.isDepthTexture) {
  19091. // populate depth texture with dummy data
  19092. glInternalFormat = 6402;
  19093. if (isWebGL2) {
  19094. if (texture.type === FloatType) {
  19095. glInternalFormat = 36012;
  19096. } else if (texture.type === UnsignedIntType) {
  19097. glInternalFormat = 33190;
  19098. } else if (texture.type === UnsignedInt248Type) {
  19099. glInternalFormat = 35056;
  19100. } else {
  19101. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  19102. }
  19103. } else {
  19104. if (texture.type === FloatType) {
  19105. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  19106. }
  19107. } // validation checks for WebGL 1
  19108. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  19109. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19110. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  19111. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19112. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  19113. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  19114. texture.type = UnsignedShortType;
  19115. glType = utils.convert(texture.type);
  19116. }
  19117. }
  19118. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  19119. // Depth stencil textures need the DEPTH_STENCIL internal format
  19120. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19121. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19122. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  19123. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19124. if (texture.type !== UnsignedInt248Type) {
  19125. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  19126. texture.type = UnsignedInt248Type;
  19127. glType = utils.convert(texture.type);
  19128. }
  19129. } //
  19130. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  19131. } else if (texture.isDataTexture) {
  19132. // use manually created mipmaps if available
  19133. // if there are no manual mipmaps
  19134. // set 0 level mipmap and then use GL to generate other mipmap levels
  19135. if (mipmaps.length > 0 && supportsMips) {
  19136. for (var i = 0, il = mipmaps.length; i < il; i++) {
  19137. mipmap = mipmaps[i];
  19138. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19139. }
  19140. texture.generateMipmaps = false;
  19141. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19142. } else {
  19143. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  19144. textureProperties.__maxMipLevel = 0;
  19145. }
  19146. } else if (texture.isCompressedTexture) {
  19147. for (var _i = 0, _il = mipmaps.length; _i < _il; _i++) {
  19148. mipmap = mipmaps[_i];
  19149. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19150. if (glFormat !== null) {
  19151. state.compressedTexImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19152. } else {
  19153. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  19154. }
  19155. } else {
  19156. state.texImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19157. }
  19158. }
  19159. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19160. } else if (texture.isDataTexture2DArray) {
  19161. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19162. textureProperties.__maxMipLevel = 0;
  19163. } else if (texture.isDataTexture3D) {
  19164. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19165. textureProperties.__maxMipLevel = 0;
  19166. } else {
  19167. // regular Texture (image, video, canvas)
  19168. // use manually created mipmaps if available
  19169. // if there are no manual mipmaps
  19170. // set 0 level mipmap and then use GL to generate other mipmap levels
  19171. if (mipmaps.length > 0 && supportsMips) {
  19172. for (var _i2 = 0, _il2 = mipmaps.length; _i2 < _il2; _i2++) {
  19173. mipmap = mipmaps[_i2];
  19174. state.texImage2D(3553, _i2, glInternalFormat, glFormat, glType, mipmap);
  19175. }
  19176. texture.generateMipmaps = false;
  19177. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19178. } else {
  19179. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  19180. textureProperties.__maxMipLevel = 0;
  19181. }
  19182. }
  19183. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19184. generateMipmap(textureType, texture, image.width, image.height);
  19185. }
  19186. textureProperties.__version = texture.version;
  19187. if (texture.onUpdate) texture.onUpdate(texture);
  19188. }
  19189. function uploadCubeTexture(textureProperties, texture, slot) {
  19190. if (texture.image.length !== 6) return;
  19191. initTexture(textureProperties, texture);
  19192. state.activeTexture(33984 + slot);
  19193. state.bindTexture(34067, textureProperties.__webglTexture);
  19194. _gl.pixelStorei(37440, texture.flipY);
  19195. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  19196. _gl.pixelStorei(3317, texture.unpackAlignment);
  19197. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  19198. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  19199. var cubeImage = [];
  19200. for (var i = 0; i < 6; i++) {
  19201. if (!isCompressed && !isDataTexture) {
  19202. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  19203. } else {
  19204. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  19205. }
  19206. }
  19207. var image = cubeImage[0],
  19208. supportsMips = isPowerOfTwo(image) || isWebGL2,
  19209. glFormat = utils.convert(texture.format),
  19210. glType = utils.convert(texture.type),
  19211. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  19212. setTextureParameters(34067, texture, supportsMips);
  19213. var mipmaps;
  19214. if (isCompressed) {
  19215. for (var _i3 = 0; _i3 < 6; _i3++) {
  19216. mipmaps = cubeImage[_i3].mipmaps;
  19217. for (var j = 0; j < mipmaps.length; j++) {
  19218. var mipmap = mipmaps[j];
  19219. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19220. if (glFormat !== null) {
  19221. state.compressedTexImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19222. } else {
  19223. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  19224. }
  19225. } else {
  19226. state.texImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19227. }
  19228. }
  19229. }
  19230. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19231. } else {
  19232. mipmaps = texture.mipmaps;
  19233. for (var _i4 = 0; _i4 < 6; _i4++) {
  19234. if (isDataTexture) {
  19235. state.texImage2D(34069 + _i4, 0, glInternalFormat, cubeImage[_i4].width, cubeImage[_i4].height, 0, glFormat, glType, cubeImage[_i4].data);
  19236. for (var _j = 0; _j < mipmaps.length; _j++) {
  19237. var _mipmap = mipmaps[_j];
  19238. var mipmapImage = _mipmap.image[_i4].image;
  19239. state.texImage2D(34069 + _i4, _j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  19240. }
  19241. } else {
  19242. state.texImage2D(34069 + _i4, 0, glInternalFormat, glFormat, glType, cubeImage[_i4]);
  19243. for (var _j2 = 0; _j2 < mipmaps.length; _j2++) {
  19244. var _mipmap2 = mipmaps[_j2];
  19245. state.texImage2D(34069 + _i4, _j2 + 1, glInternalFormat, glFormat, glType, _mipmap2.image[_i4]);
  19246. }
  19247. }
  19248. }
  19249. textureProperties.__maxMipLevel = mipmaps.length;
  19250. }
  19251. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19252. // We assume images for cube map have the same size.
  19253. generateMipmap(34067, texture, image.width, image.height);
  19254. }
  19255. textureProperties.__version = texture.version;
  19256. if (texture.onUpdate) texture.onUpdate(texture);
  19257. } // Render targets
  19258. // Setup storage for target texture and bind it to correct framebuffer
  19259. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  19260. var glFormat = utils.convert(renderTarget.texture.format);
  19261. var glType = utils.convert(renderTarget.texture.type);
  19262. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19263. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  19264. _gl.bindFramebuffer(36160, framebuffer);
  19265. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  19266. _gl.bindFramebuffer(36160, null);
  19267. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19268. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  19269. _gl.bindRenderbuffer(36161, renderbuffer);
  19270. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  19271. var glInternalFormat = 33189;
  19272. if (isMultisample) {
  19273. var depthTexture = renderTarget.depthTexture;
  19274. if (depthTexture && depthTexture.isDepthTexture) {
  19275. if (depthTexture.type === FloatType) {
  19276. glInternalFormat = 36012;
  19277. } else if (depthTexture.type === UnsignedIntType) {
  19278. glInternalFormat = 33190;
  19279. }
  19280. }
  19281. var samples = getRenderTargetSamples(renderTarget);
  19282. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19283. } else {
  19284. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  19285. }
  19286. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  19287. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  19288. if (isMultisample) {
  19289. var _samples = getRenderTargetSamples(renderTarget);
  19290. _gl.renderbufferStorageMultisample(36161, _samples, 35056, renderTarget.width, renderTarget.height);
  19291. } else {
  19292. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  19293. }
  19294. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  19295. } else {
  19296. var glFormat = utils.convert(renderTarget.texture.format);
  19297. var glType = utils.convert(renderTarget.texture.type);
  19298. var _glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19299. if (isMultisample) {
  19300. var _samples2 = getRenderTargetSamples(renderTarget);
  19301. _gl.renderbufferStorageMultisample(36161, _samples2, _glInternalFormat, renderTarget.width, renderTarget.height);
  19302. } else {
  19303. _gl.renderbufferStorage(36161, _glInternalFormat, renderTarget.width, renderTarget.height);
  19304. }
  19305. }
  19306. _gl.bindRenderbuffer(36161, null);
  19307. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  19308. function setupDepthTexture(framebuffer, renderTarget) {
  19309. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  19310. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  19311. _gl.bindFramebuffer(36160, framebuffer);
  19312. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  19313. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  19314. } // upload an empty depth texture with framebuffer size
  19315. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  19316. renderTarget.depthTexture.image.width = renderTarget.width;
  19317. renderTarget.depthTexture.image.height = renderTarget.height;
  19318. renderTarget.depthTexture.needsUpdate = true;
  19319. }
  19320. setTexture2D(renderTarget.depthTexture, 0);
  19321. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  19322. if (renderTarget.depthTexture.format === DepthFormat) {
  19323. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  19324. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  19325. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  19326. } else {
  19327. throw new Error('Unknown depthTexture format');
  19328. }
  19329. } // Setup GL resources for a non-texture depth buffer
  19330. function setupDepthRenderbuffer(renderTarget) {
  19331. var renderTargetProperties = properties.get(renderTarget);
  19332. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19333. if (renderTarget.depthTexture) {
  19334. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  19335. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  19336. } else {
  19337. if (isCube) {
  19338. renderTargetProperties.__webglDepthbuffer = [];
  19339. for (var i = 0; i < 6; i++) {
  19340. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  19341. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  19342. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  19343. }
  19344. } else {
  19345. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  19346. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  19347. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  19348. }
  19349. }
  19350. _gl.bindFramebuffer(36160, null);
  19351. } // Set up GL resources for the render target
  19352. function setupRenderTarget(renderTarget) {
  19353. var renderTargetProperties = properties.get(renderTarget);
  19354. var textureProperties = properties.get(renderTarget.texture);
  19355. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  19356. textureProperties.__webglTexture = _gl.createTexture();
  19357. info.memory.textures++;
  19358. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19359. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  19360. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  19361. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  19362. renderTarget.texture.format = RGBAFormat;
  19363. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  19364. } // Setup framebuffer
  19365. if (isCube) {
  19366. renderTargetProperties.__webglFramebuffer = [];
  19367. for (var i = 0; i < 6; i++) {
  19368. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  19369. }
  19370. } else {
  19371. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  19372. if (isMultisample) {
  19373. if (isWebGL2) {
  19374. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  19375. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  19376. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  19377. var glFormat = utils.convert(renderTarget.texture.format);
  19378. var glType = utils.convert(renderTarget.texture.type);
  19379. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19380. var samples = getRenderTargetSamples(renderTarget);
  19381. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19382. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  19383. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  19384. _gl.bindRenderbuffer(36161, null);
  19385. if (renderTarget.depthBuffer) {
  19386. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  19387. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  19388. }
  19389. _gl.bindFramebuffer(36160, null);
  19390. } else {
  19391. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19392. }
  19393. }
  19394. } // Setup color buffer
  19395. if (isCube) {
  19396. state.bindTexture(34067, textureProperties.__webglTexture);
  19397. setTextureParameters(34067, renderTarget.texture, supportsMips);
  19398. for (var _i5 = 0; _i5 < 6; _i5++) {
  19399. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i5], renderTarget, 36064, 34069 + _i5);
  19400. }
  19401. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  19402. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  19403. }
  19404. state.bindTexture(34067, null);
  19405. } else {
  19406. state.bindTexture(3553, textureProperties.__webglTexture);
  19407. setTextureParameters(3553, renderTarget.texture, supportsMips);
  19408. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  19409. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  19410. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  19411. }
  19412. state.bindTexture(3553, null);
  19413. } // Setup depth and stencil buffers
  19414. if (renderTarget.depthBuffer) {
  19415. setupDepthRenderbuffer(renderTarget);
  19416. }
  19417. }
  19418. function updateRenderTargetMipmap(renderTarget) {
  19419. var texture = renderTarget.texture;
  19420. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  19421. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19422. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  19423. var webglTexture = properties.get(texture).__webglTexture;
  19424. state.bindTexture(target, webglTexture);
  19425. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  19426. state.bindTexture(target, null);
  19427. }
  19428. }
  19429. function updateMultisampleRenderTarget(renderTarget) {
  19430. if (renderTarget.isWebGLMultisampleRenderTarget) {
  19431. if (isWebGL2) {
  19432. var renderTargetProperties = properties.get(renderTarget);
  19433. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  19434. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  19435. var width = renderTarget.width;
  19436. var height = renderTarget.height;
  19437. var mask = 16384;
  19438. if (renderTarget.depthBuffer) mask |= 256;
  19439. if (renderTarget.stencilBuffer) mask |= 1024;
  19440. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  19441. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  19442. } else {
  19443. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19444. }
  19445. }
  19446. }
  19447. function getRenderTargetSamples(renderTarget) {
  19448. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  19449. }
  19450. function updateVideoTexture(texture) {
  19451. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  19452. if (_videoTextures.get(texture) !== frame) {
  19453. _videoTextures.set(texture, frame);
  19454. texture.update();
  19455. }
  19456. } // backwards compatibility
  19457. var warnedTexture2D = false;
  19458. var warnedTextureCube = false;
  19459. function safeSetTexture2D(texture, slot) {
  19460. if (texture && texture.isWebGLRenderTarget) {
  19461. if (warnedTexture2D === false) {
  19462. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  19463. warnedTexture2D = true;
  19464. }
  19465. texture = texture.texture;
  19466. }
  19467. setTexture2D(texture, slot);
  19468. }
  19469. function safeSetTextureCube(texture, slot) {
  19470. if (texture && texture.isWebGLCubeRenderTarget) {
  19471. if (warnedTextureCube === false) {
  19472. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  19473. warnedTextureCube = true;
  19474. }
  19475. texture = texture.texture;
  19476. }
  19477. setTextureCube(texture, slot);
  19478. } //
  19479. this.allocateTextureUnit = allocateTextureUnit;
  19480. this.resetTextureUnits = resetTextureUnits;
  19481. this.setTexture2D = setTexture2D;
  19482. this.setTexture2DArray = setTexture2DArray;
  19483. this.setTexture3D = setTexture3D;
  19484. this.setTextureCube = setTextureCube;
  19485. this.setupRenderTarget = setupRenderTarget;
  19486. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19487. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19488. this.safeSetTexture2D = safeSetTexture2D;
  19489. this.safeSetTextureCube = safeSetTextureCube;
  19490. }
  19491. function WebGLUtils(gl, extensions, capabilities) {
  19492. var isWebGL2 = capabilities.isWebGL2;
  19493. function convert(p) {
  19494. var extension;
  19495. if (p === UnsignedByteType) return 5121;
  19496. if (p === UnsignedShort4444Type) return 32819;
  19497. if (p === UnsignedShort5551Type) return 32820;
  19498. if (p === UnsignedShort565Type) return 33635;
  19499. if (p === ByteType) return 5120;
  19500. if (p === ShortType) return 5122;
  19501. if (p === UnsignedShortType) return 5123;
  19502. if (p === IntType) return 5124;
  19503. if (p === UnsignedIntType) return 5125;
  19504. if (p === FloatType) return 5126;
  19505. if (p === HalfFloatType) {
  19506. if (isWebGL2) return 5131;
  19507. extension = extensions.get('OES_texture_half_float');
  19508. if (extension !== null) {
  19509. return extension.HALF_FLOAT_OES;
  19510. } else {
  19511. return null;
  19512. }
  19513. }
  19514. if (p === AlphaFormat) return 6406;
  19515. if (p === RGBFormat) return 6407;
  19516. if (p === RGBAFormat) return 6408;
  19517. if (p === LuminanceFormat) return 6409;
  19518. if (p === LuminanceAlphaFormat) return 6410;
  19519. if (p === DepthFormat) return 6402;
  19520. if (p === DepthStencilFormat) return 34041;
  19521. if (p === RedFormat) return 6403; // WebGL2 formats.
  19522. if (p === RedIntegerFormat) return 36244;
  19523. if (p === RGFormat) return 33319;
  19524. if (p === RGIntegerFormat) return 33320;
  19525. if (p === RGBIntegerFormat) return 36248;
  19526. if (p === RGBAIntegerFormat) return 36249;
  19527. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  19528. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  19529. if (extension !== null) {
  19530. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19531. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19532. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19533. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19534. } else {
  19535. return null;
  19536. }
  19537. }
  19538. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  19539. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  19540. if (extension !== null) {
  19541. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19542. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19543. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19544. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19545. } else {
  19546. return null;
  19547. }
  19548. }
  19549. if (p === RGB_ETC1_Format) {
  19550. extension = extensions.get('WEBGL_compressed_texture_etc1');
  19551. if (extension !== null) {
  19552. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19553. } else {
  19554. return null;
  19555. }
  19556. }
  19557. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  19558. extension = extensions.get('WEBGL_compressed_texture_etc');
  19559. if (extension !== null) {
  19560. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  19561. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  19562. }
  19563. }
  19564. 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) {
  19565. extension = extensions.get('WEBGL_compressed_texture_astc');
  19566. if (extension !== null) {
  19567. // TODO Complete?
  19568. return p;
  19569. } else {
  19570. return null;
  19571. }
  19572. }
  19573. if (p === RGBA_BPTC_Format) {
  19574. extension = extensions.get('EXT_texture_compression_bptc');
  19575. if (extension !== null) {
  19576. // TODO Complete?
  19577. return p;
  19578. } else {
  19579. return null;
  19580. }
  19581. }
  19582. if (p === UnsignedInt248Type) {
  19583. if (isWebGL2) return 34042;
  19584. extension = extensions.get('WEBGL_depth_texture');
  19585. if (extension !== null) {
  19586. return extension.UNSIGNED_INT_24_8_WEBGL;
  19587. } else {
  19588. return null;
  19589. }
  19590. }
  19591. }
  19592. return {
  19593. convert: convert
  19594. };
  19595. }
  19596. function Group() {
  19597. Object3D.call(this);
  19598. this.type = 'Group';
  19599. }
  19600. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  19601. constructor: Group,
  19602. isGroup: true
  19603. });
  19604. function ArrayCamera(array) {
  19605. if (array === void 0) {
  19606. array = [];
  19607. }
  19608. PerspectiveCamera.call(this);
  19609. this.cameras = array;
  19610. }
  19611. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  19612. constructor: ArrayCamera,
  19613. isArrayCamera: true
  19614. });
  19615. /**
  19616. * @author jsantell / https://www.jsantell.com/
  19617. * @author mrdoob / http://mrdoob.com/
  19618. */
  19619. var cameraLPos = new Vector3();
  19620. var cameraRPos = new Vector3();
  19621. /**
  19622. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19623. * the cameras' projection and world matrices have already been set.
  19624. * And that near and far planes are identical for both cameras.
  19625. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19626. */
  19627. function setProjectionFromUnion(camera, cameraL, cameraR) {
  19628. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  19629. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  19630. var ipd = cameraLPos.distanceTo(cameraRPos);
  19631. var projL = cameraL.projectionMatrix.elements;
  19632. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  19633. // most likely identical top and bottom frustum extents.
  19634. // Use the left camera for these values.
  19635. var near = projL[14] / (projL[10] - 1);
  19636. var far = projL[14] / (projL[10] + 1);
  19637. var topFov = (projL[9] + 1) / projL[5];
  19638. var bottomFov = (projL[9] - 1) / projL[5];
  19639. var leftFov = (projL[8] - 1) / projL[0];
  19640. var rightFov = (projR[8] + 1) / projR[0];
  19641. var left = near * leftFov;
  19642. var right = near * rightFov; // Calculate the new camera's position offset from the
  19643. // left camera. xOffset should be roughly half `ipd`.
  19644. var zOffset = ipd / (-leftFov + rightFov);
  19645. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  19646. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  19647. camera.translateX(xOffset);
  19648. camera.translateZ(zOffset);
  19649. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  19650. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  19651. // the values so that the near plane's position does not change in world space,
  19652. // although must now be relative to the new union camera.
  19653. var near2 = near + zOffset;
  19654. var far2 = far + zOffset;
  19655. var left2 = left - xOffset;
  19656. var right2 = right + (ipd - xOffset);
  19657. var top2 = topFov * far / far2 * near2;
  19658. var bottom2 = bottomFov * far / far2 * near2;
  19659. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  19660. }
  19661. /**
  19662. * @author mrdoob / http://mrdoob.com/
  19663. */
  19664. function WebVRManager(renderer) {
  19665. var renderWidth, renderHeight;
  19666. var scope = this;
  19667. var device = null;
  19668. var frameData = null;
  19669. var poseTarget = null;
  19670. var controllers = [];
  19671. var standingMatrix = new Matrix4();
  19672. var standingMatrixInverse = new Matrix4();
  19673. var framebufferScaleFactor = 1.0;
  19674. var referenceSpaceType = 'local-floor';
  19675. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  19676. frameData = new window.VRFrameData();
  19677. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  19678. }
  19679. var matrixWorldInverse = new Matrix4();
  19680. var tempQuaternion = new Quaternion();
  19681. var tempPosition = new Vector3();
  19682. var cameraL = new PerspectiveCamera();
  19683. cameraL.viewport = new Vector4();
  19684. cameraL.layers.enable(1);
  19685. var cameraR = new PerspectiveCamera();
  19686. cameraR.viewport = new Vector4();
  19687. cameraR.layers.enable(2);
  19688. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  19689. cameraVR.layers.enable(1);
  19690. cameraVR.layers.enable(2);
  19691. var currentSize = new Vector2(),
  19692. currentPixelRatio;
  19693. function onVRDisplayPresentChange() {
  19694. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19695. if (isPresenting) {
  19696. var eyeParameters = device.getEyeParameters('left');
  19697. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19698. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19699. currentPixelRatio = renderer.getPixelRatio();
  19700. renderer.getSize(currentSize);
  19701. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  19702. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  19703. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  19704. animation.start();
  19705. scope.dispatchEvent({
  19706. type: 'sessionstart'
  19707. });
  19708. } else {
  19709. if (scope.enabled) {
  19710. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  19711. }
  19712. animation.stop();
  19713. scope.dispatchEvent({
  19714. type: 'sessionend'
  19715. });
  19716. }
  19717. } //
  19718. var triggers = [];
  19719. var grips = [];
  19720. function findGamepad(id) {
  19721. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19722. for (var i = 0, l = gamepads.length; i < l; i++) {
  19723. var gamepad = gamepads[i];
  19724. 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'))) {
  19725. var hand = gamepad.hand;
  19726. if (id === 0 && (hand === '' || hand === 'right')) return gamepad;
  19727. if (id === 1 && hand === 'left') return gamepad;
  19728. }
  19729. }
  19730. }
  19731. function updateControllers() {
  19732. for (var i = 0; i < controllers.length; i++) {
  19733. var controller = controllers[i];
  19734. var gamepad = findGamepad(i);
  19735. if (gamepad !== undefined && gamepad.pose !== undefined) {
  19736. if (gamepad.pose === null) return; // Pose
  19737. var pose = gamepad.pose;
  19738. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  19739. if (pose.position !== null) controller.position.fromArray(pose.position);
  19740. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  19741. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  19742. controller.matrix.premultiply(standingMatrix);
  19743. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  19744. controller.matrixWorldNeedsUpdate = true;
  19745. controller.visible = true; // Trigger
  19746. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19747. if (triggers[i] === undefined) triggers[i] = false;
  19748. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  19749. triggers[i] = gamepad.buttons[buttonId].pressed;
  19750. if (triggers[i] === true) {
  19751. controller.dispatchEvent({
  19752. type: 'selectstart'
  19753. });
  19754. } else {
  19755. controller.dispatchEvent({
  19756. type: 'selectend'
  19757. });
  19758. controller.dispatchEvent({
  19759. type: 'select'
  19760. });
  19761. }
  19762. } // Grip
  19763. buttonId = 2;
  19764. if (grips[i] === undefined) grips[i] = false; // Skip if the grip button doesn't exist on this controller
  19765. if (gamepad.buttons[buttonId] !== undefined) {
  19766. if (grips[i] !== gamepad.buttons[buttonId].pressed) {
  19767. grips[i] = gamepad.buttons[buttonId].pressed;
  19768. if (grips[i] === true) {
  19769. controller.dispatchEvent({
  19770. type: 'squeezestart'
  19771. });
  19772. } else {
  19773. controller.dispatchEvent({
  19774. type: 'squeezeend'
  19775. });
  19776. controller.dispatchEvent({
  19777. type: 'squeeze'
  19778. });
  19779. }
  19780. }
  19781. }
  19782. } else {
  19783. controller.visible = false;
  19784. }
  19785. }
  19786. }
  19787. function updateViewportFromBounds(viewport, bounds) {
  19788. if (bounds !== null && bounds.length === 4) {
  19789. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  19790. }
  19791. } //
  19792. this.enabled = false;
  19793. this.getController = function (id) {
  19794. var controller = controllers[id];
  19795. if (controller === undefined) {
  19796. controller = new Group();
  19797. controller.matrixAutoUpdate = false;
  19798. controller.visible = false;
  19799. controllers[id] = controller;
  19800. }
  19801. return controller;
  19802. };
  19803. this.getDevice = function () {
  19804. return device;
  19805. };
  19806. this.setDevice = function (value) {
  19807. if (value !== undefined) device = value;
  19808. animation.setContext(value);
  19809. };
  19810. this.setFramebufferScaleFactor = function (value) {
  19811. framebufferScaleFactor = value;
  19812. };
  19813. this.setReferenceSpaceType = function (value) {
  19814. referenceSpaceType = value;
  19815. };
  19816. this.setPoseTarget = function (object) {
  19817. if (object !== undefined) poseTarget = object;
  19818. };
  19819. this.getCamera = function (camera) {
  19820. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19821. device.depthNear = camera.near;
  19822. device.depthFar = camera.far;
  19823. device.getFrameData(frameData); //
  19824. if (referenceSpaceType === 'local-floor') {
  19825. var stageParameters = device.stageParameters;
  19826. if (stageParameters) {
  19827. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  19828. } else {
  19829. standingMatrix.makeTranslation(0, userHeight, 0);
  19830. }
  19831. }
  19832. var pose = frameData.pose;
  19833. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19834. poseObject.matrix.copy(standingMatrix);
  19835. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  19836. if (pose.orientation !== null) {
  19837. tempQuaternion.fromArray(pose.orientation);
  19838. poseObject.quaternion.multiply(tempQuaternion);
  19839. }
  19840. if (pose.position !== null) {
  19841. tempQuaternion.setFromRotationMatrix(standingMatrix);
  19842. tempPosition.fromArray(pose.position);
  19843. tempPosition.applyQuaternion(tempQuaternion);
  19844. poseObject.position.add(tempPosition);
  19845. }
  19846. poseObject.updateMatrixWorld();
  19847. var children = poseObject.children;
  19848. for (var i = 0, l = children.length; i < l; i++) {
  19849. children[i].updateMatrixWorld(true);
  19850. } //
  19851. cameraL.near = camera.near;
  19852. cameraR.near = camera.near;
  19853. cameraL.far = camera.far;
  19854. cameraR.far = camera.far;
  19855. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  19856. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  19857. standingMatrixInverse.getInverse(standingMatrix);
  19858. if (referenceSpaceType === 'local-floor') {
  19859. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  19860. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  19861. }
  19862. var parent = poseObject.parent;
  19863. if (parent !== null) {
  19864. matrixWorldInverse.getInverse(parent.matrixWorld);
  19865. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  19866. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  19867. } // envMap and Mirror needs camera.matrixWorld
  19868. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  19869. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  19870. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  19871. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  19872. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  19873. var layers = device.getLayers();
  19874. if (layers.length) {
  19875. var layer = layers[0];
  19876. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  19877. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  19878. }
  19879. updateControllers();
  19880. return cameraVR;
  19881. };
  19882. this.getStandingMatrix = function () {
  19883. return standingMatrix;
  19884. };
  19885. this.isPresenting = false; // Animation Loop
  19886. var animation = new WebGLAnimation();
  19887. this.setAnimationLoop = function (callback) {
  19888. animation.setAnimationLoop(callback);
  19889. if (this.isPresenting) animation.start();
  19890. };
  19891. this.submitFrame = function () {
  19892. if (this.isPresenting) device.submitFrame();
  19893. };
  19894. this.dispose = function () {
  19895. if (typeof window !== 'undefined') {
  19896. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  19897. }
  19898. }; // DEPRECATED
  19899. this.setFrameOfReferenceType = function () {
  19900. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  19901. };
  19902. }
  19903. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  19904. function WebXRController() {
  19905. this._targetRay = null;
  19906. this._grip = null;
  19907. this._hand = null;
  19908. }
  19909. Object.assign(WebXRController.prototype, {
  19910. constructor: WebXRController,
  19911. getHandSpace: function getHandSpace() {
  19912. if (this._hand === null) {
  19913. this._hand = new Group();
  19914. this._hand.matrixAutoUpdate = false;
  19915. this._hand.visible = false;
  19916. this._hand.joints = {};
  19917. this._hand.inputState = {
  19918. pinching: false
  19919. };
  19920. }
  19921. return this._hand;
  19922. },
  19923. getTargetRaySpace: function getTargetRaySpace() {
  19924. if (this._targetRay === null) {
  19925. this._targetRay = new Group();
  19926. this._targetRay.matrixAutoUpdate = false;
  19927. this._targetRay.visible = false;
  19928. }
  19929. return this._targetRay;
  19930. },
  19931. getGripSpace: function getGripSpace() {
  19932. if (this._grip === null) {
  19933. this._grip = new Group();
  19934. this._grip.matrixAutoUpdate = false;
  19935. this._grip.visible = false;
  19936. }
  19937. return this._grip;
  19938. },
  19939. dispatchEvent: function dispatchEvent(event) {
  19940. if (this._targetRay !== null) {
  19941. this._targetRay.dispatchEvent(event);
  19942. }
  19943. if (this._grip !== null) {
  19944. this._grip.dispatchEvent(event);
  19945. }
  19946. if (this._hand !== null) {
  19947. this._hand.dispatchEvent(event);
  19948. }
  19949. return this;
  19950. },
  19951. disconnect: function disconnect(inputSource) {
  19952. this.dispatchEvent({
  19953. type: 'disconnected',
  19954. data: inputSource
  19955. });
  19956. if (this._targetRay !== null) {
  19957. this._targetRay.visible = false;
  19958. }
  19959. if (this._grip !== null) {
  19960. this._grip.visible = false;
  19961. }
  19962. if (this._hand !== null) {
  19963. this._hand.visible = false;
  19964. }
  19965. return this;
  19966. },
  19967. update: function update(inputSource, frame, referenceSpace) {
  19968. var inputPose = null;
  19969. var gripPose = null;
  19970. var handPose = null;
  19971. var targetRay = this._targetRay;
  19972. var grip = this._grip;
  19973. var hand = this._hand;
  19974. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  19975. if (hand && inputSource.hand) {
  19976. handPose = true;
  19977. for (var _iterator = _createForOfIteratorHelperLoose(inputSource.hand.values()), _step; !(_step = _iterator()).done;) {
  19978. var inputjoint = _step.value;
  19979. // Update the joints groups with the XRJoint poses
  19980. var jointPose = frame.getJointPose(inputjoint, referenceSpace);
  19981. if (hand.joints[inputjoint.jointName] === undefined) {
  19982. // The transform of this joint will be updated with the joint pose on each frame
  19983. var _joint = new Group();
  19984. _joint.matrixAutoUpdate = false;
  19985. _joint.visible = false;
  19986. hand.joints[inputjoint.jointName] = _joint; // ??
  19987. hand.add(_joint);
  19988. }
  19989. var joint = hand.joints[inputjoint.jointName];
  19990. if (jointPose !== null) {
  19991. joint.matrix.fromArray(jointPose.transform.matrix);
  19992. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  19993. joint.jointRadius = jointPose.radius;
  19994. }
  19995. joint.visible = jointPose !== null;
  19996. } // Custom events
  19997. // Check pinchz
  19998. var indexTip = hand.joints['index-finger-tip'];
  19999. var thumbTip = hand.joints['thumb-tip'];
  20000. var distance = indexTip.position.distanceTo(thumbTip.position);
  20001. var distanceToPinch = 0.02;
  20002. var threshold = 0.005;
  20003. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  20004. hand.inputState.pinching = false;
  20005. this.dispatchEvent({
  20006. type: 'pinchend',
  20007. handedness: inputSource.handedness,
  20008. target: this
  20009. });
  20010. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  20011. hand.inputState.pinching = true;
  20012. this.dispatchEvent({
  20013. type: 'pinchstart',
  20014. handedness: inputSource.handedness,
  20015. target: this
  20016. });
  20017. }
  20018. } else {
  20019. if (targetRay !== null) {
  20020. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  20021. if (inputPose !== null) {
  20022. targetRay.matrix.fromArray(inputPose.transform.matrix);
  20023. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  20024. }
  20025. }
  20026. if (grip !== null && inputSource.gripSpace) {
  20027. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  20028. if (gripPose !== null) {
  20029. grip.matrix.fromArray(gripPose.transform.matrix);
  20030. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  20031. }
  20032. }
  20033. }
  20034. }
  20035. if (targetRay !== null) {
  20036. targetRay.visible = inputPose !== null;
  20037. }
  20038. if (grip !== null) {
  20039. grip.visible = gripPose !== null;
  20040. }
  20041. if (hand !== null) {
  20042. hand.visible = handPose !== null;
  20043. }
  20044. return this;
  20045. }
  20046. });
  20047. function WebXRManager(renderer, gl) {
  20048. var scope = this;
  20049. var session = null;
  20050. var framebufferScaleFactor = 1.0;
  20051. var referenceSpace = null;
  20052. var referenceSpaceType = 'local-floor';
  20053. var pose = null;
  20054. var poseTarget = null;
  20055. var controllers = [];
  20056. var inputSourcesMap = new Map();
  20057. var layers = [];
  20058. var baseLayer; //
  20059. var cameraL = new PerspectiveCamera();
  20060. cameraL.layers.enable(1);
  20061. cameraL.viewport = new Vector4();
  20062. var cameraR = new PerspectiveCamera();
  20063. cameraR.layers.enable(2);
  20064. cameraR.viewport = new Vector4();
  20065. var cameras = [cameraL, cameraR];
  20066. var cameraVR = new ArrayCamera();
  20067. cameraVR.layers.enable(1);
  20068. cameraVR.layers.enable(2);
  20069. var _currentDepthNear = null;
  20070. var _currentDepthFar = null; //
  20071. this.layersEnabled = false;
  20072. this.enabled = false;
  20073. this.isPresenting = false;
  20074. this.getCameraPose = function () {
  20075. return pose;
  20076. };
  20077. this.getController = function (index) {
  20078. var controller = controllers[index];
  20079. if (controller === undefined) {
  20080. controller = new WebXRController();
  20081. controllers[index] = controller;
  20082. }
  20083. return controller.getTargetRaySpace();
  20084. };
  20085. this.getControllerGrip = function (index) {
  20086. var controller = controllers[index];
  20087. if (controller === undefined) {
  20088. controller = new WebXRController();
  20089. controllers[index] = controller;
  20090. }
  20091. return controller.getGripSpace();
  20092. };
  20093. this.getHand = function (index) {
  20094. var controller = controllers[index];
  20095. if (controller === undefined) {
  20096. controller = new WebXRController();
  20097. controllers[index] = controller;
  20098. }
  20099. return controller.getHandSpace();
  20100. }; //
  20101. function onSessionEvent(event) {
  20102. var controller = inputSourcesMap.get(event.inputSource);
  20103. if (controller) {
  20104. controller.dispatchEvent({
  20105. type: event.type,
  20106. data: event.inputSource
  20107. });
  20108. }
  20109. }
  20110. function onSessionEnd() {
  20111. inputSourcesMap.forEach(function (controller, inputSource) {
  20112. controller.disconnect(inputSource);
  20113. });
  20114. inputSourcesMap.clear();
  20115. _currentDepthNear = null;
  20116. _currentDepthFar = null; //
  20117. renderer.setFramebuffer(null);
  20118. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  20119. animation.stop();
  20120. scope.isPresenting = false;
  20121. scope.dispatchEvent({
  20122. type: 'sessionend'
  20123. });
  20124. }
  20125. this.setFramebufferScaleFactor = function (value) {
  20126. framebufferScaleFactor = value;
  20127. if (scope.isPresenting === true) {
  20128. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  20129. }
  20130. };
  20131. this.setReferenceSpaceType = function (value) {
  20132. referenceSpaceType = value;
  20133. if (scope.isPresenting === true) {
  20134. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  20135. }
  20136. };
  20137. this.getReferenceSpace = function () {
  20138. return referenceSpace;
  20139. };
  20140. this.getSession = function () {
  20141. return session;
  20142. };
  20143. this.setSession = /*#__PURE__*/function () {
  20144. var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {
  20145. var attributes, layerInit;
  20146. return regeneratorRuntime.wrap(function _callee$(_context) {
  20147. while (1) {
  20148. switch (_context.prev = _context.next) {
  20149. case 0:
  20150. session = value;
  20151. if (!(session !== null)) {
  20152. _context.next = 24;
  20153. break;
  20154. }
  20155. session.addEventListener('select', onSessionEvent);
  20156. session.addEventListener('selectstart', onSessionEvent);
  20157. session.addEventListener('selectend', onSessionEvent);
  20158. session.addEventListener('squeeze', onSessionEvent);
  20159. session.addEventListener('squeezestart', onSessionEvent);
  20160. session.addEventListener('squeezeend', onSessionEvent);
  20161. session.addEventListener('end', onSessionEnd);
  20162. session.addEventListener('inputsourceschange', onInputSourcesChange);
  20163. attributes = gl.getContextAttributes();
  20164. if (!(attributes.xrCompatible !== true)) {
  20165. _context.next = 14;
  20166. break;
  20167. }
  20168. _context.next = 14;
  20169. return gl.makeXRCompatible();
  20170. case 14:
  20171. layerInit = {
  20172. antialias: attributes.antialias,
  20173. alpha: attributes.alpha,
  20174. depth: attributes.depth,
  20175. stencil: attributes.stencil,
  20176. framebufferScaleFactor: framebufferScaleFactor
  20177. }; // eslint-disable-next-line no-undef
  20178. baseLayer = new XRWebGLLayer(session, gl, layerInit);
  20179. if (window.XRWebGLBinding && this.layersEnabled) {
  20180. this.addLayer(baseLayer);
  20181. } else {
  20182. session.updateRenderState({
  20183. baseLayer: baseLayer
  20184. });
  20185. }
  20186. _context.next = 19;
  20187. return session.requestReferenceSpace(referenceSpaceType);
  20188. case 19:
  20189. referenceSpace = _context.sent;
  20190. animation.setContext(session);
  20191. animation.start();
  20192. scope.isPresenting = true;
  20193. scope.dispatchEvent({
  20194. type: 'sessionstart'
  20195. });
  20196. case 24:
  20197. case "end":
  20198. return _context.stop();
  20199. }
  20200. }
  20201. }, _callee, this);
  20202. }));
  20203. return function (_x) {
  20204. return _ref.apply(this, arguments);
  20205. };
  20206. }();
  20207. this.addLayer = function (layer) {
  20208. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20209. return;
  20210. }
  20211. layers.push(layer);
  20212. session.updateRenderState({
  20213. layers: layers
  20214. });
  20215. };
  20216. this.removeLayer = function (layer) {
  20217. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20218. return;
  20219. }
  20220. layers.splice(layers.indexOf(layer), 1);
  20221. session.updateRenderState({
  20222. layers: layers
  20223. });
  20224. };
  20225. function onInputSourcesChange(event) {
  20226. var inputSources = session.inputSources; // Assign inputSources to available controllers
  20227. for (var i = 0; i < controllers.length; i++) {
  20228. inputSourcesMap.set(inputSources[i], controllers[i]);
  20229. } // Notify disconnected
  20230. for (var _i = 0; _i < event.removed.length; _i++) {
  20231. var inputSource = event.removed[_i];
  20232. var controller = inputSourcesMap.get(inputSource);
  20233. if (controller) {
  20234. controller.dispatchEvent({
  20235. type: 'disconnected',
  20236. data: inputSource
  20237. });
  20238. inputSourcesMap.delete(inputSource);
  20239. }
  20240. } // Notify connected
  20241. for (var _i2 = 0; _i2 < event.added.length; _i2++) {
  20242. var _inputSource = event.added[_i2];
  20243. var _controller = inputSourcesMap.get(_inputSource);
  20244. if (_controller) {
  20245. _controller.dispatchEvent({
  20246. type: 'connected',
  20247. data: _inputSource
  20248. });
  20249. }
  20250. }
  20251. } //
  20252. var cameraLPos = new Vector3();
  20253. var cameraRPos = new Vector3();
  20254. /**
  20255. * Assumes 2 cameras that are parallel and share an X-axis, and that
  20256. * the cameras' projection and world matrices have already been set.
  20257. * And that near and far planes are identical for both cameras.
  20258. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  20259. */
  20260. function setProjectionFromUnion(camera, cameraL, cameraR) {
  20261. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  20262. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  20263. var ipd = cameraLPos.distanceTo(cameraRPos);
  20264. var projL = cameraL.projectionMatrix.elements;
  20265. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  20266. // most likely identical top and bottom frustum extents.
  20267. // Use the left camera for these values.
  20268. var near = projL[14] / (projL[10] - 1);
  20269. var far = projL[14] / (projL[10] + 1);
  20270. var topFov = (projL[9] + 1) / projL[5];
  20271. var bottomFov = (projL[9] - 1) / projL[5];
  20272. var leftFov = (projL[8] - 1) / projL[0];
  20273. var rightFov = (projR[8] + 1) / projR[0];
  20274. var left = near * leftFov;
  20275. var right = near * rightFov; // Calculate the new camera's position offset from the
  20276. // left camera. xOffset should be roughly half `ipd`.
  20277. var zOffset = ipd / (-leftFov + rightFov);
  20278. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  20279. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  20280. camera.translateX(xOffset);
  20281. camera.translateZ(zOffset);
  20282. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  20283. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  20284. // the values so that the near plane's position does not change in world space,
  20285. // although must now be relative to the new union camera.
  20286. var near2 = near + zOffset;
  20287. var far2 = far + zOffset;
  20288. var left2 = left - xOffset;
  20289. var right2 = right + (ipd - xOffset);
  20290. var top2 = topFov * far / far2 * near2;
  20291. var bottom2 = bottomFov * far / far2 * near2;
  20292. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  20293. }
  20294. function updateCamera(camera, parent) {
  20295. if (parent === null) {
  20296. camera.matrixWorld.copy(camera.matrix);
  20297. } else {
  20298. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  20299. }
  20300. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  20301. }
  20302. this.setPoseTarget = function (object) {
  20303. if (object !== undefined) poseTarget = object;
  20304. };
  20305. this.getCamera = function (camera) {
  20306. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  20307. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  20308. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  20309. // Note that the new renderState won't apply until the next frame. See #18320
  20310. session.updateRenderState({
  20311. depthNear: cameraVR.near,
  20312. depthFar: cameraVR.far
  20313. });
  20314. _currentDepthNear = cameraVR.near;
  20315. _currentDepthFar = cameraVR.far;
  20316. }
  20317. var parent = camera.parent;
  20318. var cameras = cameraVR.cameras;
  20319. var object = poseTarget || camera;
  20320. updateCamera(cameraVR, parent);
  20321. for (var i = 0; i < cameras.length; i++) {
  20322. updateCamera(cameras[i], parent);
  20323. } // update camera and its children
  20324. object.matrixWorld.copy(cameraVR.matrixWorld);
  20325. var children = object.children;
  20326. for (var _i3 = 0, l = children.length; _i3 < l; _i3++) {
  20327. children[_i3].updateMatrixWorld(true);
  20328. } // update projection matrix for proper view frustum culling
  20329. if (cameras.length === 2) {
  20330. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  20331. } else {
  20332. // assume single camera setup (AR)
  20333. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  20334. }
  20335. return cameraVR;
  20336. }; // Animation Loop
  20337. var onAnimationFrameCallback = null;
  20338. function onAnimationFrame(time, frame) {
  20339. pose = frame.getViewerPose(referenceSpace);
  20340. if (pose !== null) {
  20341. var views = pose.views;
  20342. renderer.setFramebuffer(baseLayer.framebuffer);
  20343. var cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  20344. if (views.length !== cameraVR.cameras.length) {
  20345. cameraVR.cameras.length = 0;
  20346. cameraVRNeedsUpdate = true;
  20347. }
  20348. for (var i = 0; i < views.length; i++) {
  20349. var view = views[i];
  20350. var viewport = baseLayer.getViewport(view);
  20351. var camera = cameras[i];
  20352. camera.matrix.fromArray(view.transform.matrix);
  20353. camera.projectionMatrix.fromArray(view.projectionMatrix);
  20354. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  20355. if (i === 0) {
  20356. cameraVR.matrix.copy(camera.matrix);
  20357. }
  20358. if (cameraVRNeedsUpdate === true) {
  20359. cameraVR.cameras.push(camera);
  20360. }
  20361. }
  20362. } //
  20363. var inputSources = session.inputSources;
  20364. for (var _i4 = 0; _i4 < controllers.length; _i4++) {
  20365. var controller = controllers[_i4];
  20366. var inputSource = inputSources[_i4];
  20367. controller.update(inputSource, frame, referenceSpace);
  20368. }
  20369. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  20370. }
  20371. var animation = new WebGLAnimation();
  20372. animation.setAnimationLoop(onAnimationFrame);
  20373. this.setAnimationLoop = function (callback) {
  20374. onAnimationFrameCallback = callback;
  20375. };
  20376. this.dispose = function () {};
  20377. }
  20378. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  20379. function WebGLMaterials(properties) {
  20380. function refreshFogUniforms(uniforms, fog) {
  20381. uniforms.fogColor.value.copy(fog.color);
  20382. if (fog.isFog) {
  20383. uniforms.fogNear.value = fog.near;
  20384. uniforms.fogFar.value = fog.far;
  20385. } else if (fog.isFogExp2) {
  20386. uniforms.fogDensity.value = fog.density;
  20387. }
  20388. }
  20389. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  20390. if (material.isMeshBasicMaterial) {
  20391. refreshUniformsCommon(uniforms, material);
  20392. } else if (material.isMeshLambertMaterial) {
  20393. refreshUniformsCommon(uniforms, material);
  20394. refreshUniformsLambert(uniforms, material);
  20395. } else if (material.isMeshToonMaterial) {
  20396. refreshUniformsCommon(uniforms, material);
  20397. refreshUniformsToon(uniforms, material);
  20398. } else if (material.isMeshPhongMaterial) {
  20399. refreshUniformsCommon(uniforms, material);
  20400. refreshUniformsPhong(uniforms, material);
  20401. } else if (material.isMeshStandardMaterial) {
  20402. refreshUniformsCommon(uniforms, material);
  20403. if (material.isMeshPhysicalMaterial) {
  20404. refreshUniformsPhysical(uniforms, material);
  20405. } else {
  20406. refreshUniformsStandard(uniforms, material);
  20407. }
  20408. } else if (material.isMeshMatcapMaterial) {
  20409. refreshUniformsCommon(uniforms, material);
  20410. refreshUniformsMatcap(uniforms, material);
  20411. } else if (material.isMeshDepthMaterial) {
  20412. refreshUniformsCommon(uniforms, material);
  20413. refreshUniformsDepth(uniforms, material);
  20414. } else if (material.isMeshDistanceMaterial) {
  20415. refreshUniformsCommon(uniforms, material);
  20416. refreshUniformsDistance(uniforms, material);
  20417. } else if (material.isMeshNormalMaterial) {
  20418. refreshUniformsCommon(uniforms, material);
  20419. refreshUniformsNormal(uniforms, material);
  20420. } else if (material.isLineBasicMaterial) {
  20421. refreshUniformsLine(uniforms, material);
  20422. if (material.isLineDashedMaterial) {
  20423. refreshUniformsDash(uniforms, material);
  20424. }
  20425. } else if (material.isPointsMaterial) {
  20426. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  20427. } else if (material.isSpriteMaterial) {
  20428. refreshUniformsSprites(uniforms, material);
  20429. } else if (material.isShadowMaterial) {
  20430. uniforms.color.value.copy(material.color);
  20431. uniforms.opacity.value = material.opacity;
  20432. } else if (material.isShaderMaterial) {
  20433. material.uniformsNeedUpdate = false; // #15581
  20434. }
  20435. }
  20436. function refreshUniformsCommon(uniforms, material) {
  20437. uniforms.opacity.value = material.opacity;
  20438. if (material.color) {
  20439. uniforms.diffuse.value.copy(material.color);
  20440. }
  20441. if (material.emissive) {
  20442. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  20443. }
  20444. if (material.map) {
  20445. uniforms.map.value = material.map;
  20446. }
  20447. if (material.alphaMap) {
  20448. uniforms.alphaMap.value = material.alphaMap;
  20449. }
  20450. if (material.specularMap) {
  20451. uniforms.specularMap.value = material.specularMap;
  20452. }
  20453. var envMap = properties.get(material).envMap;
  20454. if (envMap) {
  20455. uniforms.envMap.value = envMap;
  20456. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  20457. uniforms.reflectivity.value = material.reflectivity;
  20458. uniforms.refractionRatio.value = material.refractionRatio;
  20459. var maxMipLevel = properties.get(envMap).__maxMipLevel;
  20460. if (maxMipLevel !== undefined) {
  20461. uniforms.maxMipLevel.value = maxMipLevel;
  20462. }
  20463. }
  20464. if (material.lightMap) {
  20465. uniforms.lightMap.value = material.lightMap;
  20466. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  20467. }
  20468. if (material.aoMap) {
  20469. uniforms.aoMap.value = material.aoMap;
  20470. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  20471. } // uv repeat and offset setting priorities
  20472. // 1. color map
  20473. // 2. specular map
  20474. // 3. displacementMap map
  20475. // 4. normal map
  20476. // 5. bump map
  20477. // 6. roughnessMap map
  20478. // 7. metalnessMap map
  20479. // 8. alphaMap map
  20480. // 9. emissiveMap map
  20481. // 10. clearcoat map
  20482. // 11. clearcoat normal map
  20483. // 12. clearcoat roughnessMap map
  20484. var uvScaleMap;
  20485. if (material.map) {
  20486. uvScaleMap = material.map;
  20487. } else if (material.specularMap) {
  20488. uvScaleMap = material.specularMap;
  20489. } else if (material.displacementMap) {
  20490. uvScaleMap = material.displacementMap;
  20491. } else if (material.normalMap) {
  20492. uvScaleMap = material.normalMap;
  20493. } else if (material.bumpMap) {
  20494. uvScaleMap = material.bumpMap;
  20495. } else if (material.roughnessMap) {
  20496. uvScaleMap = material.roughnessMap;
  20497. } else if (material.metalnessMap) {
  20498. uvScaleMap = material.metalnessMap;
  20499. } else if (material.alphaMap) {
  20500. uvScaleMap = material.alphaMap;
  20501. } else if (material.emissiveMap) {
  20502. uvScaleMap = material.emissiveMap;
  20503. } else if (material.clearcoatMap) {
  20504. uvScaleMap = material.clearcoatMap;
  20505. } else if (material.clearcoatNormalMap) {
  20506. uvScaleMap = material.clearcoatNormalMap;
  20507. } else if (material.clearcoatRoughnessMap) {
  20508. uvScaleMap = material.clearcoatRoughnessMap;
  20509. }
  20510. if (uvScaleMap !== undefined) {
  20511. // backwards compatibility
  20512. if (uvScaleMap.isWebGLRenderTarget) {
  20513. uvScaleMap = uvScaleMap.texture;
  20514. }
  20515. if (uvScaleMap.matrixAutoUpdate === true) {
  20516. uvScaleMap.updateMatrix();
  20517. }
  20518. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20519. } // uv repeat and offset setting priorities for uv2
  20520. // 1. ao map
  20521. // 2. light map
  20522. var uv2ScaleMap;
  20523. if (material.aoMap) {
  20524. uv2ScaleMap = material.aoMap;
  20525. } else if (material.lightMap) {
  20526. uv2ScaleMap = material.lightMap;
  20527. }
  20528. if (uv2ScaleMap !== undefined) {
  20529. // backwards compatibility
  20530. if (uv2ScaleMap.isWebGLRenderTarget) {
  20531. uv2ScaleMap = uv2ScaleMap.texture;
  20532. }
  20533. if (uv2ScaleMap.matrixAutoUpdate === true) {
  20534. uv2ScaleMap.updateMatrix();
  20535. }
  20536. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  20537. }
  20538. }
  20539. function refreshUniformsLine(uniforms, material) {
  20540. uniforms.diffuse.value.copy(material.color);
  20541. uniforms.opacity.value = material.opacity;
  20542. }
  20543. function refreshUniformsDash(uniforms, material) {
  20544. uniforms.dashSize.value = material.dashSize;
  20545. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20546. uniforms.scale.value = material.scale;
  20547. }
  20548. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  20549. uniforms.diffuse.value.copy(material.color);
  20550. uniforms.opacity.value = material.opacity;
  20551. uniforms.size.value = material.size * pixelRatio;
  20552. uniforms.scale.value = height * 0.5;
  20553. if (material.map) {
  20554. uniforms.map.value = material.map;
  20555. }
  20556. if (material.alphaMap) {
  20557. uniforms.alphaMap.value = material.alphaMap;
  20558. } // uv repeat and offset setting priorities
  20559. // 1. color map
  20560. // 2. alpha map
  20561. var uvScaleMap;
  20562. if (material.map) {
  20563. uvScaleMap = material.map;
  20564. } else if (material.alphaMap) {
  20565. uvScaleMap = material.alphaMap;
  20566. }
  20567. if (uvScaleMap !== undefined) {
  20568. if (uvScaleMap.matrixAutoUpdate === true) {
  20569. uvScaleMap.updateMatrix();
  20570. }
  20571. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20572. }
  20573. }
  20574. function refreshUniformsSprites(uniforms, material) {
  20575. uniforms.diffuse.value.copy(material.color);
  20576. uniforms.opacity.value = material.opacity;
  20577. uniforms.rotation.value = material.rotation;
  20578. if (material.map) {
  20579. uniforms.map.value = material.map;
  20580. }
  20581. if (material.alphaMap) {
  20582. uniforms.alphaMap.value = material.alphaMap;
  20583. } // uv repeat and offset setting priorities
  20584. // 1. color map
  20585. // 2. alpha map
  20586. var uvScaleMap;
  20587. if (material.map) {
  20588. uvScaleMap = material.map;
  20589. } else if (material.alphaMap) {
  20590. uvScaleMap = material.alphaMap;
  20591. }
  20592. if (uvScaleMap !== undefined) {
  20593. if (uvScaleMap.matrixAutoUpdate === true) {
  20594. uvScaleMap.updateMatrix();
  20595. }
  20596. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20597. }
  20598. }
  20599. function refreshUniformsLambert(uniforms, material) {
  20600. if (material.emissiveMap) {
  20601. uniforms.emissiveMap.value = material.emissiveMap;
  20602. }
  20603. }
  20604. function refreshUniformsPhong(uniforms, material) {
  20605. uniforms.specular.value.copy(material.specular);
  20606. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  20607. if (material.emissiveMap) {
  20608. uniforms.emissiveMap.value = material.emissiveMap;
  20609. }
  20610. if (material.bumpMap) {
  20611. uniforms.bumpMap.value = material.bumpMap;
  20612. uniforms.bumpScale.value = material.bumpScale;
  20613. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20614. }
  20615. if (material.normalMap) {
  20616. uniforms.normalMap.value = material.normalMap;
  20617. uniforms.normalScale.value.copy(material.normalScale);
  20618. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20619. }
  20620. if (material.displacementMap) {
  20621. uniforms.displacementMap.value = material.displacementMap;
  20622. uniforms.displacementScale.value = material.displacementScale;
  20623. uniforms.displacementBias.value = material.displacementBias;
  20624. }
  20625. }
  20626. function refreshUniformsToon(uniforms, material) {
  20627. if (material.gradientMap) {
  20628. uniforms.gradientMap.value = material.gradientMap;
  20629. }
  20630. if (material.emissiveMap) {
  20631. uniforms.emissiveMap.value = material.emissiveMap;
  20632. }
  20633. if (material.bumpMap) {
  20634. uniforms.bumpMap.value = material.bumpMap;
  20635. uniforms.bumpScale.value = material.bumpScale;
  20636. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20637. }
  20638. if (material.normalMap) {
  20639. uniforms.normalMap.value = material.normalMap;
  20640. uniforms.normalScale.value.copy(material.normalScale);
  20641. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20642. }
  20643. if (material.displacementMap) {
  20644. uniforms.displacementMap.value = material.displacementMap;
  20645. uniforms.displacementScale.value = material.displacementScale;
  20646. uniforms.displacementBias.value = material.displacementBias;
  20647. }
  20648. }
  20649. function refreshUniformsStandard(uniforms, material) {
  20650. uniforms.roughness.value = material.roughness;
  20651. uniforms.metalness.value = material.metalness;
  20652. if (material.roughnessMap) {
  20653. uniforms.roughnessMap.value = material.roughnessMap;
  20654. }
  20655. if (material.metalnessMap) {
  20656. uniforms.metalnessMap.value = material.metalnessMap;
  20657. }
  20658. if (material.emissiveMap) {
  20659. uniforms.emissiveMap.value = material.emissiveMap;
  20660. }
  20661. if (material.bumpMap) {
  20662. uniforms.bumpMap.value = material.bumpMap;
  20663. uniforms.bumpScale.value = material.bumpScale;
  20664. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20665. }
  20666. if (material.normalMap) {
  20667. uniforms.normalMap.value = material.normalMap;
  20668. uniforms.normalScale.value.copy(material.normalScale);
  20669. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20670. }
  20671. if (material.displacementMap) {
  20672. uniforms.displacementMap.value = material.displacementMap;
  20673. uniforms.displacementScale.value = material.displacementScale;
  20674. uniforms.displacementBias.value = material.displacementBias;
  20675. }
  20676. var envMap = properties.get(material).envMap;
  20677. if (envMap) {
  20678. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20679. uniforms.envMapIntensity.value = material.envMapIntensity;
  20680. }
  20681. }
  20682. function refreshUniformsPhysical(uniforms, material) {
  20683. refreshUniformsStandard(uniforms, material);
  20684. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  20685. uniforms.clearcoat.value = material.clearcoat;
  20686. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20687. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  20688. if (material.clearcoatMap) {
  20689. uniforms.clearcoatMap.value = material.clearcoatMap;
  20690. }
  20691. if (material.clearcoatRoughnessMap) {
  20692. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  20693. }
  20694. if (material.clearcoatNormalMap) {
  20695. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  20696. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20697. if (material.side === BackSide) {
  20698. uniforms.clearcoatNormalScale.value.negate();
  20699. }
  20700. }
  20701. uniforms.transmission.value = material.transmission;
  20702. if (material.transmissionMap) {
  20703. uniforms.transmissionMap.value = material.transmissionMap;
  20704. }
  20705. }
  20706. function refreshUniformsMatcap(uniforms, material) {
  20707. if (material.matcap) {
  20708. uniforms.matcap.value = material.matcap;
  20709. }
  20710. if (material.bumpMap) {
  20711. uniforms.bumpMap.value = material.bumpMap;
  20712. uniforms.bumpScale.value = material.bumpScale;
  20713. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20714. }
  20715. if (material.normalMap) {
  20716. uniforms.normalMap.value = material.normalMap;
  20717. uniforms.normalScale.value.copy(material.normalScale);
  20718. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20719. }
  20720. if (material.displacementMap) {
  20721. uniforms.displacementMap.value = material.displacementMap;
  20722. uniforms.displacementScale.value = material.displacementScale;
  20723. uniforms.displacementBias.value = material.displacementBias;
  20724. }
  20725. }
  20726. function refreshUniformsDepth(uniforms, material) {
  20727. if (material.displacementMap) {
  20728. uniforms.displacementMap.value = material.displacementMap;
  20729. uniforms.displacementScale.value = material.displacementScale;
  20730. uniforms.displacementBias.value = material.displacementBias;
  20731. }
  20732. }
  20733. function refreshUniformsDistance(uniforms, material) {
  20734. if (material.displacementMap) {
  20735. uniforms.displacementMap.value = material.displacementMap;
  20736. uniforms.displacementScale.value = material.displacementScale;
  20737. uniforms.displacementBias.value = material.displacementBias;
  20738. }
  20739. uniforms.referencePosition.value.copy(material.referencePosition);
  20740. uniforms.nearDistance.value = material.nearDistance;
  20741. uniforms.farDistance.value = material.farDistance;
  20742. }
  20743. function refreshUniformsNormal(uniforms, material) {
  20744. if (material.bumpMap) {
  20745. uniforms.bumpMap.value = material.bumpMap;
  20746. uniforms.bumpScale.value = material.bumpScale;
  20747. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20748. }
  20749. if (material.normalMap) {
  20750. uniforms.normalMap.value = material.normalMap;
  20751. uniforms.normalScale.value.copy(material.normalScale);
  20752. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20753. }
  20754. if (material.displacementMap) {
  20755. uniforms.displacementMap.value = material.displacementMap;
  20756. uniforms.displacementScale.value = material.displacementScale;
  20757. uniforms.displacementBias.value = material.displacementBias;
  20758. }
  20759. }
  20760. return {
  20761. refreshFogUniforms: refreshFogUniforms,
  20762. refreshMaterialUniforms: refreshMaterialUniforms
  20763. };
  20764. }
  20765. function createCanvasElement() {
  20766. var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  20767. canvas.style.display = 'block';
  20768. return canvas;
  20769. }
  20770. function WebGLRenderer(parameters) {
  20771. parameters = parameters || {};
  20772. var _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  20773. _context = parameters.context !== undefined ? parameters.context : null,
  20774. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  20775. _depth = parameters.depth !== undefined ? parameters.depth : true,
  20776. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  20777. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  20778. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  20779. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20780. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  20781. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  20782. var currentRenderList = null;
  20783. var currentRenderState = null; // render() can be called from within a callback triggered by another render.
  20784. // We track this so that the nested render call gets its state isolated from the parent render call.
  20785. var renderStateStack = []; // public properties
  20786. this.domElement = _canvas; // Debug configuration container
  20787. this.debug = {
  20788. /**
  20789. * Enables error checking and reporting when shader programs are being compiled
  20790. * @type {boolean}
  20791. */
  20792. checkShaderErrors: true
  20793. }; // clearing
  20794. this.autoClear = true;
  20795. this.autoClearColor = true;
  20796. this.autoClearDepth = true;
  20797. this.autoClearStencil = true; // scene graph
  20798. this.sortObjects = true; // user-defined clipping
  20799. this.clippingPlanes = [];
  20800. this.localClippingEnabled = false; // physically based shading
  20801. this.gammaFactor = 2.0; // for backwards compatibility
  20802. this.outputEncoding = LinearEncoding; // physical lights
  20803. this.physicallyCorrectLights = false; // tone mapping
  20804. this.toneMapping = NoToneMapping;
  20805. this.toneMappingExposure = 1.0; // morphs
  20806. this.maxMorphTargets = 8;
  20807. this.maxMorphNormals = 4; // internal properties
  20808. var _this = this;
  20809. var _isContextLost = false; // internal state cache
  20810. var _framebuffer = null;
  20811. var _currentActiveCubeFace = 0;
  20812. var _currentActiveMipmapLevel = 0;
  20813. var _currentRenderTarget = null;
  20814. var _currentFramebuffer = null;
  20815. var _currentMaterialId = -1;
  20816. var _currentCamera = null;
  20817. var _currentViewport = new Vector4();
  20818. var _currentScissor = new Vector4();
  20819. var _currentScissorTest = null; //
  20820. var _width = _canvas.width;
  20821. var _height = _canvas.height;
  20822. var _pixelRatio = 1;
  20823. var _opaqueSort = null;
  20824. var _transparentSort = null;
  20825. var _viewport = new Vector4(0, 0, _width, _height);
  20826. var _scissor = new Vector4(0, 0, _width, _height);
  20827. var _scissorTest = false; // frustum
  20828. var _frustum = new Frustum(); // clipping
  20829. var _clippingEnabled = false;
  20830. var _localClippingEnabled = false; // camera matrices cache
  20831. var _projScreenMatrix = new Matrix4();
  20832. var _vector3 = new Vector3();
  20833. var _emptyScene = {
  20834. background: null,
  20835. fog: null,
  20836. environment: null,
  20837. overrideMaterial: null,
  20838. isScene: true
  20839. };
  20840. function getTargetPixelRatio() {
  20841. return _currentRenderTarget === null ? _pixelRatio : 1;
  20842. } // initialize
  20843. var _gl = _context;
  20844. function getContext(contextNames, contextAttributes) {
  20845. for (var i = 0; i < contextNames.length; i++) {
  20846. var contextName = contextNames[i];
  20847. var context = _canvas.getContext(contextName, contextAttributes);
  20848. if (context !== null) return context;
  20849. }
  20850. return null;
  20851. }
  20852. try {
  20853. var contextAttributes = {
  20854. alpha: _alpha,
  20855. depth: _depth,
  20856. stencil: _stencil,
  20857. antialias: _antialias,
  20858. premultipliedAlpha: _premultipliedAlpha,
  20859. preserveDrawingBuffer: _preserveDrawingBuffer,
  20860. powerPreference: _powerPreference,
  20861. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  20862. }; // event listeners must be registered before WebGL context is created, see #12753
  20863. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  20864. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  20865. if (_gl === null) {
  20866. var contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  20867. if (_this.isWebGL1Renderer === true) {
  20868. contextNames.shift();
  20869. }
  20870. _gl = getContext(contextNames, contextAttributes);
  20871. if (_gl === null) {
  20872. if (getContext(contextNames)) {
  20873. throw new Error('Error creating WebGL context with your selected attributes.');
  20874. } else {
  20875. throw new Error('Error creating WebGL context.');
  20876. }
  20877. }
  20878. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  20879. if (_gl.getShaderPrecisionFormat === undefined) {
  20880. _gl.getShaderPrecisionFormat = function () {
  20881. return {
  20882. 'rangeMin': 1,
  20883. 'rangeMax': 1,
  20884. 'precision': 1
  20885. };
  20886. };
  20887. }
  20888. } catch (error) {
  20889. console.error('THREE.WebGLRenderer: ' + error.message);
  20890. throw error;
  20891. }
  20892. var extensions, capabilities, state, info;
  20893. var properties, textures, cubemaps, attributes, geometries, objects;
  20894. var programCache, materials, renderLists, renderStates, clipping;
  20895. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  20896. var utils, bindingStates;
  20897. function initGLContext() {
  20898. extensions = new WebGLExtensions(_gl);
  20899. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  20900. extensions.init(capabilities);
  20901. utils = new WebGLUtils(_gl, extensions, capabilities);
  20902. state = new WebGLState(_gl, extensions, capabilities);
  20903. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  20904. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  20905. info = new WebGLInfo(_gl);
  20906. properties = new WebGLProperties();
  20907. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  20908. cubemaps = new WebGLCubeMaps(_this);
  20909. attributes = new WebGLAttributes(_gl, capabilities);
  20910. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  20911. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  20912. objects = new WebGLObjects(_gl, geometries, attributes, info);
  20913. morphtargets = new WebGLMorphtargets(_gl);
  20914. clipping = new WebGLClipping(properties);
  20915. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  20916. materials = new WebGLMaterials(properties);
  20917. renderLists = new WebGLRenderLists(properties);
  20918. renderStates = new WebGLRenderStates(extensions, capabilities);
  20919. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  20920. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  20921. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  20922. info.programs = programCache.programs;
  20923. _this.capabilities = capabilities;
  20924. _this.extensions = extensions;
  20925. _this.properties = properties;
  20926. _this.renderLists = renderLists;
  20927. _this.state = state;
  20928. _this.info = info;
  20929. }
  20930. initGLContext();
  20931. var xr = typeof navigator !== 'undefined' && 'xr' in navigator ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  20932. this.xr = xr; // shadow map
  20933. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  20934. this.shadowMap = shadowMap; // API
  20935. this.getContext = function () {
  20936. return _gl;
  20937. };
  20938. this.getContextAttributes = function () {
  20939. return _gl.getContextAttributes();
  20940. };
  20941. this.forceContextLoss = function () {
  20942. var extension = extensions.get('WEBGL_lose_context');
  20943. if (extension) extension.loseContext();
  20944. };
  20945. this.forceContextRestore = function () {
  20946. var extension = extensions.get('WEBGL_lose_context');
  20947. if (extension) extension.restoreContext();
  20948. };
  20949. this.getPixelRatio = function () {
  20950. return _pixelRatio;
  20951. };
  20952. this.setPixelRatio = function (value) {
  20953. if (value === undefined) return;
  20954. _pixelRatio = value;
  20955. this.setSize(_width, _height, false);
  20956. };
  20957. this.getSize = function (target) {
  20958. if (target === undefined) {
  20959. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  20960. target = new Vector2();
  20961. }
  20962. return target.set(_width, _height);
  20963. };
  20964. this.setSize = function (width, height, updateStyle) {
  20965. if (xr.isPresenting) {
  20966. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  20967. return;
  20968. }
  20969. _width = width;
  20970. _height = height;
  20971. _canvas.width = Math.floor(width * _pixelRatio);
  20972. _canvas.height = Math.floor(height * _pixelRatio);
  20973. if (updateStyle !== false) {
  20974. _canvas.style.width = width + 'px';
  20975. _canvas.style.height = height + 'px';
  20976. }
  20977. this.setViewport(0, 0, width, height);
  20978. };
  20979. this.getDrawingBufferSize = function (target) {
  20980. if (target === undefined) {
  20981. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  20982. target = new Vector2();
  20983. }
  20984. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  20985. };
  20986. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  20987. _width = width;
  20988. _height = height;
  20989. _pixelRatio = pixelRatio;
  20990. _canvas.width = Math.floor(width * pixelRatio);
  20991. _canvas.height = Math.floor(height * pixelRatio);
  20992. this.setViewport(0, 0, width, height);
  20993. };
  20994. this.getCurrentViewport = function (target) {
  20995. if (target === undefined) {
  20996. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  20997. target = new Vector4();
  20998. }
  20999. return target.copy(_currentViewport);
  21000. };
  21001. this.getViewport = function (target) {
  21002. return target.copy(_viewport);
  21003. };
  21004. this.setViewport = function (x, y, width, height) {
  21005. if (x.isVector4) {
  21006. _viewport.set(x.x, x.y, x.z, x.w);
  21007. } else {
  21008. _viewport.set(x, y, width, height);
  21009. }
  21010. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  21011. };
  21012. this.getScissor = function (target) {
  21013. return target.copy(_scissor);
  21014. };
  21015. this.setScissor = function (x, y, width, height) {
  21016. if (x.isVector4) {
  21017. _scissor.set(x.x, x.y, x.z, x.w);
  21018. } else {
  21019. _scissor.set(x, y, width, height);
  21020. }
  21021. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  21022. };
  21023. this.getScissorTest = function () {
  21024. return _scissorTest;
  21025. };
  21026. this.setScissorTest = function (boolean) {
  21027. state.setScissorTest(_scissorTest = boolean);
  21028. };
  21029. this.setOpaqueSort = function (method) {
  21030. _opaqueSort = method;
  21031. };
  21032. this.setTransparentSort = function (method) {
  21033. _transparentSort = method;
  21034. }; // Clearing
  21035. this.getClearColor = function (target) {
  21036. if (target === undefined) {
  21037. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  21038. target = new Color();
  21039. }
  21040. return target.copy(background.getClearColor());
  21041. };
  21042. this.setClearColor = function () {
  21043. background.setClearColor.apply(background, arguments);
  21044. };
  21045. this.getClearAlpha = function () {
  21046. return background.getClearAlpha();
  21047. };
  21048. this.setClearAlpha = function () {
  21049. background.setClearAlpha.apply(background, arguments);
  21050. };
  21051. this.clear = function (color, depth, stencil) {
  21052. var bits = 0;
  21053. if (color === undefined || color) bits |= 16384;
  21054. if (depth === undefined || depth) bits |= 256;
  21055. if (stencil === undefined || stencil) bits |= 1024;
  21056. _gl.clear(bits);
  21057. };
  21058. this.clearColor = function () {
  21059. this.clear(true, false, false);
  21060. };
  21061. this.clearDepth = function () {
  21062. this.clear(false, true, false);
  21063. };
  21064. this.clearStencil = function () {
  21065. this.clear(false, false, true);
  21066. }; //
  21067. this.dispose = function () {
  21068. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  21069. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  21070. renderLists.dispose();
  21071. renderStates.dispose();
  21072. properties.dispose();
  21073. cubemaps.dispose();
  21074. objects.dispose();
  21075. bindingStates.dispose();
  21076. xr.dispose();
  21077. animation.stop();
  21078. }; // Events
  21079. function onContextLost(event) {
  21080. event.preventDefault();
  21081. console.log('THREE.WebGLRenderer: Context Lost.');
  21082. _isContextLost = true;
  21083. }
  21084. function onContextRestore()
  21085. /* event */
  21086. {
  21087. console.log('THREE.WebGLRenderer: Context Restored.');
  21088. _isContextLost = false;
  21089. initGLContext();
  21090. }
  21091. function onMaterialDispose(event) {
  21092. var material = event.target;
  21093. material.removeEventListener('dispose', onMaterialDispose);
  21094. deallocateMaterial(material);
  21095. } // Buffer deallocation
  21096. function deallocateMaterial(material) {
  21097. releaseMaterialProgramReference(material);
  21098. properties.remove(material);
  21099. }
  21100. function releaseMaterialProgramReference(material) {
  21101. var programInfo = properties.get(material).program;
  21102. if (programInfo !== undefined) {
  21103. programCache.releaseProgram(programInfo);
  21104. }
  21105. } // Buffer rendering
  21106. function renderObjectImmediate(object, program) {
  21107. object.render(function (object) {
  21108. _this.renderBufferImmediate(object, program);
  21109. });
  21110. }
  21111. this.renderBufferImmediate = function (object, program) {
  21112. bindingStates.initAttributes();
  21113. var buffers = properties.get(object);
  21114. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  21115. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  21116. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  21117. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  21118. var programAttributes = program.getAttributes();
  21119. if (object.hasPositions) {
  21120. _gl.bindBuffer(34962, buffers.position);
  21121. _gl.bufferData(34962, object.positionArray, 35048);
  21122. bindingStates.enableAttribute(programAttributes.position);
  21123. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  21124. }
  21125. if (object.hasNormals) {
  21126. _gl.bindBuffer(34962, buffers.normal);
  21127. _gl.bufferData(34962, object.normalArray, 35048);
  21128. bindingStates.enableAttribute(programAttributes.normal);
  21129. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  21130. }
  21131. if (object.hasUvs) {
  21132. _gl.bindBuffer(34962, buffers.uv);
  21133. _gl.bufferData(34962, object.uvArray, 35048);
  21134. bindingStates.enableAttribute(programAttributes.uv);
  21135. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  21136. }
  21137. if (object.hasColors) {
  21138. _gl.bindBuffer(34962, buffers.color);
  21139. _gl.bufferData(34962, object.colorArray, 35048);
  21140. bindingStates.enableAttribute(programAttributes.color);
  21141. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  21142. }
  21143. bindingStates.disableUnusedAttributes();
  21144. _gl.drawArrays(4, 0, object.count);
  21145. object.count = 0;
  21146. };
  21147. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  21148. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  21149. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  21150. var program = setProgram(camera, scene, material, object);
  21151. state.setMaterial(material, frontFaceCW); //
  21152. var index = geometry.index;
  21153. var position = geometry.attributes.position; //
  21154. if (index === null) {
  21155. if (position === undefined || position.count === 0) return;
  21156. } else if (index.count === 0) {
  21157. return;
  21158. } //
  21159. var rangeFactor = 1;
  21160. if (material.wireframe === true) {
  21161. index = geometries.getWireframeAttribute(geometry);
  21162. rangeFactor = 2;
  21163. }
  21164. if (material.morphTargets || material.morphNormals) {
  21165. morphtargets.update(object, geometry, material, program);
  21166. }
  21167. bindingStates.setup(object, material, program, geometry, index);
  21168. var attribute;
  21169. var renderer = bufferRenderer;
  21170. if (index !== null) {
  21171. attribute = attributes.get(index);
  21172. renderer = indexedBufferRenderer;
  21173. renderer.setIndex(attribute);
  21174. } //
  21175. var dataCount = index !== null ? index.count : position.count;
  21176. var rangeStart = geometry.drawRange.start * rangeFactor;
  21177. var rangeCount = geometry.drawRange.count * rangeFactor;
  21178. var groupStart = group !== null ? group.start * rangeFactor : 0;
  21179. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  21180. var drawStart = Math.max(rangeStart, groupStart);
  21181. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  21182. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  21183. if (drawCount === 0) return; //
  21184. if (object.isMesh) {
  21185. if (material.wireframe === true) {
  21186. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  21187. renderer.setMode(1);
  21188. } else {
  21189. renderer.setMode(4);
  21190. }
  21191. } else if (object.isLine) {
  21192. var lineWidth = material.linewidth;
  21193. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  21194. state.setLineWidth(lineWidth * getTargetPixelRatio());
  21195. if (object.isLineSegments) {
  21196. renderer.setMode(1);
  21197. } else if (object.isLineLoop) {
  21198. renderer.setMode(2);
  21199. } else {
  21200. renderer.setMode(3);
  21201. }
  21202. } else if (object.isPoints) {
  21203. renderer.setMode(0);
  21204. } else if (object.isSprite) {
  21205. renderer.setMode(4);
  21206. }
  21207. if (object.isInstancedMesh) {
  21208. renderer.renderInstances(drawStart, drawCount, object.count);
  21209. } else if (geometry.isInstancedBufferGeometry) {
  21210. var instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  21211. renderer.renderInstances(drawStart, drawCount, instanceCount);
  21212. } else {
  21213. renderer.render(drawStart, drawCount);
  21214. }
  21215. }; // Compile
  21216. this.compile = function (scene, camera) {
  21217. currentRenderState = renderStates.get(scene);
  21218. currentRenderState.init();
  21219. scene.traverseVisible(function (object) {
  21220. if (object.isLight && object.layers.test(camera.layers)) {
  21221. currentRenderState.pushLight(object);
  21222. if (object.castShadow) {
  21223. currentRenderState.pushShadow(object);
  21224. }
  21225. }
  21226. });
  21227. currentRenderState.setupLights();
  21228. var compiled = new WeakMap();
  21229. scene.traverse(function (object) {
  21230. var material = object.material;
  21231. if (material) {
  21232. if (Array.isArray(material)) {
  21233. for (var i = 0; i < material.length; i++) {
  21234. var material2 = material[i];
  21235. if (compiled.has(material2) === false) {
  21236. initMaterial(material2, scene, object);
  21237. compiled.set(material2);
  21238. }
  21239. }
  21240. } else if (compiled.has(material) === false) {
  21241. initMaterial(material, scene, object);
  21242. compiled.set(material);
  21243. }
  21244. }
  21245. });
  21246. }; // Animation Loop
  21247. var onAnimationFrameCallback = null;
  21248. function onAnimationFrame(time) {
  21249. if (xr.isPresenting) return;
  21250. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  21251. }
  21252. var animation = new WebGLAnimation();
  21253. animation.setAnimationLoop(onAnimationFrame);
  21254. if (typeof window !== 'undefined') animation.setContext(window);
  21255. this.setAnimationLoop = function (callback) {
  21256. onAnimationFrameCallback = callback;
  21257. xr.setAnimationLoop(callback);
  21258. callback === null ? animation.stop() : animation.start();
  21259. }; // Rendering
  21260. this.render = function (scene, camera) {
  21261. var renderTarget, forceClear;
  21262. if (arguments[2] !== undefined) {
  21263. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  21264. renderTarget = arguments[2];
  21265. }
  21266. if (arguments[3] !== undefined) {
  21267. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  21268. forceClear = arguments[3];
  21269. }
  21270. if (camera !== undefined && camera.isCamera !== true) {
  21271. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  21272. return;
  21273. }
  21274. if (_isContextLost === true) return; // reset caching for this frame
  21275. bindingStates.resetDefaultState();
  21276. _currentMaterialId = -1;
  21277. _currentCamera = null; // update scene graph
  21278. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  21279. if (camera.parent === null) camera.updateMatrixWorld();
  21280. if (xr.enabled === true && xr.isPresenting === true) {
  21281. camera = xr.getCamera(camera);
  21282. } //
  21283. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  21284. currentRenderState = renderStates.get(scene, renderStateStack.length);
  21285. currentRenderState.init();
  21286. renderStateStack.push(currentRenderState);
  21287. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  21288. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  21289. _localClippingEnabled = this.localClippingEnabled;
  21290. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  21291. currentRenderList = renderLists.get(scene, camera);
  21292. currentRenderList.init();
  21293. projectObject(scene, camera, 0, _this.sortObjects);
  21294. currentRenderList.finish();
  21295. if (_this.sortObjects === true) {
  21296. currentRenderList.sort(_opaqueSort, _transparentSort);
  21297. } //
  21298. if (_clippingEnabled === true) clipping.beginShadows();
  21299. var shadowsArray = currentRenderState.state.shadowsArray;
  21300. shadowMap.render(shadowsArray, scene, camera);
  21301. currentRenderState.setupLights();
  21302. currentRenderState.setupLightsView(camera);
  21303. if (_clippingEnabled === true) clipping.endShadows(); //
  21304. if (this.info.autoReset === true) this.info.reset();
  21305. if (renderTarget !== undefined) {
  21306. this.setRenderTarget(renderTarget);
  21307. } //
  21308. background.render(currentRenderList, scene, camera, forceClear); // render scene
  21309. var opaqueObjects = currentRenderList.opaque;
  21310. var transparentObjects = currentRenderList.transparent;
  21311. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  21312. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  21313. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  21314. if (_currentRenderTarget !== null) {
  21315. // Generate mipmap if we're using any kind of mipmap filtering
  21316. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  21317. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  21318. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  21319. state.buffers.depth.setTest(true);
  21320. state.buffers.depth.setMask(true);
  21321. state.buffers.color.setMask(true);
  21322. state.setPolygonOffset(false);
  21323. if (xr.enabled && xr.submitFrame) {
  21324. xr.submitFrame();
  21325. } // _gl.finish();
  21326. renderStateStack.pop();
  21327. if (renderStateStack.length > 0) {
  21328. currentRenderState = renderStateStack[renderStateStack.length - 1];
  21329. } else {
  21330. currentRenderState = null;
  21331. }
  21332. currentRenderList = null;
  21333. };
  21334. function projectObject(object, camera, groupOrder, sortObjects) {
  21335. if (object.visible === false) return;
  21336. var visible = object.layers.test(camera.layers);
  21337. if (visible) {
  21338. if (object.isGroup) {
  21339. groupOrder = object.renderOrder;
  21340. } else if (object.isLOD) {
  21341. if (object.autoUpdate === true) object.update(camera);
  21342. } else if (object.isLight) {
  21343. currentRenderState.pushLight(object);
  21344. if (object.castShadow) {
  21345. currentRenderState.pushShadow(object);
  21346. }
  21347. } else if (object.isSprite) {
  21348. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  21349. if (sortObjects) {
  21350. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21351. }
  21352. var geometry = objects.update(object);
  21353. var material = object.material;
  21354. if (material.visible) {
  21355. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  21356. }
  21357. }
  21358. } else if (object.isImmediateRenderObject) {
  21359. if (sortObjects) {
  21360. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21361. }
  21362. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  21363. } else if (object.isMesh || object.isLine || object.isPoints) {
  21364. if (object.isSkinnedMesh) {
  21365. // update skeleton only once in a frame
  21366. if (object.skeleton.frame !== info.render.frame) {
  21367. object.skeleton.update();
  21368. object.skeleton.frame = info.render.frame;
  21369. }
  21370. }
  21371. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  21372. if (sortObjects) {
  21373. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21374. }
  21375. var _geometry = objects.update(object);
  21376. var _material = object.material;
  21377. if (Array.isArray(_material)) {
  21378. var groups = _geometry.groups;
  21379. for (var i = 0, l = groups.length; i < l; i++) {
  21380. var group = groups[i];
  21381. var groupMaterial = _material[group.materialIndex];
  21382. if (groupMaterial && groupMaterial.visible) {
  21383. currentRenderList.push(object, _geometry, groupMaterial, groupOrder, _vector3.z, group);
  21384. }
  21385. }
  21386. } else if (_material.visible) {
  21387. currentRenderList.push(object, _geometry, _material, groupOrder, _vector3.z, null);
  21388. }
  21389. }
  21390. }
  21391. }
  21392. var children = object.children;
  21393. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  21394. projectObject(children[_i], camera, groupOrder, sortObjects);
  21395. }
  21396. }
  21397. function renderObjects(renderList, scene, camera) {
  21398. var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  21399. for (var i = 0, l = renderList.length; i < l; i++) {
  21400. var renderItem = renderList[i];
  21401. var object = renderItem.object;
  21402. var geometry = renderItem.geometry;
  21403. var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  21404. var group = renderItem.group;
  21405. if (camera.isArrayCamera) {
  21406. var cameras = camera.cameras;
  21407. for (var j = 0, jl = cameras.length; j < jl; j++) {
  21408. var camera2 = cameras[j];
  21409. if (object.layers.test(camera2.layers)) {
  21410. state.viewport(_currentViewport.copy(camera2.viewport));
  21411. currentRenderState.setupLightsView(camera2);
  21412. renderObject(object, scene, camera2, geometry, material, group);
  21413. }
  21414. }
  21415. } else {
  21416. renderObject(object, scene, camera, geometry, material, group);
  21417. }
  21418. }
  21419. }
  21420. function renderObject(object, scene, camera, geometry, material, group) {
  21421. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  21422. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  21423. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  21424. if (object.isImmediateRenderObject) {
  21425. var program = setProgram(camera, scene, material, object);
  21426. state.setMaterial(material);
  21427. bindingStates.reset();
  21428. renderObjectImmediate(object, program);
  21429. } else {
  21430. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  21431. }
  21432. object.onAfterRender(_this, scene, camera, geometry, material, group);
  21433. }
  21434. function initMaterial(material, scene, object) {
  21435. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21436. var materialProperties = properties.get(material);
  21437. var lights = currentRenderState.state.lights;
  21438. var shadowsArray = currentRenderState.state.shadowsArray;
  21439. var lightsStateVersion = lights.state.version;
  21440. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  21441. var programCacheKey = programCache.getProgramCacheKey(parameters);
  21442. var program = materialProperties.program;
  21443. var programChange = true; // always update environment and fog - changing these trigger an initMaterial call, but it's possible that the program doesn't change
  21444. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  21445. materialProperties.fog = scene.fog;
  21446. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  21447. if (program === undefined) {
  21448. // new material
  21449. material.addEventListener('dispose', onMaterialDispose);
  21450. } else if (program.cacheKey !== programCacheKey) {
  21451. // changed glsl or parameters
  21452. releaseMaterialProgramReference(material);
  21453. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  21454. programChange = false;
  21455. } else if (parameters.shaderID !== undefined) {
  21456. // same glsl and uniform list
  21457. return;
  21458. } else {
  21459. // only rebuild uniform list
  21460. programChange = false;
  21461. }
  21462. if (programChange) {
  21463. parameters.uniforms = programCache.getUniforms(material);
  21464. material.onBeforeCompile(parameters, _this);
  21465. program = programCache.acquireProgram(parameters, programCacheKey);
  21466. materialProperties.program = program;
  21467. materialProperties.uniforms = parameters.uniforms;
  21468. materialProperties.outputEncoding = parameters.outputEncoding;
  21469. }
  21470. var uniforms = materialProperties.uniforms;
  21471. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  21472. materialProperties.numClippingPlanes = clipping.numPlanes;
  21473. materialProperties.numIntersection = clipping.numIntersection;
  21474. uniforms.clippingPlanes = clipping.uniform;
  21475. } // store the light setup it was created for
  21476. materialProperties.needsLights = materialNeedsLights(material);
  21477. materialProperties.lightsStateVersion = lightsStateVersion;
  21478. if (materialProperties.needsLights) {
  21479. // wire up the material to this renderer's lighting state
  21480. uniforms.ambientLightColor.value = lights.state.ambient;
  21481. uniforms.lightProbe.value = lights.state.probe;
  21482. uniforms.directionalLights.value = lights.state.directional;
  21483. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  21484. uniforms.spotLights.value = lights.state.spot;
  21485. uniforms.spotLightShadows.value = lights.state.spotShadow;
  21486. uniforms.rectAreaLights.value = lights.state.rectArea;
  21487. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  21488. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  21489. uniforms.pointLights.value = lights.state.point;
  21490. uniforms.pointLightShadows.value = lights.state.pointShadow;
  21491. uniforms.hemisphereLights.value = lights.state.hemi;
  21492. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  21493. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  21494. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  21495. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  21496. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  21497. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  21498. }
  21499. var progUniforms = materialProperties.program.getUniforms();
  21500. var uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  21501. materialProperties.uniformsList = uniformsList;
  21502. }
  21503. function setProgram(camera, scene, material, object) {
  21504. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21505. textures.resetTextureUnits();
  21506. var fog = scene.fog;
  21507. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  21508. var encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  21509. var envMap = cubemaps.get(material.envMap || environment);
  21510. var materialProperties = properties.get(material);
  21511. var lights = currentRenderState.state.lights;
  21512. if (_clippingEnabled === true) {
  21513. if (_localClippingEnabled === true || camera !== _currentCamera) {
  21514. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  21515. // object instead of the material, once it becomes feasible
  21516. // (#8465, #8379)
  21517. clipping.setState(material, camera, useCache);
  21518. }
  21519. }
  21520. if (material.version === materialProperties.__version) {
  21521. if (material.fog && materialProperties.fog !== fog) {
  21522. initMaterial(material, scene, object);
  21523. } else if (materialProperties.environment !== environment) {
  21524. initMaterial(material, scene, object);
  21525. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  21526. initMaterial(material, scene, object);
  21527. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  21528. initMaterial(material, scene, object);
  21529. } else if (materialProperties.outputEncoding !== encoding) {
  21530. initMaterial(material, scene, object);
  21531. } else if (materialProperties.envMap !== envMap) {
  21532. initMaterial(material, scene, object);
  21533. }
  21534. } else {
  21535. initMaterial(material, scene, object);
  21536. materialProperties.__version = material.version;
  21537. }
  21538. var refreshProgram = false;
  21539. var refreshMaterial = false;
  21540. var refreshLights = false;
  21541. var program = materialProperties.program,
  21542. p_uniforms = program.getUniforms(),
  21543. m_uniforms = materialProperties.uniforms;
  21544. if (state.useProgram(program.program)) {
  21545. refreshProgram = true;
  21546. refreshMaterial = true;
  21547. refreshLights = true;
  21548. }
  21549. if (material.id !== _currentMaterialId) {
  21550. _currentMaterialId = material.id;
  21551. refreshMaterial = true;
  21552. }
  21553. if (refreshProgram || _currentCamera !== camera) {
  21554. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  21555. if (capabilities.logarithmicDepthBuffer) {
  21556. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  21557. }
  21558. if (_currentCamera !== camera) {
  21559. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  21560. // now, in case this material supports lights - or later, when
  21561. // the next material that does gets activated:
  21562. refreshMaterial = true; // set to true on material change
  21563. refreshLights = true; // remains set until update done
  21564. } // load material specific uniforms
  21565. // (shader material also gets them for the sake of genericity)
  21566. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  21567. var uCamPos = p_uniforms.map.cameraPosition;
  21568. if (uCamPos !== undefined) {
  21569. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  21570. }
  21571. }
  21572. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  21573. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  21574. }
  21575. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  21576. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  21577. }
  21578. } // skinning uniforms must be set even if material didn't change
  21579. // auto-setting of texture unit for bone texture must go before other textures
  21580. // otherwise textures used for skinning can take over texture units reserved for other material textures
  21581. if (material.skinning) {
  21582. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  21583. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  21584. var skeleton = object.skeleton;
  21585. if (skeleton) {
  21586. var bones = skeleton.bones;
  21587. if (capabilities.floatVertexTextures) {
  21588. if (skeleton.boneTexture === null) {
  21589. // layout (1 matrix = 4 pixels)
  21590. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  21591. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  21592. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  21593. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  21594. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  21595. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  21596. size = MathUtils.ceilPowerOfTwo(size);
  21597. size = Math.max(size, 4);
  21598. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  21599. boneMatrices.set(skeleton.boneMatrices); // copy current values
  21600. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  21601. skeleton.boneMatrices = boneMatrices;
  21602. skeleton.boneTexture = boneTexture;
  21603. skeleton.boneTextureSize = size;
  21604. }
  21605. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  21606. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  21607. } else {
  21608. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  21609. }
  21610. }
  21611. }
  21612. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  21613. materialProperties.receiveShadow = object.receiveShadow;
  21614. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  21615. }
  21616. if (refreshMaterial) {
  21617. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  21618. if (materialProperties.needsLights) {
  21619. // the current material requires lighting info
  21620. // note: all lighting uniforms are always set correctly
  21621. // they simply reference the renderer's state for their
  21622. // values
  21623. //
  21624. // use the current material's .needsUpdate flags to set
  21625. // the GL state when required
  21626. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  21627. } // refresh uniforms common to several materials
  21628. if (fog && material.fog) {
  21629. materials.refreshFogUniforms(m_uniforms, fog);
  21630. }
  21631. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  21632. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21633. }
  21634. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  21635. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21636. material.uniformsNeedUpdate = false;
  21637. }
  21638. if (material.isSpriteMaterial) {
  21639. p_uniforms.setValue(_gl, 'center', object.center);
  21640. } // common matrices
  21641. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  21642. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  21643. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  21644. return program;
  21645. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  21646. function markUniformsLightsNeedsUpdate(uniforms, value) {
  21647. uniforms.ambientLightColor.needsUpdate = value;
  21648. uniforms.lightProbe.needsUpdate = value;
  21649. uniforms.directionalLights.needsUpdate = value;
  21650. uniforms.directionalLightShadows.needsUpdate = value;
  21651. uniforms.pointLights.needsUpdate = value;
  21652. uniforms.pointLightShadows.needsUpdate = value;
  21653. uniforms.spotLights.needsUpdate = value;
  21654. uniforms.spotLightShadows.needsUpdate = value;
  21655. uniforms.rectAreaLights.needsUpdate = value;
  21656. uniforms.hemisphereLights.needsUpdate = value;
  21657. }
  21658. function materialNeedsLights(material) {
  21659. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  21660. } // this.setTexture2D = setTexture2D;
  21661. this.setTexture2D = function () {
  21662. var warned = false; // backwards compatibility: peel texture.texture
  21663. return function setTexture2D(texture, slot) {
  21664. if (texture && texture.isWebGLRenderTarget) {
  21665. if (!warned) {
  21666. console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead.");
  21667. warned = true;
  21668. }
  21669. texture = texture.texture;
  21670. }
  21671. textures.setTexture2D(texture, slot);
  21672. };
  21673. }(); //
  21674. this.setFramebuffer = function (value) {
  21675. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  21676. _framebuffer = value;
  21677. };
  21678. this.getActiveCubeFace = function () {
  21679. return _currentActiveCubeFace;
  21680. };
  21681. this.getActiveMipmapLevel = function () {
  21682. return _currentActiveMipmapLevel;
  21683. };
  21684. this.getRenderList = function () {
  21685. return currentRenderList;
  21686. };
  21687. this.setRenderList = function (renderList) {
  21688. currentRenderList = renderList;
  21689. };
  21690. this.getRenderTarget = function () {
  21691. return _currentRenderTarget;
  21692. };
  21693. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  21694. if (activeCubeFace === void 0) {
  21695. activeCubeFace = 0;
  21696. }
  21697. if (activeMipmapLevel === void 0) {
  21698. activeMipmapLevel = 0;
  21699. }
  21700. _currentRenderTarget = renderTarget;
  21701. _currentActiveCubeFace = activeCubeFace;
  21702. _currentActiveMipmapLevel = activeMipmapLevel;
  21703. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  21704. textures.setupRenderTarget(renderTarget);
  21705. }
  21706. var framebuffer = _framebuffer;
  21707. var isCube = false;
  21708. if (renderTarget) {
  21709. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  21710. if (renderTarget.isWebGLCubeRenderTarget) {
  21711. framebuffer = __webglFramebuffer[activeCubeFace];
  21712. isCube = true;
  21713. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  21714. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  21715. } else {
  21716. framebuffer = __webglFramebuffer;
  21717. }
  21718. _currentViewport.copy(renderTarget.viewport);
  21719. _currentScissor.copy(renderTarget.scissor);
  21720. _currentScissorTest = renderTarget.scissorTest;
  21721. } else {
  21722. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  21723. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  21724. _currentScissorTest = _scissorTest;
  21725. }
  21726. if (_currentFramebuffer !== framebuffer) {
  21727. _gl.bindFramebuffer(36160, framebuffer);
  21728. _currentFramebuffer = framebuffer;
  21729. }
  21730. state.viewport(_currentViewport);
  21731. state.scissor(_currentScissor);
  21732. state.setScissorTest(_currentScissorTest);
  21733. if (isCube) {
  21734. var textureProperties = properties.get(renderTarget.texture);
  21735. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  21736. }
  21737. };
  21738. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  21739. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  21740. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  21741. return;
  21742. }
  21743. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  21744. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  21745. framebuffer = framebuffer[activeCubeFaceIndex];
  21746. }
  21747. if (framebuffer) {
  21748. var restore = false;
  21749. if (framebuffer !== _currentFramebuffer) {
  21750. _gl.bindFramebuffer(36160, framebuffer);
  21751. restore = true;
  21752. }
  21753. try {
  21754. var texture = renderTarget.texture;
  21755. var textureFormat = texture.format;
  21756. var textureType = texture.type;
  21757. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  21758. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  21759. return;
  21760. }
  21761. var halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  21762. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  21763. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  21764. !halfFloatSupportedByExt) {
  21765. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  21766. return;
  21767. }
  21768. if (_gl.checkFramebufferStatus(36160) === 36053) {
  21769. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  21770. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  21771. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  21772. }
  21773. } else {
  21774. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  21775. }
  21776. } finally {
  21777. if (restore) {
  21778. _gl.bindFramebuffer(36160, _currentFramebuffer);
  21779. }
  21780. }
  21781. }
  21782. };
  21783. this.copyFramebufferToTexture = function (position, texture, level) {
  21784. if (level === void 0) {
  21785. level = 0;
  21786. }
  21787. var levelScale = Math.pow(2, -level);
  21788. var width = Math.floor(texture.image.width * levelScale);
  21789. var height = Math.floor(texture.image.height * levelScale);
  21790. var glFormat = utils.convert(texture.format);
  21791. textures.setTexture2D(texture, 0);
  21792. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  21793. state.unbindTexture();
  21794. };
  21795. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  21796. if (level === void 0) {
  21797. level = 0;
  21798. }
  21799. var width = srcTexture.image.width;
  21800. var height = srcTexture.image.height;
  21801. var glFormat = utils.convert(dstTexture.format);
  21802. var glType = utils.convert(dstTexture.type);
  21803. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  21804. // parameters, make sure they are correct for the dstTexture
  21805. _gl.pixelStorei(37440, dstTexture.flipY);
  21806. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  21807. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  21808. if (srcTexture.isDataTexture) {
  21809. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  21810. } else {
  21811. if (srcTexture.isCompressedTexture) {
  21812. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  21813. } else {
  21814. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  21815. }
  21816. } // Generate mipmaps only when copying level 0
  21817. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  21818. state.unbindTexture();
  21819. };
  21820. this.initTexture = function (texture) {
  21821. textures.setTexture2D(texture, 0);
  21822. state.unbindTexture();
  21823. };
  21824. this.resetState = function () {
  21825. state.reset();
  21826. bindingStates.reset();
  21827. };
  21828. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21829. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21830. detail: this
  21831. })); // eslint-disable-line no-undef
  21832. }
  21833. }
  21834. function WebGL1Renderer(parameters) {
  21835. WebGLRenderer.call(this, parameters);
  21836. }
  21837. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  21838. constructor: WebGL1Renderer,
  21839. isWebGL1Renderer: true
  21840. });
  21841. var FogExp2 = /*#__PURE__*/function () {
  21842. function FogExp2(color, density) {
  21843. Object.defineProperty(this, 'isFogExp2', {
  21844. value: true
  21845. });
  21846. this.name = '';
  21847. this.color = new Color(color);
  21848. this.density = density !== undefined ? density : 0.00025;
  21849. }
  21850. var _proto = FogExp2.prototype;
  21851. _proto.clone = function clone() {
  21852. return new FogExp2(this.color, this.density);
  21853. };
  21854. _proto.toJSON = function toJSON()
  21855. /* meta */
  21856. {
  21857. return {
  21858. type: 'FogExp2',
  21859. color: this.color.getHex(),
  21860. density: this.density
  21861. };
  21862. };
  21863. return FogExp2;
  21864. }();
  21865. var Fog = /*#__PURE__*/function () {
  21866. function Fog(color, near, far) {
  21867. Object.defineProperty(this, 'isFog', {
  21868. value: true
  21869. });
  21870. this.name = '';
  21871. this.color = new Color(color);
  21872. this.near = near !== undefined ? near : 1;
  21873. this.far = far !== undefined ? far : 1000;
  21874. }
  21875. var _proto = Fog.prototype;
  21876. _proto.clone = function clone() {
  21877. return new Fog(this.color, this.near, this.far);
  21878. };
  21879. _proto.toJSON = function toJSON()
  21880. /* meta */
  21881. {
  21882. return {
  21883. type: 'Fog',
  21884. color: this.color.getHex(),
  21885. near: this.near,
  21886. far: this.far
  21887. };
  21888. };
  21889. return Fog;
  21890. }();
  21891. var Scene = /*#__PURE__*/function (_Object3D) {
  21892. _inheritsLoose(Scene, _Object3D);
  21893. function Scene() {
  21894. var _this;
  21895. _this = _Object3D.call(this) || this;
  21896. Object.defineProperty(_assertThisInitialized(_this), 'isScene', {
  21897. value: true
  21898. });
  21899. _this.type = 'Scene';
  21900. _this.background = null;
  21901. _this.environment = null;
  21902. _this.fog = null;
  21903. _this.overrideMaterial = null;
  21904. _this.autoUpdate = true; // checked by the renderer
  21905. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21906. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21907. detail: _assertThisInitialized(_this)
  21908. })); // eslint-disable-line no-undef
  21909. }
  21910. return _this;
  21911. }
  21912. var _proto = Scene.prototype;
  21913. _proto.copy = function copy(source, recursive) {
  21914. _Object3D.prototype.copy.call(this, source, recursive);
  21915. if (source.background !== null) this.background = source.background.clone();
  21916. if (source.environment !== null) this.environment = source.environment.clone();
  21917. if (source.fog !== null) this.fog = source.fog.clone();
  21918. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  21919. this.autoUpdate = source.autoUpdate;
  21920. this.matrixAutoUpdate = source.matrixAutoUpdate;
  21921. return this;
  21922. };
  21923. _proto.toJSON = function toJSON(meta) {
  21924. var data = _Object3D.prototype.toJSON.call(this, meta);
  21925. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  21926. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  21927. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  21928. return data;
  21929. };
  21930. return Scene;
  21931. }(Object3D);
  21932. function InterleavedBuffer(array, stride) {
  21933. this.array = array;
  21934. this.stride = stride;
  21935. this.count = array !== undefined ? array.length / stride : 0;
  21936. this.usage = StaticDrawUsage;
  21937. this.updateRange = {
  21938. offset: 0,
  21939. count: -1
  21940. };
  21941. this.version = 0;
  21942. this.uuid = MathUtils.generateUUID();
  21943. }
  21944. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  21945. set: function set(value) {
  21946. if (value === true) this.version++;
  21947. }
  21948. });
  21949. Object.assign(InterleavedBuffer.prototype, {
  21950. isInterleavedBuffer: true,
  21951. onUploadCallback: function onUploadCallback() {},
  21952. setUsage: function setUsage(value) {
  21953. this.usage = value;
  21954. return this;
  21955. },
  21956. copy: function copy(source) {
  21957. this.array = new source.array.constructor(source.array);
  21958. this.count = source.count;
  21959. this.stride = source.stride;
  21960. this.usage = source.usage;
  21961. return this;
  21962. },
  21963. copyAt: function copyAt(index1, attribute, index2) {
  21964. index1 *= this.stride;
  21965. index2 *= attribute.stride;
  21966. for (var i = 0, l = this.stride; i < l; i++) {
  21967. this.array[index1 + i] = attribute.array[index2 + i];
  21968. }
  21969. return this;
  21970. },
  21971. set: function set(value, offset) {
  21972. if (offset === void 0) {
  21973. offset = 0;
  21974. }
  21975. this.array.set(value, offset);
  21976. return this;
  21977. },
  21978. clone: function clone(data) {
  21979. if (data.arrayBuffers === undefined) {
  21980. data.arrayBuffers = {};
  21981. }
  21982. if (this.array.buffer._uuid === undefined) {
  21983. this.array.buffer._uuid = MathUtils.generateUUID();
  21984. }
  21985. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  21986. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  21987. }
  21988. var array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  21989. var ib = new InterleavedBuffer(array, this.stride);
  21990. ib.setUsage(this.usage);
  21991. return ib;
  21992. },
  21993. onUpload: function onUpload(callback) {
  21994. this.onUploadCallback = callback;
  21995. return this;
  21996. },
  21997. toJSON: function toJSON(data) {
  21998. if (data.arrayBuffers === undefined) {
  21999. data.arrayBuffers = {};
  22000. } // generate UUID for array buffer if necessary
  22001. if (this.array.buffer._uuid === undefined) {
  22002. this.array.buffer._uuid = MathUtils.generateUUID();
  22003. }
  22004. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  22005. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  22006. } //
  22007. return {
  22008. uuid: this.uuid,
  22009. buffer: this.array.buffer._uuid,
  22010. type: this.array.constructor.name,
  22011. stride: this.stride
  22012. };
  22013. }
  22014. });
  22015. var _vector$6 = new Vector3();
  22016. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  22017. this.name = '';
  22018. this.data = interleavedBuffer;
  22019. this.itemSize = itemSize;
  22020. this.offset = offset;
  22021. this.normalized = normalized === true;
  22022. }
  22023. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  22024. count: {
  22025. get: function get() {
  22026. return this.data.count;
  22027. }
  22028. },
  22029. array: {
  22030. get: function get() {
  22031. return this.data.array;
  22032. }
  22033. },
  22034. needsUpdate: {
  22035. set: function set(value) {
  22036. this.data.needsUpdate = value;
  22037. }
  22038. }
  22039. });
  22040. Object.assign(InterleavedBufferAttribute.prototype, {
  22041. isInterleavedBufferAttribute: true,
  22042. applyMatrix4: function applyMatrix4(m) {
  22043. for (var i = 0, l = this.data.count; i < l; i++) {
  22044. _vector$6.x = this.getX(i);
  22045. _vector$6.y = this.getY(i);
  22046. _vector$6.z = this.getZ(i);
  22047. _vector$6.applyMatrix4(m);
  22048. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  22049. }
  22050. return this;
  22051. },
  22052. setX: function setX(index, x) {
  22053. this.data.array[index * this.data.stride + this.offset] = x;
  22054. return this;
  22055. },
  22056. setY: function setY(index, y) {
  22057. this.data.array[index * this.data.stride + this.offset + 1] = y;
  22058. return this;
  22059. },
  22060. setZ: function setZ(index, z) {
  22061. this.data.array[index * this.data.stride + this.offset + 2] = z;
  22062. return this;
  22063. },
  22064. setW: function setW(index, w) {
  22065. this.data.array[index * this.data.stride + this.offset + 3] = w;
  22066. return this;
  22067. },
  22068. getX: function getX(index) {
  22069. return this.data.array[index * this.data.stride + this.offset];
  22070. },
  22071. getY: function getY(index) {
  22072. return this.data.array[index * this.data.stride + this.offset + 1];
  22073. },
  22074. getZ: function getZ(index) {
  22075. return this.data.array[index * this.data.stride + this.offset + 2];
  22076. },
  22077. getW: function getW(index) {
  22078. return this.data.array[index * this.data.stride + this.offset + 3];
  22079. },
  22080. setXY: function setXY(index, x, y) {
  22081. index = index * this.data.stride + this.offset;
  22082. this.data.array[index + 0] = x;
  22083. this.data.array[index + 1] = y;
  22084. return this;
  22085. },
  22086. setXYZ: function setXYZ(index, x, y, z) {
  22087. index = index * this.data.stride + this.offset;
  22088. this.data.array[index + 0] = x;
  22089. this.data.array[index + 1] = y;
  22090. this.data.array[index + 2] = z;
  22091. return this;
  22092. },
  22093. setXYZW: function setXYZW(index, x, y, z, w) {
  22094. index = index * this.data.stride + this.offset;
  22095. this.data.array[index + 0] = x;
  22096. this.data.array[index + 1] = y;
  22097. this.data.array[index + 2] = z;
  22098. this.data.array[index + 3] = w;
  22099. return this;
  22100. },
  22101. clone: function clone(data) {
  22102. if (data === undefined) {
  22103. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  22104. var array = [];
  22105. for (var i = 0; i < this.count; i++) {
  22106. var index = i * this.data.stride + this.offset;
  22107. for (var j = 0; j < this.itemSize; j++) {
  22108. array.push(this.data.array[index + j]);
  22109. }
  22110. }
  22111. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  22112. } else {
  22113. if (data.interleavedBuffers === undefined) {
  22114. data.interleavedBuffers = {};
  22115. }
  22116. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22117. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  22118. }
  22119. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  22120. }
  22121. },
  22122. toJSON: function toJSON(data) {
  22123. if (data === undefined) {
  22124. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  22125. var array = [];
  22126. for (var i = 0; i < this.count; i++) {
  22127. var index = i * this.data.stride + this.offset;
  22128. for (var j = 0; j < this.itemSize; j++) {
  22129. array.push(this.data.array[index + j]);
  22130. }
  22131. } // deinterleave data and save it as an ordinary buffer attribute for now
  22132. return {
  22133. itemSize: this.itemSize,
  22134. type: this.array.constructor.name,
  22135. array: array,
  22136. normalized: this.normalized
  22137. };
  22138. } else {
  22139. // save as true interlaved attribtue
  22140. if (data.interleavedBuffers === undefined) {
  22141. data.interleavedBuffers = {};
  22142. }
  22143. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22144. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  22145. }
  22146. return {
  22147. isInterleavedBufferAttribute: true,
  22148. itemSize: this.itemSize,
  22149. data: this.data.uuid,
  22150. offset: this.offset,
  22151. normalized: this.normalized
  22152. };
  22153. }
  22154. }
  22155. });
  22156. /**
  22157. * parameters = {
  22158. * color: <hex>,
  22159. * map: new THREE.Texture( <Image> ),
  22160. * alphaMap: new THREE.Texture( <Image> ),
  22161. * rotation: <float>,
  22162. * sizeAttenuation: <bool>
  22163. * }
  22164. */
  22165. function SpriteMaterial(parameters) {
  22166. Material.call(this);
  22167. this.type = 'SpriteMaterial';
  22168. this.color = new Color(0xffffff);
  22169. this.map = null;
  22170. this.alphaMap = null;
  22171. this.rotation = 0;
  22172. this.sizeAttenuation = true;
  22173. this.transparent = true;
  22174. this.setValues(parameters);
  22175. }
  22176. SpriteMaterial.prototype = Object.create(Material.prototype);
  22177. SpriteMaterial.prototype.constructor = SpriteMaterial;
  22178. SpriteMaterial.prototype.isSpriteMaterial = true;
  22179. SpriteMaterial.prototype.copy = function (source) {
  22180. Material.prototype.copy.call(this, source);
  22181. this.color.copy(source.color);
  22182. this.map = source.map;
  22183. this.alphaMap = source.alphaMap;
  22184. this.rotation = source.rotation;
  22185. this.sizeAttenuation = source.sizeAttenuation;
  22186. return this;
  22187. };
  22188. var _geometry;
  22189. var _intersectPoint = new Vector3();
  22190. var _worldScale = new Vector3();
  22191. var _mvPosition = new Vector3();
  22192. var _alignedPosition = new Vector2();
  22193. var _rotatedPosition = new Vector2();
  22194. var _viewWorldMatrix = new Matrix4();
  22195. var _vA$1 = new Vector3();
  22196. var _vB$1 = new Vector3();
  22197. var _vC$1 = new Vector3();
  22198. var _uvA$1 = new Vector2();
  22199. var _uvB$1 = new Vector2();
  22200. var _uvC$1 = new Vector2();
  22201. function Sprite(material) {
  22202. Object3D.call(this);
  22203. this.type = 'Sprite';
  22204. if (_geometry === undefined) {
  22205. _geometry = new BufferGeometry();
  22206. 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]);
  22207. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  22208. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  22209. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  22210. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  22211. }
  22212. this.geometry = _geometry;
  22213. this.material = material !== undefined ? material : new SpriteMaterial();
  22214. this.center = new Vector2(0.5, 0.5);
  22215. }
  22216. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  22217. constructor: Sprite,
  22218. isSprite: true,
  22219. raycast: function raycast(raycaster, intersects) {
  22220. if (raycaster.camera === null) {
  22221. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  22222. }
  22223. _worldScale.setFromMatrixScale(this.matrixWorld);
  22224. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  22225. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  22226. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  22227. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  22228. _worldScale.multiplyScalar(-_mvPosition.z);
  22229. }
  22230. var rotation = this.material.rotation;
  22231. var sin, cos;
  22232. if (rotation !== 0) {
  22233. cos = Math.cos(rotation);
  22234. sin = Math.sin(rotation);
  22235. }
  22236. var center = this.center;
  22237. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22238. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22239. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22240. _uvA$1.set(0, 0);
  22241. _uvB$1.set(1, 0);
  22242. _uvC$1.set(1, 1); // check first triangle
  22243. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  22244. if (intersect === null) {
  22245. // check second triangle
  22246. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22247. _uvB$1.set(0, 1);
  22248. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  22249. if (intersect === null) {
  22250. return;
  22251. }
  22252. }
  22253. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  22254. if (distance < raycaster.near || distance > raycaster.far) return;
  22255. intersects.push({
  22256. distance: distance,
  22257. point: _intersectPoint.clone(),
  22258. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  22259. face: null,
  22260. object: this
  22261. });
  22262. },
  22263. copy: function copy(source) {
  22264. Object3D.prototype.copy.call(this, source);
  22265. if (source.center !== undefined) this.center.copy(source.center);
  22266. this.material = source.material;
  22267. return this;
  22268. }
  22269. });
  22270. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  22271. // compute position in camera space
  22272. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  22273. if (sin !== undefined) {
  22274. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  22275. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  22276. } else {
  22277. _rotatedPosition.copy(_alignedPosition);
  22278. }
  22279. vertexPosition.copy(mvPosition);
  22280. vertexPosition.x += _rotatedPosition.x;
  22281. vertexPosition.y += _rotatedPosition.y; // transform to world space
  22282. vertexPosition.applyMatrix4(_viewWorldMatrix);
  22283. }
  22284. var _v1$4 = new Vector3();
  22285. var _v2$2 = new Vector3();
  22286. function LOD() {
  22287. Object3D.call(this);
  22288. this._currentLevel = 0;
  22289. this.type = 'LOD';
  22290. Object.defineProperties(this, {
  22291. levels: {
  22292. enumerable: true,
  22293. value: []
  22294. }
  22295. });
  22296. this.autoUpdate = true;
  22297. }
  22298. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  22299. constructor: LOD,
  22300. isLOD: true,
  22301. copy: function copy(source) {
  22302. Object3D.prototype.copy.call(this, source, false);
  22303. var levels = source.levels;
  22304. for (var i = 0, l = levels.length; i < l; i++) {
  22305. var level = levels[i];
  22306. this.addLevel(level.object.clone(), level.distance);
  22307. }
  22308. this.autoUpdate = source.autoUpdate;
  22309. return this;
  22310. },
  22311. addLevel: function addLevel(object, distance) {
  22312. if (distance === void 0) {
  22313. distance = 0;
  22314. }
  22315. distance = Math.abs(distance);
  22316. var levels = this.levels;
  22317. var l;
  22318. for (l = 0; l < levels.length; l++) {
  22319. if (distance < levels[l].distance) {
  22320. break;
  22321. }
  22322. }
  22323. levels.splice(l, 0, {
  22324. distance: distance,
  22325. object: object
  22326. });
  22327. this.add(object);
  22328. return this;
  22329. },
  22330. getCurrentLevel: function getCurrentLevel() {
  22331. return this._currentLevel;
  22332. },
  22333. getObjectForDistance: function getObjectForDistance(distance) {
  22334. var levels = this.levels;
  22335. if (levels.length > 0) {
  22336. var i, l;
  22337. for (i = 1, l = levels.length; i < l; i++) {
  22338. if (distance < levels[i].distance) {
  22339. break;
  22340. }
  22341. }
  22342. return levels[i - 1].object;
  22343. }
  22344. return null;
  22345. },
  22346. raycast: function raycast(raycaster, intersects) {
  22347. var levels = this.levels;
  22348. if (levels.length > 0) {
  22349. _v1$4.setFromMatrixPosition(this.matrixWorld);
  22350. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  22351. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  22352. }
  22353. },
  22354. update: function update(camera) {
  22355. var levels = this.levels;
  22356. if (levels.length > 1) {
  22357. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  22358. _v2$2.setFromMatrixPosition(this.matrixWorld);
  22359. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  22360. levels[0].object.visible = true;
  22361. var i, l;
  22362. for (i = 1, l = levels.length; i < l; i++) {
  22363. if (distance >= levels[i].distance) {
  22364. levels[i - 1].object.visible = false;
  22365. levels[i].object.visible = true;
  22366. } else {
  22367. break;
  22368. }
  22369. }
  22370. this._currentLevel = i - 1;
  22371. for (; i < l; i++) {
  22372. levels[i].object.visible = false;
  22373. }
  22374. }
  22375. },
  22376. toJSON: function toJSON(meta) {
  22377. var data = Object3D.prototype.toJSON.call(this, meta);
  22378. if (this.autoUpdate === false) data.object.autoUpdate = false;
  22379. data.object.levels = [];
  22380. var levels = this.levels;
  22381. for (var i = 0, l = levels.length; i < l; i++) {
  22382. var level = levels[i];
  22383. data.object.levels.push({
  22384. object: level.object.uuid,
  22385. distance: level.distance
  22386. });
  22387. }
  22388. return data;
  22389. }
  22390. });
  22391. var _basePosition = new Vector3();
  22392. var _skinIndex = new Vector4();
  22393. var _skinWeight = new Vector4();
  22394. var _vector$7 = new Vector3();
  22395. var _matrix$1 = new Matrix4();
  22396. function SkinnedMesh(geometry, material) {
  22397. if (geometry && geometry.isGeometry) {
  22398. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22399. }
  22400. Mesh.call(this, geometry, material);
  22401. this.type = 'SkinnedMesh';
  22402. this.bindMode = 'attached';
  22403. this.bindMatrix = new Matrix4();
  22404. this.bindMatrixInverse = new Matrix4();
  22405. }
  22406. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  22407. constructor: SkinnedMesh,
  22408. isSkinnedMesh: true,
  22409. copy: function copy(source) {
  22410. Mesh.prototype.copy.call(this, source);
  22411. this.bindMode = source.bindMode;
  22412. this.bindMatrix.copy(source.bindMatrix);
  22413. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  22414. this.skeleton = source.skeleton;
  22415. return this;
  22416. },
  22417. bind: function bind(skeleton, bindMatrix) {
  22418. this.skeleton = skeleton;
  22419. if (bindMatrix === undefined) {
  22420. this.updateMatrixWorld(true);
  22421. this.skeleton.calculateInverses();
  22422. bindMatrix = this.matrixWorld;
  22423. }
  22424. this.bindMatrix.copy(bindMatrix);
  22425. this.bindMatrixInverse.copy(bindMatrix).invert();
  22426. },
  22427. pose: function pose() {
  22428. this.skeleton.pose();
  22429. },
  22430. normalizeSkinWeights: function normalizeSkinWeights() {
  22431. var vector = new Vector4();
  22432. var skinWeight = this.geometry.attributes.skinWeight;
  22433. for (var i = 0, l = skinWeight.count; i < l; i++) {
  22434. vector.x = skinWeight.getX(i);
  22435. vector.y = skinWeight.getY(i);
  22436. vector.z = skinWeight.getZ(i);
  22437. vector.w = skinWeight.getW(i);
  22438. var scale = 1.0 / vector.manhattanLength();
  22439. if (scale !== Infinity) {
  22440. vector.multiplyScalar(scale);
  22441. } else {
  22442. vector.set(1, 0, 0, 0); // do something reasonable
  22443. }
  22444. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  22445. }
  22446. },
  22447. updateMatrixWorld: function updateMatrixWorld(force) {
  22448. Mesh.prototype.updateMatrixWorld.call(this, force);
  22449. if (this.bindMode === 'attached') {
  22450. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  22451. } else if (this.bindMode === 'detached') {
  22452. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  22453. } else {
  22454. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  22455. }
  22456. },
  22457. boneTransform: function boneTransform(index, target) {
  22458. var skeleton = this.skeleton;
  22459. var geometry = this.geometry;
  22460. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  22461. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  22462. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  22463. target.set(0, 0, 0);
  22464. for (var i = 0; i < 4; i++) {
  22465. var weight = _skinWeight.getComponent(i);
  22466. if (weight !== 0) {
  22467. var boneIndex = _skinIndex.getComponent(i);
  22468. _matrix$1.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  22469. target.addScaledVector(_vector$7.copy(_basePosition).applyMatrix4(_matrix$1), weight);
  22470. }
  22471. }
  22472. return target.applyMatrix4(this.bindMatrixInverse);
  22473. }
  22474. });
  22475. function Bone() {
  22476. Object3D.call(this);
  22477. this.type = 'Bone';
  22478. }
  22479. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  22480. constructor: Bone,
  22481. isBone: true
  22482. });
  22483. var _offsetMatrix = new Matrix4();
  22484. var _identityMatrix = new Matrix4();
  22485. function Skeleton(bones, boneInverses) {
  22486. if (bones === void 0) {
  22487. bones = [];
  22488. }
  22489. if (boneInverses === void 0) {
  22490. boneInverses = [];
  22491. }
  22492. this.uuid = MathUtils.generateUUID();
  22493. this.bones = bones.slice(0);
  22494. this.boneInverses = boneInverses;
  22495. this.boneMatrices = null;
  22496. this.boneTexture = null;
  22497. this.boneTextureSize = 0;
  22498. this.frame = -1;
  22499. this.init();
  22500. }
  22501. Object.assign(Skeleton.prototype, {
  22502. init: function init() {
  22503. var bones = this.bones;
  22504. var boneInverses = this.boneInverses;
  22505. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  22506. if (boneInverses.length === 0) {
  22507. this.calculateInverses();
  22508. } else {
  22509. // handle special case
  22510. if (bones.length !== boneInverses.length) {
  22511. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  22512. this.boneInverses = [];
  22513. for (var i = 0, il = this.bones.length; i < il; i++) {
  22514. this.boneInverses.push(new Matrix4());
  22515. }
  22516. }
  22517. }
  22518. },
  22519. calculateInverses: function calculateInverses() {
  22520. this.boneInverses.length = 0;
  22521. for (var i = 0, il = this.bones.length; i < il; i++) {
  22522. var inverse = new Matrix4();
  22523. if (this.bones[i]) {
  22524. inverse.copy(this.bones[i].matrixWorld).invert();
  22525. }
  22526. this.boneInverses.push(inverse);
  22527. }
  22528. },
  22529. pose: function pose() {
  22530. // recover the bind-time world matrices
  22531. for (var i = 0, il = this.bones.length; i < il; i++) {
  22532. var bone = this.bones[i];
  22533. if (bone) {
  22534. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  22535. }
  22536. } // compute the local matrices, positions, rotations and scales
  22537. for (var _i = 0, _il = this.bones.length; _i < _il; _i++) {
  22538. var _bone = this.bones[_i];
  22539. if (_bone) {
  22540. if (_bone.parent && _bone.parent.isBone) {
  22541. _bone.matrix.copy(_bone.parent.matrixWorld).invert();
  22542. _bone.matrix.multiply(_bone.matrixWorld);
  22543. } else {
  22544. _bone.matrix.copy(_bone.matrixWorld);
  22545. }
  22546. _bone.matrix.decompose(_bone.position, _bone.quaternion, _bone.scale);
  22547. }
  22548. }
  22549. },
  22550. update: function update() {
  22551. var bones = this.bones;
  22552. var boneInverses = this.boneInverses;
  22553. var boneMatrices = this.boneMatrices;
  22554. var boneTexture = this.boneTexture; // flatten bone matrices to array
  22555. for (var i = 0, il = bones.length; i < il; i++) {
  22556. // compute the offset between the current and the original transform
  22557. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  22558. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  22559. _offsetMatrix.toArray(boneMatrices, i * 16);
  22560. }
  22561. if (boneTexture !== null) {
  22562. boneTexture.needsUpdate = true;
  22563. }
  22564. },
  22565. clone: function clone() {
  22566. return new Skeleton(this.bones, this.boneInverses);
  22567. },
  22568. getBoneByName: function getBoneByName(name) {
  22569. for (var i = 0, il = this.bones.length; i < il; i++) {
  22570. var bone = this.bones[i];
  22571. if (bone.name === name) {
  22572. return bone;
  22573. }
  22574. }
  22575. return undefined;
  22576. },
  22577. dispose: function dispose() {
  22578. if (this.boneTexture !== null) {
  22579. this.boneTexture.dispose();
  22580. this.boneTexture = null;
  22581. }
  22582. },
  22583. fromJSON: function fromJSON(json, bones) {
  22584. this.uuid = json.uuid;
  22585. for (var i = 0, l = json.bones.length; i < l; i++) {
  22586. var uuid = json.bones[i];
  22587. var bone = bones[uuid];
  22588. if (bone === undefined) {
  22589. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  22590. bone = new Bone();
  22591. }
  22592. this.bones.push(bone);
  22593. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  22594. }
  22595. this.init();
  22596. return this;
  22597. },
  22598. toJSON: function toJSON() {
  22599. var data = {
  22600. metadata: {
  22601. version: 4.5,
  22602. type: 'Skeleton',
  22603. generator: 'Skeleton.toJSON'
  22604. },
  22605. bones: [],
  22606. boneInverses: []
  22607. };
  22608. data.uuid = this.uuid;
  22609. var bones = this.bones;
  22610. var boneInverses = this.boneInverses;
  22611. for (var i = 0, l = bones.length; i < l; i++) {
  22612. var bone = bones[i];
  22613. data.bones.push(bone.uuid);
  22614. var boneInverse = boneInverses[i];
  22615. data.boneInverses.push(boneInverse.toArray());
  22616. }
  22617. return data;
  22618. }
  22619. });
  22620. var _instanceLocalMatrix = new Matrix4();
  22621. var _instanceWorldMatrix = new Matrix4();
  22622. var _instanceIntersects = [];
  22623. var _mesh = new Mesh();
  22624. function InstancedMesh(geometry, material, count) {
  22625. Mesh.call(this, geometry, material);
  22626. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  22627. this.instanceColor = null;
  22628. this.count = count;
  22629. this.frustumCulled = false;
  22630. }
  22631. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  22632. constructor: InstancedMesh,
  22633. isInstancedMesh: true,
  22634. copy: function copy(source) {
  22635. Mesh.prototype.copy.call(this, source);
  22636. this.instanceMatrix.copy(source.instanceMatrix);
  22637. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  22638. this.count = source.count;
  22639. return this;
  22640. },
  22641. getColorAt: function getColorAt(index, color) {
  22642. color.fromArray(this.instanceColor.array, index * 3);
  22643. },
  22644. getMatrixAt: function getMatrixAt(index, matrix) {
  22645. matrix.fromArray(this.instanceMatrix.array, index * 16);
  22646. },
  22647. raycast: function raycast(raycaster, intersects) {
  22648. var matrixWorld = this.matrixWorld;
  22649. var raycastTimes = this.count;
  22650. _mesh.geometry = this.geometry;
  22651. _mesh.material = this.material;
  22652. if (_mesh.material === undefined) return;
  22653. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  22654. // calculate the world matrix for each instance
  22655. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  22656. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  22657. _mesh.matrixWorld = _instanceWorldMatrix;
  22658. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  22659. for (var i = 0, l = _instanceIntersects.length; i < l; i++) {
  22660. var intersect = _instanceIntersects[i];
  22661. intersect.instanceId = instanceId;
  22662. intersect.object = this;
  22663. intersects.push(intersect);
  22664. }
  22665. _instanceIntersects.length = 0;
  22666. }
  22667. },
  22668. setColorAt: function setColorAt(index, color) {
  22669. if (this.instanceColor === null) {
  22670. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  22671. }
  22672. color.toArray(this.instanceColor.array, index * 3);
  22673. },
  22674. setMatrixAt: function setMatrixAt(index, matrix) {
  22675. matrix.toArray(this.instanceMatrix.array, index * 16);
  22676. },
  22677. updateMorphTargets: function updateMorphTargets() {},
  22678. dispose: function dispose() {
  22679. this.dispatchEvent({
  22680. type: 'dispose'
  22681. });
  22682. }
  22683. });
  22684. /**
  22685. * parameters = {
  22686. * color: <hex>,
  22687. * opacity: <float>,
  22688. *
  22689. * linewidth: <float>,
  22690. * linecap: "round",
  22691. * linejoin: "round"
  22692. * }
  22693. */
  22694. function LineBasicMaterial(parameters) {
  22695. Material.call(this);
  22696. this.type = 'LineBasicMaterial';
  22697. this.color = new Color(0xffffff);
  22698. this.linewidth = 1;
  22699. this.linecap = 'round';
  22700. this.linejoin = 'round';
  22701. this.morphTargets = false;
  22702. this.setValues(parameters);
  22703. }
  22704. LineBasicMaterial.prototype = Object.create(Material.prototype);
  22705. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  22706. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  22707. LineBasicMaterial.prototype.copy = function (source) {
  22708. Material.prototype.copy.call(this, source);
  22709. this.color.copy(source.color);
  22710. this.linewidth = source.linewidth;
  22711. this.linecap = source.linecap;
  22712. this.linejoin = source.linejoin;
  22713. this.morphTargets = source.morphTargets;
  22714. return this;
  22715. };
  22716. var _start = new Vector3();
  22717. var _end = new Vector3();
  22718. var _inverseMatrix$1 = new Matrix4();
  22719. var _ray$1 = new Ray();
  22720. var _sphere$2 = new Sphere();
  22721. function Line(geometry, material) {
  22722. if (geometry === void 0) {
  22723. geometry = new BufferGeometry();
  22724. }
  22725. if (material === void 0) {
  22726. material = new LineBasicMaterial();
  22727. }
  22728. Object3D.call(this);
  22729. this.type = 'Line';
  22730. this.geometry = geometry;
  22731. this.material = material;
  22732. this.updateMorphTargets();
  22733. }
  22734. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  22735. constructor: Line,
  22736. isLine: true,
  22737. copy: function copy(source) {
  22738. Object3D.prototype.copy.call(this, source);
  22739. this.material = source.material;
  22740. this.geometry = source.geometry;
  22741. return this;
  22742. },
  22743. computeLineDistances: function computeLineDistances() {
  22744. var geometry = this.geometry;
  22745. if (geometry.isBufferGeometry) {
  22746. // we assume non-indexed geometry
  22747. if (geometry.index === null) {
  22748. var positionAttribute = geometry.attributes.position;
  22749. var lineDistances = [0];
  22750. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  22751. _start.fromBufferAttribute(positionAttribute, i - 1);
  22752. _end.fromBufferAttribute(positionAttribute, i);
  22753. lineDistances[i] = lineDistances[i - 1];
  22754. lineDistances[i] += _start.distanceTo(_end);
  22755. }
  22756. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22757. } else {
  22758. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22759. }
  22760. } else if (geometry.isGeometry) {
  22761. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22762. }
  22763. return this;
  22764. },
  22765. raycast: function raycast(raycaster, intersects) {
  22766. var geometry = this.geometry;
  22767. var matrixWorld = this.matrixWorld;
  22768. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  22769. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22770. _sphere$2.copy(geometry.boundingSphere);
  22771. _sphere$2.applyMatrix4(matrixWorld);
  22772. _sphere$2.radius += threshold;
  22773. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  22774. _inverseMatrix$1.copy(matrixWorld).invert();
  22775. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  22776. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22777. var localThresholdSq = localThreshold * localThreshold;
  22778. var vStart = new Vector3();
  22779. var vEnd = new Vector3();
  22780. var interSegment = new Vector3();
  22781. var interRay = new Vector3();
  22782. var step = this.isLineSegments ? 2 : 1;
  22783. if (geometry.isBufferGeometry) {
  22784. var index = geometry.index;
  22785. var attributes = geometry.attributes;
  22786. var positionAttribute = attributes.position;
  22787. if (index !== null) {
  22788. var indices = index.array;
  22789. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  22790. var a = indices[i];
  22791. var b = indices[i + 1];
  22792. vStart.fromBufferAttribute(positionAttribute, a);
  22793. vEnd.fromBufferAttribute(positionAttribute, b);
  22794. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22795. if (distSq > localThresholdSq) continue;
  22796. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22797. var distance = raycaster.ray.origin.distanceTo(interRay);
  22798. if (distance < raycaster.near || distance > raycaster.far) continue;
  22799. intersects.push({
  22800. distance: distance,
  22801. // What do we want? intersection point on the ray or on the segment??
  22802. // point: raycaster.ray.at( distance ),
  22803. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22804. index: i,
  22805. face: null,
  22806. faceIndex: null,
  22807. object: this
  22808. });
  22809. }
  22810. } else {
  22811. for (var _i = 0, _l = positionAttribute.count - 1; _i < _l; _i += step) {
  22812. vStart.fromBufferAttribute(positionAttribute, _i);
  22813. vEnd.fromBufferAttribute(positionAttribute, _i + 1);
  22814. var _distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22815. if (_distSq > localThresholdSq) continue;
  22816. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22817. var _distance = raycaster.ray.origin.distanceTo(interRay);
  22818. if (_distance < raycaster.near || _distance > raycaster.far) continue;
  22819. intersects.push({
  22820. distance: _distance,
  22821. // What do we want? intersection point on the ray or on the segment??
  22822. // point: raycaster.ray.at( distance ),
  22823. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22824. index: _i,
  22825. face: null,
  22826. faceIndex: null,
  22827. object: this
  22828. });
  22829. }
  22830. }
  22831. } else if (geometry.isGeometry) {
  22832. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22833. }
  22834. },
  22835. updateMorphTargets: function updateMorphTargets() {
  22836. var geometry = this.geometry;
  22837. if (geometry.isBufferGeometry) {
  22838. var morphAttributes = geometry.morphAttributes;
  22839. var keys = Object.keys(morphAttributes);
  22840. if (keys.length > 0) {
  22841. var morphAttribute = morphAttributes[keys[0]];
  22842. if (morphAttribute !== undefined) {
  22843. this.morphTargetInfluences = [];
  22844. this.morphTargetDictionary = {};
  22845. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  22846. var name = morphAttribute[m].name || String(m);
  22847. this.morphTargetInfluences.push(0);
  22848. this.morphTargetDictionary[name] = m;
  22849. }
  22850. }
  22851. }
  22852. } else {
  22853. var morphTargets = geometry.morphTargets;
  22854. if (morphTargets !== undefined && morphTargets.length > 0) {
  22855. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  22856. }
  22857. }
  22858. }
  22859. });
  22860. var _start$1 = new Vector3();
  22861. var _end$1 = new Vector3();
  22862. function LineSegments(geometry, material) {
  22863. Line.call(this, geometry, material);
  22864. this.type = 'LineSegments';
  22865. }
  22866. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  22867. constructor: LineSegments,
  22868. isLineSegments: true,
  22869. computeLineDistances: function computeLineDistances() {
  22870. var geometry = this.geometry;
  22871. if (geometry.isBufferGeometry) {
  22872. // we assume non-indexed geometry
  22873. if (geometry.index === null) {
  22874. var positionAttribute = geometry.attributes.position;
  22875. var lineDistances = [];
  22876. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  22877. _start$1.fromBufferAttribute(positionAttribute, i);
  22878. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  22879. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  22880. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  22881. }
  22882. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22883. } else {
  22884. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22885. }
  22886. } else if (geometry.isGeometry) {
  22887. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22888. }
  22889. return this;
  22890. }
  22891. });
  22892. function LineLoop(geometry, material) {
  22893. Line.call(this, geometry, material);
  22894. this.type = 'LineLoop';
  22895. }
  22896. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  22897. constructor: LineLoop,
  22898. isLineLoop: true
  22899. });
  22900. /**
  22901. * parameters = {
  22902. * color: <hex>,
  22903. * opacity: <float>,
  22904. * map: new THREE.Texture( <Image> ),
  22905. * alphaMap: new THREE.Texture( <Image> ),
  22906. *
  22907. * size: <float>,
  22908. * sizeAttenuation: <bool>
  22909. *
  22910. * morphTargets: <bool>
  22911. * }
  22912. */
  22913. function PointsMaterial(parameters) {
  22914. Material.call(this);
  22915. this.type = 'PointsMaterial';
  22916. this.color = new Color(0xffffff);
  22917. this.map = null;
  22918. this.alphaMap = null;
  22919. this.size = 1;
  22920. this.sizeAttenuation = true;
  22921. this.morphTargets = false;
  22922. this.setValues(parameters);
  22923. }
  22924. PointsMaterial.prototype = Object.create(Material.prototype);
  22925. PointsMaterial.prototype.constructor = PointsMaterial;
  22926. PointsMaterial.prototype.isPointsMaterial = true;
  22927. PointsMaterial.prototype.copy = function (source) {
  22928. Material.prototype.copy.call(this, source);
  22929. this.color.copy(source.color);
  22930. this.map = source.map;
  22931. this.alphaMap = source.alphaMap;
  22932. this.size = source.size;
  22933. this.sizeAttenuation = source.sizeAttenuation;
  22934. this.morphTargets = source.morphTargets;
  22935. return this;
  22936. };
  22937. var _inverseMatrix$2 = new Matrix4();
  22938. var _ray$2 = new Ray();
  22939. var _sphere$3 = new Sphere();
  22940. var _position$1 = new Vector3();
  22941. function Points(geometry, material) {
  22942. if (geometry === void 0) {
  22943. geometry = new BufferGeometry();
  22944. }
  22945. if (material === void 0) {
  22946. material = new PointsMaterial();
  22947. }
  22948. Object3D.call(this);
  22949. this.type = 'Points';
  22950. this.geometry = geometry;
  22951. this.material = material;
  22952. this.updateMorphTargets();
  22953. }
  22954. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  22955. constructor: Points,
  22956. isPoints: true,
  22957. copy: function copy(source) {
  22958. Object3D.prototype.copy.call(this, source);
  22959. this.material = source.material;
  22960. this.geometry = source.geometry;
  22961. return this;
  22962. },
  22963. raycast: function raycast(raycaster, intersects) {
  22964. var geometry = this.geometry;
  22965. var matrixWorld = this.matrixWorld;
  22966. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  22967. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22968. _sphere$3.copy(geometry.boundingSphere);
  22969. _sphere$3.applyMatrix4(matrixWorld);
  22970. _sphere$3.radius += threshold;
  22971. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  22972. _inverseMatrix$2.copy(matrixWorld).invert();
  22973. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  22974. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22975. var localThresholdSq = localThreshold * localThreshold;
  22976. if (geometry.isBufferGeometry) {
  22977. var index = geometry.index;
  22978. var attributes = geometry.attributes;
  22979. var positionAttribute = attributes.position;
  22980. if (index !== null) {
  22981. var indices = index.array;
  22982. for (var i = 0, il = indices.length; i < il; i++) {
  22983. var a = indices[i];
  22984. _position$1.fromBufferAttribute(positionAttribute, a);
  22985. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22986. }
  22987. } else {
  22988. for (var _i = 0, l = positionAttribute.count; _i < l; _i++) {
  22989. _position$1.fromBufferAttribute(positionAttribute, _i);
  22990. testPoint(_position$1, _i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22991. }
  22992. }
  22993. } else {
  22994. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22995. }
  22996. },
  22997. updateMorphTargets: function updateMorphTargets() {
  22998. var geometry = this.geometry;
  22999. if (geometry.isBufferGeometry) {
  23000. var morphAttributes = geometry.morphAttributes;
  23001. var keys = Object.keys(morphAttributes);
  23002. if (keys.length > 0) {
  23003. var morphAttribute = morphAttributes[keys[0]];
  23004. if (morphAttribute !== undefined) {
  23005. this.morphTargetInfluences = [];
  23006. this.morphTargetDictionary = {};
  23007. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  23008. var name = morphAttribute[m].name || String(m);
  23009. this.morphTargetInfluences.push(0);
  23010. this.morphTargetDictionary[name] = m;
  23011. }
  23012. }
  23013. }
  23014. } else {
  23015. var morphTargets = geometry.morphTargets;
  23016. if (morphTargets !== undefined && morphTargets.length > 0) {
  23017. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  23018. }
  23019. }
  23020. }
  23021. });
  23022. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  23023. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  23024. if (rayPointDistanceSq < localThresholdSq) {
  23025. var intersectPoint = new Vector3();
  23026. _ray$2.closestPointToPoint(point, intersectPoint);
  23027. intersectPoint.applyMatrix4(matrixWorld);
  23028. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  23029. if (distance < raycaster.near || distance > raycaster.far) return;
  23030. intersects.push({
  23031. distance: distance,
  23032. distanceToRay: Math.sqrt(rayPointDistanceSq),
  23033. point: intersectPoint,
  23034. index: index,
  23035. face: null,
  23036. object: object
  23037. });
  23038. }
  23039. }
  23040. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23041. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23042. this.format = format !== undefined ? format : RGBFormat;
  23043. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  23044. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  23045. this.generateMipmaps = false;
  23046. var scope = this;
  23047. function updateVideo() {
  23048. scope.needsUpdate = true;
  23049. video.requestVideoFrameCallback(updateVideo);
  23050. }
  23051. if ('requestVideoFrameCallback' in video) {
  23052. video.requestVideoFrameCallback(updateVideo);
  23053. }
  23054. }
  23055. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  23056. constructor: VideoTexture,
  23057. clone: function clone() {
  23058. return new this.constructor(this.image).copy(this);
  23059. },
  23060. isVideoTexture: true,
  23061. update: function update() {
  23062. var video = this.image;
  23063. var hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  23064. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  23065. this.needsUpdate = true;
  23066. }
  23067. }
  23068. });
  23069. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  23070. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  23071. this.image = {
  23072. width: width,
  23073. height: height
  23074. };
  23075. this.mipmaps = mipmaps; // no flipping for cube textures
  23076. // (also flipping doesn't work for compressed textures )
  23077. this.flipY = false; // can't generate mipmaps for compressed textures
  23078. // mips must be embedded in DDS files
  23079. this.generateMipmaps = false;
  23080. }
  23081. CompressedTexture.prototype = Object.create(Texture.prototype);
  23082. CompressedTexture.prototype.constructor = CompressedTexture;
  23083. CompressedTexture.prototype.isCompressedTexture = true;
  23084. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23085. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23086. this.needsUpdate = true;
  23087. }
  23088. CanvasTexture.prototype = Object.create(Texture.prototype);
  23089. CanvasTexture.prototype.constructor = CanvasTexture;
  23090. CanvasTexture.prototype.isCanvasTexture = true;
  23091. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  23092. format = format !== undefined ? format : DepthFormat;
  23093. if (format !== DepthFormat && format !== DepthStencilFormat) {
  23094. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  23095. }
  23096. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  23097. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  23098. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23099. this.image = {
  23100. width: width,
  23101. height: height
  23102. };
  23103. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  23104. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  23105. this.flipY = false;
  23106. this.generateMipmaps = false;
  23107. }
  23108. DepthTexture.prototype = Object.create(Texture.prototype);
  23109. DepthTexture.prototype.constructor = DepthTexture;
  23110. DepthTexture.prototype.isDepthTexture = true;
  23111. var CircleGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23112. _inheritsLoose(CircleGeometry, _BufferGeometry);
  23113. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  23114. var _this;
  23115. if (radius === void 0) {
  23116. radius = 1;
  23117. }
  23118. if (segments === void 0) {
  23119. segments = 8;
  23120. }
  23121. if (thetaStart === void 0) {
  23122. thetaStart = 0;
  23123. }
  23124. if (thetaLength === void 0) {
  23125. thetaLength = Math.PI * 2;
  23126. }
  23127. _this = _BufferGeometry.call(this) || this;
  23128. _this.type = 'CircleGeometry';
  23129. _this.parameters = {
  23130. radius: radius,
  23131. segments: segments,
  23132. thetaStart: thetaStart,
  23133. thetaLength: thetaLength
  23134. };
  23135. segments = Math.max(3, segments); // buffers
  23136. var indices = [];
  23137. var vertices = [];
  23138. var normals = [];
  23139. var uvs = []; // helper variables
  23140. var vertex = new Vector3();
  23141. var uv = new Vector2(); // center point
  23142. vertices.push(0, 0, 0);
  23143. normals.push(0, 0, 1);
  23144. uvs.push(0.5, 0.5);
  23145. for (var s = 0, i = 3; s <= segments; s++, i += 3) {
  23146. var segment = thetaStart + s / segments * thetaLength; // vertex
  23147. vertex.x = radius * Math.cos(segment);
  23148. vertex.y = radius * Math.sin(segment);
  23149. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23150. normals.push(0, 0, 1); // uvs
  23151. uv.x = (vertices[i] / radius + 1) / 2;
  23152. uv.y = (vertices[i + 1] / radius + 1) / 2;
  23153. uvs.push(uv.x, uv.y);
  23154. } // indices
  23155. for (var _i = 1; _i <= segments; _i++) {
  23156. indices.push(_i, _i + 1, 0);
  23157. } // build geometry
  23158. _this.setIndex(indices);
  23159. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23160. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23161. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23162. return _this;
  23163. }
  23164. return CircleGeometry;
  23165. }(BufferGeometry);
  23166. var CylinderGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23167. _inheritsLoose(CylinderGeometry, _BufferGeometry);
  23168. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23169. var _this;
  23170. if (radiusTop === void 0) {
  23171. radiusTop = 1;
  23172. }
  23173. if (radiusBottom === void 0) {
  23174. radiusBottom = 1;
  23175. }
  23176. if (height === void 0) {
  23177. height = 1;
  23178. }
  23179. if (radialSegments === void 0) {
  23180. radialSegments = 8;
  23181. }
  23182. if (heightSegments === void 0) {
  23183. heightSegments = 1;
  23184. }
  23185. if (openEnded === void 0) {
  23186. openEnded = false;
  23187. }
  23188. if (thetaStart === void 0) {
  23189. thetaStart = 0;
  23190. }
  23191. if (thetaLength === void 0) {
  23192. thetaLength = Math.PI * 2;
  23193. }
  23194. _this = _BufferGeometry.call(this) || this;
  23195. _this.type = 'CylinderGeometry';
  23196. _this.parameters = {
  23197. radiusTop: radiusTop,
  23198. radiusBottom: radiusBottom,
  23199. height: height,
  23200. radialSegments: radialSegments,
  23201. heightSegments: heightSegments,
  23202. openEnded: openEnded,
  23203. thetaStart: thetaStart,
  23204. thetaLength: thetaLength
  23205. };
  23206. var scope = _assertThisInitialized(_this);
  23207. radialSegments = Math.floor(radialSegments);
  23208. heightSegments = Math.floor(heightSegments); // buffers
  23209. var indices = [];
  23210. var vertices = [];
  23211. var normals = [];
  23212. var uvs = []; // helper variables
  23213. var index = 0;
  23214. var indexArray = [];
  23215. var halfHeight = height / 2;
  23216. var groupStart = 0; // generate geometry
  23217. generateTorso();
  23218. if (openEnded === false) {
  23219. if (radiusTop > 0) generateCap(true);
  23220. if (radiusBottom > 0) generateCap(false);
  23221. } // build geometry
  23222. _this.setIndex(indices);
  23223. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23224. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23225. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23226. function generateTorso() {
  23227. var normal = new Vector3();
  23228. var vertex = new Vector3();
  23229. var groupCount = 0; // this will be used to calculate the normal
  23230. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  23231. for (var y = 0; y <= heightSegments; y++) {
  23232. var indexRow = [];
  23233. var v = y / heightSegments; // calculate the radius of the current row
  23234. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  23235. for (var x = 0; x <= radialSegments; x++) {
  23236. var u = x / radialSegments;
  23237. var theta = u * thetaLength + thetaStart;
  23238. var sinTheta = Math.sin(theta);
  23239. var cosTheta = Math.cos(theta); // vertex
  23240. vertex.x = radius * sinTheta;
  23241. vertex.y = -v * height + halfHeight;
  23242. vertex.z = radius * cosTheta;
  23243. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23244. normal.set(sinTheta, slope, cosTheta).normalize();
  23245. normals.push(normal.x, normal.y, normal.z); // uv
  23246. uvs.push(u, 1 - v); // save index of vertex in respective row
  23247. indexRow.push(index++);
  23248. } // now save vertices of the row in our index array
  23249. indexArray.push(indexRow);
  23250. } // generate indices
  23251. for (var _x = 0; _x < radialSegments; _x++) {
  23252. for (var _y = 0; _y < heightSegments; _y++) {
  23253. // we use the index array to access the correct indices
  23254. var a = indexArray[_y][_x];
  23255. var b = indexArray[_y + 1][_x];
  23256. var c = indexArray[_y + 1][_x + 1];
  23257. var d = indexArray[_y][_x + 1]; // faces
  23258. indices.push(a, b, d);
  23259. indices.push(b, c, d); // update group counter
  23260. groupCount += 6;
  23261. }
  23262. } // add a group to the geometry. this will ensure multi material support
  23263. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  23264. groupStart += groupCount;
  23265. }
  23266. function generateCap(top) {
  23267. // save the index of the first center vertex
  23268. var centerIndexStart = index;
  23269. var uv = new Vector2();
  23270. var vertex = new Vector3();
  23271. var groupCount = 0;
  23272. var radius = top === true ? radiusTop : radiusBottom;
  23273. var sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  23274. // because the geometry needs one set of uvs per face,
  23275. // we must generate a center vertex per face/segment
  23276. for (var x = 1; x <= radialSegments; x++) {
  23277. // vertex
  23278. vertices.push(0, halfHeight * sign, 0); // normal
  23279. normals.push(0, sign, 0); // uv
  23280. uvs.push(0.5, 0.5); // increase index
  23281. index++;
  23282. } // save the index of the last center vertex
  23283. var centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  23284. for (var _x2 = 0; _x2 <= radialSegments; _x2++) {
  23285. var u = _x2 / radialSegments;
  23286. var theta = u * thetaLength + thetaStart;
  23287. var cosTheta = Math.cos(theta);
  23288. var sinTheta = Math.sin(theta); // vertex
  23289. vertex.x = radius * sinTheta;
  23290. vertex.y = halfHeight * sign;
  23291. vertex.z = radius * cosTheta;
  23292. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23293. normals.push(0, sign, 0); // uv
  23294. uv.x = cosTheta * 0.5 + 0.5;
  23295. uv.y = sinTheta * 0.5 * sign + 0.5;
  23296. uvs.push(uv.x, uv.y); // increase index
  23297. index++;
  23298. } // generate indices
  23299. for (var _x3 = 0; _x3 < radialSegments; _x3++) {
  23300. var c = centerIndexStart + _x3;
  23301. var i = centerIndexEnd + _x3;
  23302. if (top === true) {
  23303. // face top
  23304. indices.push(i, i + 1, c);
  23305. } else {
  23306. // face bottom
  23307. indices.push(i + 1, i, c);
  23308. }
  23309. groupCount += 3;
  23310. } // add a group to the geometry. this will ensure multi material support
  23311. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  23312. groupStart += groupCount;
  23313. }
  23314. return _this;
  23315. }
  23316. return CylinderGeometry;
  23317. }(BufferGeometry);
  23318. var ConeGeometry = /*#__PURE__*/function (_CylinderGeometry) {
  23319. _inheritsLoose(ConeGeometry, _CylinderGeometry);
  23320. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23321. var _this;
  23322. if (radius === void 0) {
  23323. radius = 1;
  23324. }
  23325. if (height === void 0) {
  23326. height = 1;
  23327. }
  23328. if (radialSegments === void 0) {
  23329. radialSegments = 8;
  23330. }
  23331. if (heightSegments === void 0) {
  23332. heightSegments = 1;
  23333. }
  23334. if (openEnded === void 0) {
  23335. openEnded = false;
  23336. }
  23337. if (thetaStart === void 0) {
  23338. thetaStart = 0;
  23339. }
  23340. if (thetaLength === void 0) {
  23341. thetaLength = Math.PI * 2;
  23342. }
  23343. _this = _CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
  23344. _this.type = 'ConeGeometry';
  23345. _this.parameters = {
  23346. radius: radius,
  23347. height: height,
  23348. radialSegments: radialSegments,
  23349. heightSegments: heightSegments,
  23350. openEnded: openEnded,
  23351. thetaStart: thetaStart,
  23352. thetaLength: thetaLength
  23353. };
  23354. return _this;
  23355. }
  23356. return ConeGeometry;
  23357. }(CylinderGeometry);
  23358. var PolyhedronGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23359. _inheritsLoose(PolyhedronGeometry, _BufferGeometry);
  23360. function PolyhedronGeometry(vertices, indices, radius, detail) {
  23361. var _this;
  23362. if (radius === void 0) {
  23363. radius = 1;
  23364. }
  23365. if (detail === void 0) {
  23366. detail = 0;
  23367. }
  23368. _this = _BufferGeometry.call(this) || this;
  23369. _this.type = 'PolyhedronGeometry';
  23370. _this.parameters = {
  23371. vertices: vertices,
  23372. indices: indices,
  23373. radius: radius,
  23374. detail: detail
  23375. }; // default buffer data
  23376. var vertexBuffer = [];
  23377. var uvBuffer = []; // the subdivision creates the vertex buffer data
  23378. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  23379. applyRadius(radius); // finally, create the uv data
  23380. generateUVs(); // build non-indexed geometry
  23381. _this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  23382. _this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  23383. _this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  23384. if (detail === 0) {
  23385. _this.computeVertexNormals(); // flat normals
  23386. } else {
  23387. _this.normalizeNormals(); // smooth normals
  23388. } // helper functions
  23389. function subdivide(detail) {
  23390. var a = new Vector3();
  23391. var b = new Vector3();
  23392. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  23393. for (var i = 0; i < indices.length; i += 3) {
  23394. // get the vertices of the face
  23395. getVertexByIndex(indices[i + 0], a);
  23396. getVertexByIndex(indices[i + 1], b);
  23397. getVertexByIndex(indices[i + 2], c); // perform subdivision
  23398. subdivideFace(a, b, c, detail);
  23399. }
  23400. }
  23401. function subdivideFace(a, b, c, detail) {
  23402. var cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  23403. var v = []; // construct all of the vertices for this subdivision
  23404. for (var i = 0; i <= cols; i++) {
  23405. v[i] = [];
  23406. var aj = a.clone().lerp(c, i / cols);
  23407. var bj = b.clone().lerp(c, i / cols);
  23408. var rows = cols - i;
  23409. for (var j = 0; j <= rows; j++) {
  23410. if (j === 0 && i === cols) {
  23411. v[i][j] = aj;
  23412. } else {
  23413. v[i][j] = aj.clone().lerp(bj, j / rows);
  23414. }
  23415. }
  23416. } // construct all of the faces
  23417. for (var _i = 0; _i < cols; _i++) {
  23418. for (var _j = 0; _j < 2 * (cols - _i) - 1; _j++) {
  23419. var k = Math.floor(_j / 2);
  23420. if (_j % 2 === 0) {
  23421. pushVertex(v[_i][k + 1]);
  23422. pushVertex(v[_i + 1][k]);
  23423. pushVertex(v[_i][k]);
  23424. } else {
  23425. pushVertex(v[_i][k + 1]);
  23426. pushVertex(v[_i + 1][k + 1]);
  23427. pushVertex(v[_i + 1][k]);
  23428. }
  23429. }
  23430. }
  23431. }
  23432. function applyRadius(radius) {
  23433. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  23434. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23435. vertex.x = vertexBuffer[i + 0];
  23436. vertex.y = vertexBuffer[i + 1];
  23437. vertex.z = vertexBuffer[i + 2];
  23438. vertex.normalize().multiplyScalar(radius);
  23439. vertexBuffer[i + 0] = vertex.x;
  23440. vertexBuffer[i + 1] = vertex.y;
  23441. vertexBuffer[i + 2] = vertex.z;
  23442. }
  23443. }
  23444. function generateUVs() {
  23445. var vertex = new Vector3();
  23446. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23447. vertex.x = vertexBuffer[i + 0];
  23448. vertex.y = vertexBuffer[i + 1];
  23449. vertex.z = vertexBuffer[i + 2];
  23450. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  23451. var v = inclination(vertex) / Math.PI + 0.5;
  23452. uvBuffer.push(u, 1 - v);
  23453. }
  23454. correctUVs();
  23455. correctSeam();
  23456. }
  23457. function correctSeam() {
  23458. // handle case when face straddles the seam, see #3269
  23459. for (var i = 0; i < uvBuffer.length; i += 6) {
  23460. // uv data of a single face
  23461. var x0 = uvBuffer[i + 0];
  23462. var x1 = uvBuffer[i + 2];
  23463. var x2 = uvBuffer[i + 4];
  23464. var max = Math.max(x0, x1, x2);
  23465. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  23466. if (max > 0.9 && min < 0.1) {
  23467. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  23468. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  23469. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  23470. }
  23471. }
  23472. }
  23473. function pushVertex(vertex) {
  23474. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  23475. }
  23476. function getVertexByIndex(index, vertex) {
  23477. var stride = index * 3;
  23478. vertex.x = vertices[stride + 0];
  23479. vertex.y = vertices[stride + 1];
  23480. vertex.z = vertices[stride + 2];
  23481. }
  23482. function correctUVs() {
  23483. var a = new Vector3();
  23484. var b = new Vector3();
  23485. var c = new Vector3();
  23486. var centroid = new Vector3();
  23487. var uvA = new Vector2();
  23488. var uvB = new Vector2();
  23489. var uvC = new Vector2();
  23490. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  23491. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  23492. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  23493. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  23494. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  23495. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  23496. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  23497. centroid.copy(a).add(b).add(c).divideScalar(3);
  23498. var azi = azimuth(centroid);
  23499. correctUV(uvA, j + 0, a, azi);
  23500. correctUV(uvB, j + 2, b, azi);
  23501. correctUV(uvC, j + 4, c, azi);
  23502. }
  23503. }
  23504. function correctUV(uv, stride, vector, azimuth) {
  23505. if (azimuth < 0 && uv.x === 1) {
  23506. uvBuffer[stride] = uv.x - 1;
  23507. }
  23508. if (vector.x === 0 && vector.z === 0) {
  23509. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  23510. }
  23511. } // Angle around the Y axis, counter-clockwise when looking from above.
  23512. function azimuth(vector) {
  23513. return Math.atan2(vector.z, -vector.x);
  23514. } // Angle above the XZ plane.
  23515. function inclination(vector) {
  23516. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  23517. }
  23518. return _this;
  23519. }
  23520. return PolyhedronGeometry;
  23521. }(BufferGeometry);
  23522. var DodecahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  23523. _inheritsLoose(DodecahedronGeometry, _PolyhedronGeometry);
  23524. function DodecahedronGeometry(radius, detail) {
  23525. var _this;
  23526. if (radius === void 0) {
  23527. radius = 1;
  23528. }
  23529. if (detail === void 0) {
  23530. detail = 0;
  23531. }
  23532. var t = (1 + Math.sqrt(5)) / 2;
  23533. var r = 1 / t;
  23534. var vertices = [// (±1, ±1, ±1)
  23535. -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/φ, ±φ)
  23536. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  23537. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  23538. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  23539. 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];
  23540. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  23541. _this.type = 'DodecahedronGeometry';
  23542. _this.parameters = {
  23543. radius: radius,
  23544. detail: detail
  23545. };
  23546. return _this;
  23547. }
  23548. return DodecahedronGeometry;
  23549. }(PolyhedronGeometry);
  23550. var _v0$2 = new Vector3();
  23551. var _v1$5 = new Vector3();
  23552. var _normal$1 = new Vector3();
  23553. var _triangle = new Triangle();
  23554. var EdgesGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23555. _inheritsLoose(EdgesGeometry, _BufferGeometry);
  23556. function EdgesGeometry(geometry, thresholdAngle) {
  23557. var _this;
  23558. _this = _BufferGeometry.call(this) || this;
  23559. _this.type = 'EdgesGeometry';
  23560. _this.parameters = {
  23561. thresholdAngle: thresholdAngle
  23562. };
  23563. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  23564. if (geometry.isGeometry === true) {
  23565. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23566. return _assertThisInitialized(_this);
  23567. }
  23568. var precisionPoints = 4;
  23569. var precision = Math.pow(10, precisionPoints);
  23570. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  23571. var indexAttr = geometry.getIndex();
  23572. var positionAttr = geometry.getAttribute('position');
  23573. var indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23574. var indexArr = [0, 0, 0];
  23575. var vertKeys = ['a', 'b', 'c'];
  23576. var hashes = new Array(3);
  23577. var edgeData = {};
  23578. var vertices = [];
  23579. for (var i = 0; i < indexCount; i += 3) {
  23580. if (indexAttr) {
  23581. indexArr[0] = indexAttr.getX(i);
  23582. indexArr[1] = indexAttr.getX(i + 1);
  23583. indexArr[2] = indexAttr.getX(i + 2);
  23584. } else {
  23585. indexArr[0] = i;
  23586. indexArr[1] = i + 1;
  23587. indexArr[2] = i + 2;
  23588. }
  23589. var a = _triangle.a,
  23590. b = _triangle.b,
  23591. c = _triangle.c;
  23592. a.fromBufferAttribute(positionAttr, indexArr[0]);
  23593. b.fromBufferAttribute(positionAttr, indexArr[1]);
  23594. c.fromBufferAttribute(positionAttr, indexArr[2]);
  23595. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  23596. hashes[0] = Math.round(a.x * precision) + "," + Math.round(a.y * precision) + "," + Math.round(a.z * precision);
  23597. hashes[1] = Math.round(b.x * precision) + "," + Math.round(b.y * precision) + "," + Math.round(b.z * precision);
  23598. hashes[2] = Math.round(c.x * precision) + "," + Math.round(c.y * precision) + "," + Math.round(c.z * precision); // skip degenerate triangles
  23599. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  23600. continue;
  23601. } // iterate over every edge
  23602. for (var j = 0; j < 3; j++) {
  23603. // get the first and next vertex making up the edge
  23604. var jNext = (j + 1) % 3;
  23605. var vecHash0 = hashes[j];
  23606. var vecHash1 = hashes[jNext];
  23607. var v0 = _triangle[vertKeys[j]];
  23608. var v1 = _triangle[vertKeys[jNext]];
  23609. var hash = vecHash0 + "_" + vecHash1;
  23610. var reverseHash = vecHash1 + "_" + vecHash0;
  23611. if (reverseHash in edgeData && edgeData[reverseHash]) {
  23612. // if we found a sibling edge add it into the vertex array if
  23613. // it meets the angle threshold and delete the edge from the map.
  23614. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  23615. vertices.push(v0.x, v0.y, v0.z);
  23616. vertices.push(v1.x, v1.y, v1.z);
  23617. }
  23618. edgeData[reverseHash] = null;
  23619. } else if (!(hash in edgeData)) {
  23620. // if we've already got an edge here then skip adding a new one
  23621. edgeData[hash] = {
  23622. index0: indexArr[j],
  23623. index1: indexArr[jNext],
  23624. normal: _normal$1.clone()
  23625. };
  23626. }
  23627. }
  23628. } // iterate over all remaining, unmatched edges and add them to the vertex array
  23629. for (var key in edgeData) {
  23630. if (edgeData[key]) {
  23631. var _edgeData$key = edgeData[key],
  23632. index0 = _edgeData$key.index0,
  23633. index1 = _edgeData$key.index1;
  23634. _v0$2.fromBufferAttribute(positionAttr, index0);
  23635. _v1$5.fromBufferAttribute(positionAttr, index1);
  23636. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  23637. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  23638. }
  23639. }
  23640. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23641. return _this;
  23642. }
  23643. return EdgesGeometry;
  23644. }(BufferGeometry);
  23645. /**
  23646. * Port from https://github.com/mapbox/earcut (v2.2.2)
  23647. */
  23648. var Earcut = {
  23649. triangulate: function triangulate(data, holeIndices, dim) {
  23650. dim = dim || 2;
  23651. var hasHoles = holeIndices && holeIndices.length;
  23652. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  23653. var outerNode = linkedList(data, 0, outerLen, dim, true);
  23654. var triangles = [];
  23655. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  23656. var minX, minY, maxX, maxY, x, y, invSize;
  23657. 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
  23658. if (data.length > 80 * dim) {
  23659. minX = maxX = data[0];
  23660. minY = maxY = data[1];
  23661. for (var i = dim; i < outerLen; i += dim) {
  23662. x = data[i];
  23663. y = data[i + 1];
  23664. if (x < minX) minX = x;
  23665. if (y < minY) minY = y;
  23666. if (x > maxX) maxX = x;
  23667. if (y > maxY) maxY = y;
  23668. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  23669. invSize = Math.max(maxX - minX, maxY - minY);
  23670. invSize = invSize !== 0 ? 1 / invSize : 0;
  23671. }
  23672. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  23673. return triangles;
  23674. }
  23675. }; // create a circular doubly linked list from polygon points in the specified winding order
  23676. function linkedList(data, start, end, dim, clockwise) {
  23677. var i, last;
  23678. if (clockwise === signedArea(data, start, end, dim) > 0) {
  23679. for (i = start; i < end; i += dim) {
  23680. last = insertNode(i, data[i], data[i + 1], last);
  23681. }
  23682. } else {
  23683. for (i = end - dim; i >= start; i -= dim) {
  23684. last = insertNode(i, data[i], data[i + 1], last);
  23685. }
  23686. }
  23687. if (last && equals(last, last.next)) {
  23688. removeNode(last);
  23689. last = last.next;
  23690. }
  23691. return last;
  23692. } // eliminate colinear or duplicate points
  23693. function filterPoints(start, end) {
  23694. if (!start) return start;
  23695. if (!end) end = start;
  23696. var p = start,
  23697. again;
  23698. do {
  23699. again = false;
  23700. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  23701. removeNode(p);
  23702. p = end = p.prev;
  23703. if (p === p.next) break;
  23704. again = true;
  23705. } else {
  23706. p = p.next;
  23707. }
  23708. } while (again || p !== end);
  23709. return end;
  23710. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  23711. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  23712. if (!ear) return; // interlink polygon nodes in z-order
  23713. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  23714. var stop = ear,
  23715. prev,
  23716. next; // iterate through ears, slicing them one by one
  23717. while (ear.prev !== ear.next) {
  23718. prev = ear.prev;
  23719. next = ear.next;
  23720. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  23721. // cut off the triangle
  23722. triangles.push(prev.i / dim);
  23723. triangles.push(ear.i / dim);
  23724. triangles.push(next.i / dim);
  23725. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  23726. ear = next.next;
  23727. stop = next.next;
  23728. continue;
  23729. }
  23730. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  23731. if (ear === stop) {
  23732. // try filtering points and slicing again
  23733. if (!pass) {
  23734. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  23735. } else if (pass === 1) {
  23736. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  23737. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  23738. } else if (pass === 2) {
  23739. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  23740. }
  23741. break;
  23742. }
  23743. }
  23744. } // check whether a polygon node forms a valid ear with adjacent nodes
  23745. function isEar(ear) {
  23746. var a = ear.prev,
  23747. b = ear,
  23748. c = ear.next;
  23749. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23750. // now make sure we don't have other points inside the potential ear
  23751. var p = ear.next.next;
  23752. while (p !== ear.prev) {
  23753. 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;
  23754. p = p.next;
  23755. }
  23756. return true;
  23757. }
  23758. function isEarHashed(ear, minX, minY, invSize) {
  23759. var a = ear.prev,
  23760. b = ear,
  23761. c = ear.next;
  23762. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23763. // triangle bbox; min & max are calculated like this for speed
  23764. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  23765. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  23766. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  23767. 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;
  23768. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  23769. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  23770. var p = ear.prevZ,
  23771. n = ear.nextZ; // look for points inside the triangle in both directions
  23772. while (p && p.z >= minZ && n && n.z <= maxZ) {
  23773. 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;
  23774. p = p.prevZ;
  23775. 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;
  23776. n = n.nextZ;
  23777. } // look for remaining points in decreasing z-order
  23778. while (p && p.z >= minZ) {
  23779. 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;
  23780. p = p.prevZ;
  23781. } // look for remaining points in increasing z-order
  23782. while (n && n.z <= maxZ) {
  23783. 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;
  23784. n = n.nextZ;
  23785. }
  23786. return true;
  23787. } // go through all polygon nodes and cure small local self-intersections
  23788. function cureLocalIntersections(start, triangles, dim) {
  23789. var p = start;
  23790. do {
  23791. var a = p.prev,
  23792. b = p.next.next;
  23793. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  23794. triangles.push(a.i / dim);
  23795. triangles.push(p.i / dim);
  23796. triangles.push(b.i / dim); // remove two nodes involved
  23797. removeNode(p);
  23798. removeNode(p.next);
  23799. p = start = b;
  23800. }
  23801. p = p.next;
  23802. } while (p !== start);
  23803. return filterPoints(p);
  23804. } // try splitting polygon into two and triangulate them independently
  23805. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  23806. // look for a valid diagonal that divides the polygon into two
  23807. var a = start;
  23808. do {
  23809. var b = a.next.next;
  23810. while (b !== a.prev) {
  23811. if (a.i !== b.i && isValidDiagonal(a, b)) {
  23812. // split the polygon in two by the diagonal
  23813. var c = splitPolygon(a, b); // filter colinear points around the cuts
  23814. a = filterPoints(a, a.next);
  23815. c = filterPoints(c, c.next); // run earcut on each half
  23816. earcutLinked(a, triangles, dim, minX, minY, invSize);
  23817. earcutLinked(c, triangles, dim, minX, minY, invSize);
  23818. return;
  23819. }
  23820. b = b.next;
  23821. }
  23822. a = a.next;
  23823. } while (a !== start);
  23824. } // link every hole into the outer loop, producing a single-ring polygon without holes
  23825. function eliminateHoles(data, holeIndices, outerNode, dim) {
  23826. var queue = [];
  23827. var i, len, start, end, list;
  23828. for (i = 0, len = holeIndices.length; i < len; i++) {
  23829. start = holeIndices[i] * dim;
  23830. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  23831. list = linkedList(data, start, end, dim, false);
  23832. if (list === list.next) list.steiner = true;
  23833. queue.push(getLeftmost(list));
  23834. }
  23835. queue.sort(compareX); // process holes from left to right
  23836. for (i = 0; i < queue.length; i++) {
  23837. eliminateHole(queue[i], outerNode);
  23838. outerNode = filterPoints(outerNode, outerNode.next);
  23839. }
  23840. return outerNode;
  23841. }
  23842. function compareX(a, b) {
  23843. return a.x - b.x;
  23844. } // find a bridge between vertices that connects hole with an outer ring and and link it
  23845. function eliminateHole(hole, outerNode) {
  23846. outerNode = findHoleBridge(hole, outerNode);
  23847. if (outerNode) {
  23848. var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  23849. filterPoints(outerNode, outerNode.next);
  23850. filterPoints(b, b.next);
  23851. }
  23852. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23853. function findHoleBridge(hole, outerNode) {
  23854. var p = outerNode;
  23855. var hx = hole.x;
  23856. var hy = hole.y;
  23857. var qx = -Infinity,
  23858. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  23859. // segment's endpoint with lesser x will be potential connection point
  23860. do {
  23861. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  23862. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  23863. if (x <= hx && x > qx) {
  23864. qx = x;
  23865. if (x === hx) {
  23866. if (hy === p.y) return p;
  23867. if (hy === p.next.y) return p.next;
  23868. }
  23869. m = p.x < p.next.x ? p : p.next;
  23870. }
  23871. }
  23872. p = p.next;
  23873. } while (p !== outerNode);
  23874. if (!m) return null;
  23875. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  23876. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23877. // if there are no points found, we have a valid connection;
  23878. // otherwise choose the point of the minimum angle with the ray as connection point
  23879. var stop = m,
  23880. mx = m.x,
  23881. my = m.y;
  23882. var tanMin = Infinity,
  23883. tan;
  23884. p = m;
  23885. do {
  23886. 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)) {
  23887. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  23888. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  23889. m = p;
  23890. tanMin = tan;
  23891. }
  23892. }
  23893. p = p.next;
  23894. } while (p !== stop);
  23895. return m;
  23896. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  23897. function sectorContainsSector(m, p) {
  23898. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  23899. } // interlink polygon nodes in z-order
  23900. function indexCurve(start, minX, minY, invSize) {
  23901. var p = start;
  23902. do {
  23903. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  23904. p.prevZ = p.prev;
  23905. p.nextZ = p.next;
  23906. p = p.next;
  23907. } while (p !== start);
  23908. p.prevZ.nextZ = null;
  23909. p.prevZ = null;
  23910. sortLinked(p);
  23911. } // Simon Tatham's linked list merge sort algorithm
  23912. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23913. function sortLinked(list) {
  23914. var i,
  23915. p,
  23916. q,
  23917. e,
  23918. tail,
  23919. numMerges,
  23920. pSize,
  23921. qSize,
  23922. inSize = 1;
  23923. do {
  23924. p = list;
  23925. list = null;
  23926. tail = null;
  23927. numMerges = 0;
  23928. while (p) {
  23929. numMerges++;
  23930. q = p;
  23931. pSize = 0;
  23932. for (i = 0; i < inSize; i++) {
  23933. pSize++;
  23934. q = q.nextZ;
  23935. if (!q) break;
  23936. }
  23937. qSize = inSize;
  23938. while (pSize > 0 || qSize > 0 && q) {
  23939. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  23940. e = p;
  23941. p = p.nextZ;
  23942. pSize--;
  23943. } else {
  23944. e = q;
  23945. q = q.nextZ;
  23946. qSize--;
  23947. }
  23948. if (tail) tail.nextZ = e;else list = e;
  23949. e.prevZ = tail;
  23950. tail = e;
  23951. }
  23952. p = q;
  23953. }
  23954. tail.nextZ = null;
  23955. inSize *= 2;
  23956. } while (numMerges > 1);
  23957. return list;
  23958. } // z-order of a point given coords and inverse of the longer side of data bbox
  23959. function zOrder(x, y, minX, minY, invSize) {
  23960. // coords are transformed into non-negative 15-bit integer range
  23961. x = 32767 * (x - minX) * invSize;
  23962. y = 32767 * (y - minY) * invSize;
  23963. x = (x | x << 8) & 0x00FF00FF;
  23964. x = (x | x << 4) & 0x0F0F0F0F;
  23965. x = (x | x << 2) & 0x33333333;
  23966. x = (x | x << 1) & 0x55555555;
  23967. y = (y | y << 8) & 0x00FF00FF;
  23968. y = (y | y << 4) & 0x0F0F0F0F;
  23969. y = (y | y << 2) & 0x33333333;
  23970. y = (y | y << 1) & 0x55555555;
  23971. return x | y << 1;
  23972. } // find the leftmost node of a polygon ring
  23973. function getLeftmost(start) {
  23974. var p = start,
  23975. leftmost = start;
  23976. do {
  23977. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  23978. p = p.next;
  23979. } while (p !== start);
  23980. return leftmost;
  23981. } // check if a point lies within a convex triangle
  23982. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  23983. 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;
  23984. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23985. function isValidDiagonal(a, b) {
  23986. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  23987. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  23988. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  23989. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  23990. } // signed area of a triangle
  23991. function area(p, q, r) {
  23992. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  23993. } // check if two points are equal
  23994. function equals(p1, p2) {
  23995. return p1.x === p2.x && p1.y === p2.y;
  23996. } // check if two segments intersect
  23997. function intersects(p1, q1, p2, q2) {
  23998. var o1 = sign(area(p1, q1, p2));
  23999. var o2 = sign(area(p1, q1, q2));
  24000. var o3 = sign(area(p2, q2, p1));
  24001. var o4 = sign(area(p2, q2, q1));
  24002. if (o1 !== o2 && o3 !== o4) return true; // general case
  24003. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24004. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24005. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24006. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24007. return false;
  24008. } // for collinear points p, q, r, check if point q lies on segment pr
  24009. function onSegment(p, q, r) {
  24010. 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);
  24011. }
  24012. function sign(num) {
  24013. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24014. } // check if a polygon diagonal intersects any polygon segments
  24015. function intersectsPolygon(a, b) {
  24016. var p = a;
  24017. do {
  24018. 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;
  24019. p = p.next;
  24020. } while (p !== a);
  24021. return false;
  24022. } // check if a polygon diagonal is locally inside the polygon
  24023. function locallyInside(a, b) {
  24024. 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;
  24025. } // check if the middle point of a polygon diagonal is inside the polygon
  24026. function middleInside(a, b) {
  24027. var p = a,
  24028. inside = false;
  24029. var px = (a.x + b.x) / 2,
  24030. py = (a.y + b.y) / 2;
  24031. do {
  24032. 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;
  24033. p = p.next;
  24034. } while (p !== a);
  24035. return inside;
  24036. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24037. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24038. function splitPolygon(a, b) {
  24039. var a2 = new Node(a.i, a.x, a.y),
  24040. b2 = new Node(b.i, b.x, b.y),
  24041. an = a.next,
  24042. bp = b.prev;
  24043. a.next = b;
  24044. b.prev = a;
  24045. a2.next = an;
  24046. an.prev = a2;
  24047. b2.next = a2;
  24048. a2.prev = b2;
  24049. bp.next = b2;
  24050. b2.prev = bp;
  24051. return b2;
  24052. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  24053. function insertNode(i, x, y, last) {
  24054. var p = new Node(i, x, y);
  24055. if (!last) {
  24056. p.prev = p;
  24057. p.next = p;
  24058. } else {
  24059. p.next = last.next;
  24060. p.prev = last;
  24061. last.next.prev = p;
  24062. last.next = p;
  24063. }
  24064. return p;
  24065. }
  24066. function removeNode(p) {
  24067. p.next.prev = p.prev;
  24068. p.prev.next = p.next;
  24069. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24070. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24071. }
  24072. function Node(i, x, y) {
  24073. // vertex index in coordinates array
  24074. this.i = i; // vertex coordinates
  24075. this.x = x;
  24076. this.y = y; // previous and next vertex nodes in a polygon ring
  24077. this.prev = null;
  24078. this.next = null; // z-order curve value
  24079. this.z = null; // previous and next nodes in z-order
  24080. this.prevZ = null;
  24081. this.nextZ = null; // indicates whether this is a steiner point
  24082. this.steiner = false;
  24083. }
  24084. function signedArea(data, start, end, dim) {
  24085. var sum = 0;
  24086. for (var i = start, j = end - dim; i < end; i += dim) {
  24087. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24088. j = i;
  24089. }
  24090. return sum;
  24091. }
  24092. var ShapeUtils = {
  24093. // calculate area of the contour polygon
  24094. area: function area(contour) {
  24095. var n = contour.length;
  24096. var a = 0.0;
  24097. for (var p = n - 1, q = 0; q < n; p = q++) {
  24098. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  24099. }
  24100. return a * 0.5;
  24101. },
  24102. isClockWise: function isClockWise(pts) {
  24103. return ShapeUtils.area(pts) < 0;
  24104. },
  24105. triangulateShape: function triangulateShape(contour, holes) {
  24106. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  24107. var holeIndices = []; // array of hole indices
  24108. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  24109. removeDupEndPts(contour);
  24110. addContour(vertices, contour); //
  24111. var holeIndex = contour.length;
  24112. holes.forEach(removeDupEndPts);
  24113. for (var i = 0; i < holes.length; i++) {
  24114. holeIndices.push(holeIndex);
  24115. holeIndex += holes[i].length;
  24116. addContour(vertices, holes[i]);
  24117. } //
  24118. var triangles = Earcut.triangulate(vertices, holeIndices); //
  24119. for (var _i = 0; _i < triangles.length; _i += 3) {
  24120. faces.push(triangles.slice(_i, _i + 3));
  24121. }
  24122. return faces;
  24123. }
  24124. };
  24125. function removeDupEndPts(points) {
  24126. var l = points.length;
  24127. if (l > 2 && points[l - 1].equals(points[0])) {
  24128. points.pop();
  24129. }
  24130. }
  24131. function addContour(vertices, contour) {
  24132. for (var i = 0; i < contour.length; i++) {
  24133. vertices.push(contour[i].x);
  24134. vertices.push(contour[i].y);
  24135. }
  24136. }
  24137. var ExtrudeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24138. _inheritsLoose(ExtrudeGeometry, _BufferGeometry);
  24139. function ExtrudeGeometry(shapes, options) {
  24140. var _this;
  24141. _this = _BufferGeometry.call(this) || this;
  24142. _this.type = 'ExtrudeGeometry';
  24143. _this.parameters = {
  24144. shapes: shapes,
  24145. options: options
  24146. };
  24147. shapes = Array.isArray(shapes) ? shapes : [shapes];
  24148. var scope = _assertThisInitialized(_this);
  24149. var verticesArray = [];
  24150. var uvArray = [];
  24151. for (var i = 0, l = shapes.length; i < l; i++) {
  24152. var shape = shapes[i];
  24153. addShape(shape);
  24154. } // build geometry
  24155. _this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  24156. _this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  24157. _this.computeVertexNormals(); // functions
  24158. function addShape(shape) {
  24159. var placeholder = []; // options
  24160. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  24161. var steps = options.steps !== undefined ? options.steps : 1;
  24162. var depth = options.depth !== undefined ? options.depth : 100;
  24163. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  24164. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  24165. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  24166. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  24167. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  24168. var extrudePath = options.extrudePath;
  24169. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  24170. if (options.amount !== undefined) {
  24171. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  24172. depth = options.amount;
  24173. } //
  24174. var extrudePts,
  24175. extrudeByPath = false;
  24176. var splineTube, binormal, normal, position2;
  24177. if (extrudePath) {
  24178. extrudePts = extrudePath.getSpacedPoints(steps);
  24179. extrudeByPath = true;
  24180. bevelEnabled = false; // bevels not supported for path extrusion
  24181. // SETUP TNB variables
  24182. // TODO1 - have a .isClosed in spline?
  24183. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  24184. binormal = new Vector3();
  24185. normal = new Vector3();
  24186. position2 = new Vector3();
  24187. } // Safeguards if bevels are not enabled
  24188. if (!bevelEnabled) {
  24189. bevelSegments = 0;
  24190. bevelThickness = 0;
  24191. bevelSize = 0;
  24192. bevelOffset = 0;
  24193. } // Variables initialization
  24194. var shapePoints = shape.extractPoints(curveSegments);
  24195. var vertices = shapePoints.shape;
  24196. var holes = shapePoints.holes;
  24197. var reverse = !ShapeUtils.isClockWise(vertices);
  24198. if (reverse) {
  24199. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  24200. for (var h = 0, hl = holes.length; h < hl; h++) {
  24201. var ahole = holes[h];
  24202. if (ShapeUtils.isClockWise(ahole)) {
  24203. holes[h] = ahole.reverse();
  24204. }
  24205. }
  24206. }
  24207. var faces = ShapeUtils.triangulateShape(vertices, holes);
  24208. /* Vertices */
  24209. var contour = vertices; // vertices has all points but contour has only points of circumference
  24210. for (var _h = 0, _hl = holes.length; _h < _hl; _h++) {
  24211. var _ahole = holes[_h];
  24212. vertices = vertices.concat(_ahole);
  24213. }
  24214. function scalePt2(pt, vec, size) {
  24215. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  24216. return vec.clone().multiplyScalar(size).add(pt);
  24217. }
  24218. var vlen = vertices.length,
  24219. flen = faces.length; // Find directions for point movement
  24220. function getBevelVec(inPt, inPrev, inNext) {
  24221. // computes for inPt the corresponding point inPt' on a new contour
  24222. // shifted by 1 unit (length of normalized vector) to the left
  24223. // if we walk along contour clockwise, this new contour is outside the old one
  24224. //
  24225. // inPt' is the intersection of the two lines parallel to the two
  24226. // adjacent edges of inPt at a distance of 1 unit on the left side.
  24227. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  24228. // good reading for geometry algorithms (here: line-line intersection)
  24229. // http://geomalgorithms.com/a05-_intersect-1.html
  24230. var v_prev_x = inPt.x - inPrev.x,
  24231. v_prev_y = inPt.y - inPrev.y;
  24232. var v_next_x = inNext.x - inPt.x,
  24233. v_next_y = inNext.y - inPt.y;
  24234. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  24235. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  24236. if (Math.abs(collinear0) > Number.EPSILON) {
  24237. // not collinear
  24238. // length of vectors for normalizing
  24239. var v_prev_len = Math.sqrt(v_prev_lensq);
  24240. 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
  24241. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  24242. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  24243. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  24244. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  24245. 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
  24246. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  24247. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  24248. // but prevent crazy spikes
  24249. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  24250. if (v_trans_lensq <= 2) {
  24251. return new Vector2(v_trans_x, v_trans_y);
  24252. } else {
  24253. shrink_by = Math.sqrt(v_trans_lensq / 2);
  24254. }
  24255. } else {
  24256. // handle special case of collinear edges
  24257. var direction_eq = false; // assumes: opposite
  24258. if (v_prev_x > Number.EPSILON) {
  24259. if (v_next_x > Number.EPSILON) {
  24260. direction_eq = true;
  24261. }
  24262. } else {
  24263. if (v_prev_x < -Number.EPSILON) {
  24264. if (v_next_x < -Number.EPSILON) {
  24265. direction_eq = true;
  24266. }
  24267. } else {
  24268. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  24269. direction_eq = true;
  24270. }
  24271. }
  24272. }
  24273. if (direction_eq) {
  24274. // console.log("Warning: lines are a straight sequence");
  24275. v_trans_x = -v_prev_y;
  24276. v_trans_y = v_prev_x;
  24277. shrink_by = Math.sqrt(v_prev_lensq);
  24278. } else {
  24279. // console.log("Warning: lines are a straight spike");
  24280. v_trans_x = v_prev_x;
  24281. v_trans_y = v_prev_y;
  24282. shrink_by = Math.sqrt(v_prev_lensq / 2);
  24283. }
  24284. }
  24285. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  24286. }
  24287. var contourMovements = [];
  24288. for (var _i = 0, il = contour.length, j = il - 1, k = _i + 1; _i < il; _i++, j++, k++) {
  24289. if (j === il) j = 0;
  24290. if (k === il) k = 0; // (j)---(i)---(k)
  24291. // console.log('i,j,k', i, j , k)
  24292. contourMovements[_i] = getBevelVec(contour[_i], contour[j], contour[k]);
  24293. }
  24294. var holesMovements = [];
  24295. var oneHoleMovements,
  24296. verticesMovements = contourMovements.concat();
  24297. for (var _h2 = 0, _hl2 = holes.length; _h2 < _hl2; _h2++) {
  24298. var _ahole2 = holes[_h2];
  24299. oneHoleMovements = [];
  24300. for (var _i2 = 0, _il = _ahole2.length, _j = _il - 1, _k = _i2 + 1; _i2 < _il; _i2++, _j++, _k++) {
  24301. if (_j === _il) _j = 0;
  24302. if (_k === _il) _k = 0; // (j)---(i)---(k)
  24303. oneHoleMovements[_i2] = getBevelVec(_ahole2[_i2], _ahole2[_j], _ahole2[_k]);
  24304. }
  24305. holesMovements.push(oneHoleMovements);
  24306. verticesMovements = verticesMovements.concat(oneHoleMovements);
  24307. } // Loop bevelSegments, 1 for the front, 1 for the back
  24308. for (var b = 0; b < bevelSegments; b++) {
  24309. //for ( b = bevelSegments; b > 0; b -- ) {
  24310. var t = b / bevelSegments;
  24311. var z = bevelThickness * Math.cos(t * Math.PI / 2);
  24312. var _bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  24313. for (var _i3 = 0, _il2 = contour.length; _i3 < _il2; _i3++) {
  24314. var vert = scalePt2(contour[_i3], contourMovements[_i3], _bs);
  24315. v(vert.x, vert.y, -z);
  24316. } // expand holes
  24317. for (var _h3 = 0, _hl3 = holes.length; _h3 < _hl3; _h3++) {
  24318. var _ahole3 = holes[_h3];
  24319. oneHoleMovements = holesMovements[_h3];
  24320. for (var _i4 = 0, _il3 = _ahole3.length; _i4 < _il3; _i4++) {
  24321. var _vert = scalePt2(_ahole3[_i4], oneHoleMovements[_i4], _bs);
  24322. v(_vert.x, _vert.y, -z);
  24323. }
  24324. }
  24325. }
  24326. var bs = bevelSize + bevelOffset; // Back facing vertices
  24327. for (var _i5 = 0; _i5 < vlen; _i5++) {
  24328. var _vert2 = bevelEnabled ? scalePt2(vertices[_i5], verticesMovements[_i5], bs) : vertices[_i5];
  24329. if (!extrudeByPath) {
  24330. v(_vert2.x, _vert2.y, 0);
  24331. } else {
  24332. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  24333. normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);
  24334. binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);
  24335. position2.copy(extrudePts[0]).add(normal).add(binormal);
  24336. v(position2.x, position2.y, position2.z);
  24337. }
  24338. } // Add stepped vertices...
  24339. // Including front facing vertices
  24340. for (var s = 1; s <= steps; s++) {
  24341. for (var _i6 = 0; _i6 < vlen; _i6++) {
  24342. var _vert3 = bevelEnabled ? scalePt2(vertices[_i6], verticesMovements[_i6], bs) : vertices[_i6];
  24343. if (!extrudeByPath) {
  24344. v(_vert3.x, _vert3.y, depth / steps * s);
  24345. } else {
  24346. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  24347. normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);
  24348. binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);
  24349. position2.copy(extrudePts[s]).add(normal).add(binormal);
  24350. v(position2.x, position2.y, position2.z);
  24351. }
  24352. }
  24353. } // Add bevel segments planes
  24354. //for ( b = 1; b <= bevelSegments; b ++ ) {
  24355. for (var _b = bevelSegments - 1; _b >= 0; _b--) {
  24356. var _t = _b / bevelSegments;
  24357. var _z = bevelThickness * Math.cos(_t * Math.PI / 2);
  24358. var _bs2 = bevelSize * Math.sin(_t * Math.PI / 2) + bevelOffset; // contract shape
  24359. for (var _i7 = 0, _il4 = contour.length; _i7 < _il4; _i7++) {
  24360. var _vert4 = scalePt2(contour[_i7], contourMovements[_i7], _bs2);
  24361. v(_vert4.x, _vert4.y, depth + _z);
  24362. } // expand holes
  24363. for (var _h4 = 0, _hl4 = holes.length; _h4 < _hl4; _h4++) {
  24364. var _ahole4 = holes[_h4];
  24365. oneHoleMovements = holesMovements[_h4];
  24366. for (var _i8 = 0, _il5 = _ahole4.length; _i8 < _il5; _i8++) {
  24367. var _vert5 = scalePt2(_ahole4[_i8], oneHoleMovements[_i8], _bs2);
  24368. if (!extrudeByPath) {
  24369. v(_vert5.x, _vert5.y, depth + _z);
  24370. } else {
  24371. v(_vert5.x, _vert5.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + _z);
  24372. }
  24373. }
  24374. }
  24375. }
  24376. /* Faces */
  24377. // Top and bottom faces
  24378. buildLidFaces(); // Sides faces
  24379. buildSideFaces(); ///// Internal functions
  24380. function buildLidFaces() {
  24381. var start = verticesArray.length / 3;
  24382. if (bevelEnabled) {
  24383. var layer = 0; // steps + 1
  24384. var offset = vlen * layer; // Bottom faces
  24385. for (var _i9 = 0; _i9 < flen; _i9++) {
  24386. var face = faces[_i9];
  24387. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  24388. }
  24389. layer = steps + bevelSegments * 2;
  24390. offset = vlen * layer; // Top faces
  24391. for (var _i10 = 0; _i10 < flen; _i10++) {
  24392. var _face = faces[_i10];
  24393. f3(_face[0] + offset, _face[1] + offset, _face[2] + offset);
  24394. }
  24395. } else {
  24396. // Bottom faces
  24397. for (var _i11 = 0; _i11 < flen; _i11++) {
  24398. var _face2 = faces[_i11];
  24399. f3(_face2[2], _face2[1], _face2[0]);
  24400. } // Top faces
  24401. for (var _i12 = 0; _i12 < flen; _i12++) {
  24402. var _face3 = faces[_i12];
  24403. f3(_face3[0] + vlen * steps, _face3[1] + vlen * steps, _face3[2] + vlen * steps);
  24404. }
  24405. }
  24406. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  24407. } // Create faces for the z-sides of the shape
  24408. function buildSideFaces() {
  24409. var start = verticesArray.length / 3;
  24410. var layeroffset = 0;
  24411. sidewalls(contour, layeroffset);
  24412. layeroffset += contour.length;
  24413. for (var _h5 = 0, _hl5 = holes.length; _h5 < _hl5; _h5++) {
  24414. var _ahole5 = holes[_h5];
  24415. sidewalls(_ahole5, layeroffset); //, true
  24416. layeroffset += _ahole5.length;
  24417. }
  24418. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  24419. }
  24420. function sidewalls(contour, layeroffset) {
  24421. var i = contour.length;
  24422. while (--i >= 0) {
  24423. var _j2 = i;
  24424. var _k2 = i - 1;
  24425. if (_k2 < 0) _k2 = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  24426. for (var _s = 0, sl = steps + bevelSegments * 2; _s < sl; _s++) {
  24427. var slen1 = vlen * _s;
  24428. var slen2 = vlen * (_s + 1);
  24429. var a = layeroffset + _j2 + slen1,
  24430. _b2 = layeroffset + _k2 + slen1,
  24431. c = layeroffset + _k2 + slen2,
  24432. d = layeroffset + _j2 + slen2;
  24433. f4(a, _b2, c, d);
  24434. }
  24435. }
  24436. }
  24437. function v(x, y, z) {
  24438. placeholder.push(x);
  24439. placeholder.push(y);
  24440. placeholder.push(z);
  24441. }
  24442. function f3(a, b, c) {
  24443. addVertex(a);
  24444. addVertex(b);
  24445. addVertex(c);
  24446. var nextIndex = verticesArray.length / 3;
  24447. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24448. addUV(uvs[0]);
  24449. addUV(uvs[1]);
  24450. addUV(uvs[2]);
  24451. }
  24452. function f4(a, b, c, d) {
  24453. addVertex(a);
  24454. addVertex(b);
  24455. addVertex(d);
  24456. addVertex(b);
  24457. addVertex(c);
  24458. addVertex(d);
  24459. var nextIndex = verticesArray.length / 3;
  24460. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24461. addUV(uvs[0]);
  24462. addUV(uvs[1]);
  24463. addUV(uvs[3]);
  24464. addUV(uvs[1]);
  24465. addUV(uvs[2]);
  24466. addUV(uvs[3]);
  24467. }
  24468. function addVertex(index) {
  24469. verticesArray.push(placeholder[index * 3 + 0]);
  24470. verticesArray.push(placeholder[index * 3 + 1]);
  24471. verticesArray.push(placeholder[index * 3 + 2]);
  24472. }
  24473. function addUV(vector2) {
  24474. uvArray.push(vector2.x);
  24475. uvArray.push(vector2.y);
  24476. }
  24477. }
  24478. return _this;
  24479. }
  24480. var _proto = ExtrudeGeometry.prototype;
  24481. _proto.toJSON = function toJSON() {
  24482. var data = BufferGeometry.prototype.toJSON.call(this);
  24483. var shapes = this.parameters.shapes;
  24484. var options = this.parameters.options;
  24485. return _toJSON(shapes, options, data);
  24486. };
  24487. return ExtrudeGeometry;
  24488. }(BufferGeometry);
  24489. var WorldUVGenerator = {
  24490. generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {
  24491. var a_x = vertices[indexA * 3];
  24492. var a_y = vertices[indexA * 3 + 1];
  24493. var b_x = vertices[indexB * 3];
  24494. var b_y = vertices[indexB * 3 + 1];
  24495. var c_x = vertices[indexC * 3];
  24496. var c_y = vertices[indexC * 3 + 1];
  24497. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  24498. },
  24499. generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {
  24500. var a_x = vertices[indexA * 3];
  24501. var a_y = vertices[indexA * 3 + 1];
  24502. var a_z = vertices[indexA * 3 + 2];
  24503. var b_x = vertices[indexB * 3];
  24504. var b_y = vertices[indexB * 3 + 1];
  24505. var b_z = vertices[indexB * 3 + 2];
  24506. var c_x = vertices[indexC * 3];
  24507. var c_y = vertices[indexC * 3 + 1];
  24508. var c_z = vertices[indexC * 3 + 2];
  24509. var d_x = vertices[indexD * 3];
  24510. var d_y = vertices[indexD * 3 + 1];
  24511. var d_z = vertices[indexD * 3 + 2];
  24512. if (Math.abs(a_y - b_y) < 0.01) {
  24513. 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)];
  24514. } else {
  24515. 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)];
  24516. }
  24517. }
  24518. };
  24519. function _toJSON(shapes, options, data) {
  24520. data.shapes = [];
  24521. if (Array.isArray(shapes)) {
  24522. for (var i = 0, l = shapes.length; i < l; i++) {
  24523. var shape = shapes[i];
  24524. data.shapes.push(shape.uuid);
  24525. }
  24526. } else {
  24527. data.shapes.push(shapes.uuid);
  24528. }
  24529. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  24530. return data;
  24531. }
  24532. var IcosahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24533. _inheritsLoose(IcosahedronGeometry, _PolyhedronGeometry);
  24534. function IcosahedronGeometry(radius, detail) {
  24535. var _this;
  24536. if (radius === void 0) {
  24537. radius = 1;
  24538. }
  24539. if (detail === void 0) {
  24540. detail = 0;
  24541. }
  24542. var t = (1 + Math.sqrt(5)) / 2;
  24543. 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];
  24544. 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];
  24545. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24546. _this.type = 'IcosahedronGeometry';
  24547. _this.parameters = {
  24548. radius: radius,
  24549. detail: detail
  24550. };
  24551. return _this;
  24552. }
  24553. return IcosahedronGeometry;
  24554. }(PolyhedronGeometry);
  24555. var LatheGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24556. _inheritsLoose(LatheGeometry, _BufferGeometry);
  24557. function LatheGeometry(points, segments, phiStart, phiLength) {
  24558. var _this;
  24559. if (segments === void 0) {
  24560. segments = 12;
  24561. }
  24562. if (phiStart === void 0) {
  24563. phiStart = 0;
  24564. }
  24565. if (phiLength === void 0) {
  24566. phiLength = Math.PI * 2;
  24567. }
  24568. _this = _BufferGeometry.call(this) || this;
  24569. _this.type = 'LatheGeometry';
  24570. _this.parameters = {
  24571. points: points,
  24572. segments: segments,
  24573. phiStart: phiStart,
  24574. phiLength: phiLength
  24575. };
  24576. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  24577. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  24578. var indices = [];
  24579. var vertices = [];
  24580. var uvs = []; // helper variables
  24581. var inverseSegments = 1.0 / segments;
  24582. var vertex = new Vector3();
  24583. var uv = new Vector2(); // generate vertices and uvs
  24584. for (var i = 0; i <= segments; i++) {
  24585. var phi = phiStart + i * inverseSegments * phiLength;
  24586. var sin = Math.sin(phi);
  24587. var cos = Math.cos(phi);
  24588. for (var j = 0; j <= points.length - 1; j++) {
  24589. // vertex
  24590. vertex.x = points[j].x * sin;
  24591. vertex.y = points[j].y;
  24592. vertex.z = points[j].x * cos;
  24593. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  24594. uv.x = i / segments;
  24595. uv.y = j / (points.length - 1);
  24596. uvs.push(uv.x, uv.y);
  24597. }
  24598. } // indices
  24599. for (var _i = 0; _i < segments; _i++) {
  24600. for (var _j = 0; _j < points.length - 1; _j++) {
  24601. var base = _j + _i * points.length;
  24602. var a = base;
  24603. var b = base + points.length;
  24604. var c = base + points.length + 1;
  24605. var d = base + 1; // faces
  24606. indices.push(a, b, d);
  24607. indices.push(b, c, d);
  24608. }
  24609. } // build geometry
  24610. _this.setIndex(indices);
  24611. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24612. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  24613. _this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  24614. // because the corresponding vertices are identical (but still have different UVs).
  24615. if (phiLength === Math.PI * 2) {
  24616. var normals = _this.attributes.normal.array;
  24617. var n1 = new Vector3();
  24618. var n2 = new Vector3();
  24619. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  24620. var _base = segments * points.length * 3;
  24621. for (var _i2 = 0, _j2 = 0; _i2 < points.length; _i2++, _j2 += 3) {
  24622. // select the normal of the vertex in the first line
  24623. n1.x = normals[_j2 + 0];
  24624. n1.y = normals[_j2 + 1];
  24625. n1.z = normals[_j2 + 2]; // select the normal of the vertex in the last line
  24626. n2.x = normals[_base + _j2 + 0];
  24627. n2.y = normals[_base + _j2 + 1];
  24628. n2.z = normals[_base + _j2 + 2]; // average normals
  24629. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  24630. normals[_j2 + 0] = normals[_base + _j2 + 0] = n.x;
  24631. normals[_j2 + 1] = normals[_base + _j2 + 1] = n.y;
  24632. normals[_j2 + 2] = normals[_base + _j2 + 2] = n.z;
  24633. }
  24634. }
  24635. return _this;
  24636. }
  24637. return LatheGeometry;
  24638. }(BufferGeometry);
  24639. var OctahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24640. _inheritsLoose(OctahedronGeometry, _PolyhedronGeometry);
  24641. function OctahedronGeometry(radius, detail) {
  24642. var _this;
  24643. if (radius === void 0) {
  24644. radius = 1;
  24645. }
  24646. if (detail === void 0) {
  24647. detail = 0;
  24648. }
  24649. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  24650. 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];
  24651. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24652. _this.type = 'OctahedronGeometry';
  24653. _this.parameters = {
  24654. radius: radius,
  24655. detail: detail
  24656. };
  24657. return _this;
  24658. }
  24659. return OctahedronGeometry;
  24660. }(PolyhedronGeometry);
  24661. /**
  24662. * Parametric Surfaces Geometry
  24663. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  24664. */
  24665. function ParametricGeometry(func, slices, stacks) {
  24666. BufferGeometry.call(this);
  24667. this.type = 'ParametricGeometry';
  24668. this.parameters = {
  24669. func: func,
  24670. slices: slices,
  24671. stacks: stacks
  24672. }; // buffers
  24673. var indices = [];
  24674. var vertices = [];
  24675. var normals = [];
  24676. var uvs = [];
  24677. var EPS = 0.00001;
  24678. var normal = new Vector3();
  24679. var p0 = new Vector3(),
  24680. p1 = new Vector3();
  24681. var pu = new Vector3(),
  24682. pv = new Vector3();
  24683. if (func.length < 3) {
  24684. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  24685. } // generate vertices, normals and uvs
  24686. var sliceCount = slices + 1;
  24687. for (var i = 0; i <= stacks; i++) {
  24688. var v = i / stacks;
  24689. for (var j = 0; j <= slices; j++) {
  24690. var u = j / slices; // vertex
  24691. func(u, v, p0);
  24692. vertices.push(p0.x, p0.y, p0.z); // normal
  24693. // approximate tangent vectors via finite differences
  24694. if (u - EPS >= 0) {
  24695. func(u - EPS, v, p1);
  24696. pu.subVectors(p0, p1);
  24697. } else {
  24698. func(u + EPS, v, p1);
  24699. pu.subVectors(p1, p0);
  24700. }
  24701. if (v - EPS >= 0) {
  24702. func(u, v - EPS, p1);
  24703. pv.subVectors(p0, p1);
  24704. } else {
  24705. func(u, v + EPS, p1);
  24706. pv.subVectors(p1, p0);
  24707. } // cross product of tangent vectors returns surface normal
  24708. normal.crossVectors(pu, pv).normalize();
  24709. normals.push(normal.x, normal.y, normal.z); // uv
  24710. uvs.push(u, v);
  24711. }
  24712. } // generate indices
  24713. for (var _i = 0; _i < stacks; _i++) {
  24714. for (var _j = 0; _j < slices; _j++) {
  24715. var a = _i * sliceCount + _j;
  24716. var b = _i * sliceCount + _j + 1;
  24717. var c = (_i + 1) * sliceCount + _j + 1;
  24718. var d = (_i + 1) * sliceCount + _j; // faces one and two
  24719. indices.push(a, b, d);
  24720. indices.push(b, c, d);
  24721. }
  24722. } // build geometry
  24723. this.setIndex(indices);
  24724. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24725. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24726. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24727. }
  24728. ParametricGeometry.prototype = Object.create(BufferGeometry.prototype);
  24729. ParametricGeometry.prototype.constructor = ParametricGeometry;
  24730. var RingGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24731. _inheritsLoose(RingGeometry, _BufferGeometry);
  24732. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  24733. var _this;
  24734. if (innerRadius === void 0) {
  24735. innerRadius = 0.5;
  24736. }
  24737. if (outerRadius === void 0) {
  24738. outerRadius = 1;
  24739. }
  24740. if (thetaSegments === void 0) {
  24741. thetaSegments = 8;
  24742. }
  24743. if (phiSegments === void 0) {
  24744. phiSegments = 1;
  24745. }
  24746. if (thetaStart === void 0) {
  24747. thetaStart = 0;
  24748. }
  24749. if (thetaLength === void 0) {
  24750. thetaLength = Math.PI * 2;
  24751. }
  24752. _this = _BufferGeometry.call(this) || this;
  24753. _this.type = 'RingGeometry';
  24754. _this.parameters = {
  24755. innerRadius: innerRadius,
  24756. outerRadius: outerRadius,
  24757. thetaSegments: thetaSegments,
  24758. phiSegments: phiSegments,
  24759. thetaStart: thetaStart,
  24760. thetaLength: thetaLength
  24761. };
  24762. thetaSegments = Math.max(3, thetaSegments);
  24763. phiSegments = Math.max(1, phiSegments); // buffers
  24764. var indices = [];
  24765. var vertices = [];
  24766. var normals = [];
  24767. var uvs = []; // some helper variables
  24768. var radius = innerRadius;
  24769. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  24770. var vertex = new Vector3();
  24771. var uv = new Vector2(); // generate vertices, normals and uvs
  24772. for (var j = 0; j <= phiSegments; j++) {
  24773. for (var i = 0; i <= thetaSegments; i++) {
  24774. // values are generate from the inside of the ring to the outside
  24775. var segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  24776. vertex.x = radius * Math.cos(segment);
  24777. vertex.y = radius * Math.sin(segment);
  24778. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  24779. normals.push(0, 0, 1); // uv
  24780. uv.x = (vertex.x / outerRadius + 1) / 2;
  24781. uv.y = (vertex.y / outerRadius + 1) / 2;
  24782. uvs.push(uv.x, uv.y);
  24783. } // increase the radius for next row of vertices
  24784. radius += radiusStep;
  24785. } // indices
  24786. for (var _j = 0; _j < phiSegments; _j++) {
  24787. var thetaSegmentLevel = _j * (thetaSegments + 1);
  24788. for (var _i = 0; _i < thetaSegments; _i++) {
  24789. var _segment = _i + thetaSegmentLevel;
  24790. var a = _segment;
  24791. var b = _segment + thetaSegments + 1;
  24792. var c = _segment + thetaSegments + 2;
  24793. var d = _segment + 1; // faces
  24794. indices.push(a, b, d);
  24795. indices.push(b, c, d);
  24796. }
  24797. } // build geometry
  24798. _this.setIndex(indices);
  24799. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24800. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24801. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24802. return _this;
  24803. }
  24804. return RingGeometry;
  24805. }(BufferGeometry);
  24806. var ShapeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24807. _inheritsLoose(ShapeGeometry, _BufferGeometry);
  24808. function ShapeGeometry(shapes, curveSegments) {
  24809. var _this;
  24810. if (curveSegments === void 0) {
  24811. curveSegments = 12;
  24812. }
  24813. _this = _BufferGeometry.call(this) || this;
  24814. _this.type = 'ShapeGeometry';
  24815. _this.parameters = {
  24816. shapes: shapes,
  24817. curveSegments: curveSegments
  24818. }; // buffers
  24819. var indices = [];
  24820. var vertices = [];
  24821. var normals = [];
  24822. var uvs = []; // helper variables
  24823. var groupStart = 0;
  24824. var groupCount = 0; // allow single and array values for "shapes" parameter
  24825. if (Array.isArray(shapes) === false) {
  24826. addShape(shapes);
  24827. } else {
  24828. for (var i = 0; i < shapes.length; i++) {
  24829. addShape(shapes[i]);
  24830. _this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  24831. groupStart += groupCount;
  24832. groupCount = 0;
  24833. }
  24834. } // build geometry
  24835. _this.setIndex(indices);
  24836. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24837. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24838. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  24839. function addShape(shape) {
  24840. var indexOffset = vertices.length / 3;
  24841. var points = shape.extractPoints(curveSegments);
  24842. var shapeVertices = points.shape;
  24843. var shapeHoles = points.holes; // check direction of vertices
  24844. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  24845. shapeVertices = shapeVertices.reverse();
  24846. }
  24847. for (var _i = 0, l = shapeHoles.length; _i < l; _i++) {
  24848. var shapeHole = shapeHoles[_i];
  24849. if (ShapeUtils.isClockWise(shapeHole) === true) {
  24850. shapeHoles[_i] = shapeHole.reverse();
  24851. }
  24852. }
  24853. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  24854. for (var _i2 = 0, _l = shapeHoles.length; _i2 < _l; _i2++) {
  24855. var _shapeHole = shapeHoles[_i2];
  24856. shapeVertices = shapeVertices.concat(_shapeHole);
  24857. } // vertices, normals, uvs
  24858. for (var _i3 = 0, _l2 = shapeVertices.length; _i3 < _l2; _i3++) {
  24859. var vertex = shapeVertices[_i3];
  24860. vertices.push(vertex.x, vertex.y, 0);
  24861. normals.push(0, 0, 1);
  24862. uvs.push(vertex.x, vertex.y); // world uvs
  24863. } // incides
  24864. for (var _i4 = 0, _l3 = faces.length; _i4 < _l3; _i4++) {
  24865. var face = faces[_i4];
  24866. var a = face[0] + indexOffset;
  24867. var b = face[1] + indexOffset;
  24868. var c = face[2] + indexOffset;
  24869. indices.push(a, b, c);
  24870. groupCount += 3;
  24871. }
  24872. }
  24873. return _this;
  24874. }
  24875. var _proto = ShapeGeometry.prototype;
  24876. _proto.toJSON = function toJSON() {
  24877. var data = BufferGeometry.prototype.toJSON.call(this);
  24878. var shapes = this.parameters.shapes;
  24879. return _toJSON$1(shapes, data);
  24880. };
  24881. return ShapeGeometry;
  24882. }(BufferGeometry);
  24883. function _toJSON$1(shapes, data) {
  24884. data.shapes = [];
  24885. if (Array.isArray(shapes)) {
  24886. for (var i = 0, l = shapes.length; i < l; i++) {
  24887. var shape = shapes[i];
  24888. data.shapes.push(shape.uuid);
  24889. }
  24890. } else {
  24891. data.shapes.push(shapes.uuid);
  24892. }
  24893. return data;
  24894. }
  24895. var SphereGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24896. _inheritsLoose(SphereGeometry, _BufferGeometry);
  24897. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  24898. var _this;
  24899. if (radius === void 0) {
  24900. radius = 1;
  24901. }
  24902. if (widthSegments === void 0) {
  24903. widthSegments = 8;
  24904. }
  24905. if (heightSegments === void 0) {
  24906. heightSegments = 6;
  24907. }
  24908. if (phiStart === void 0) {
  24909. phiStart = 0;
  24910. }
  24911. if (phiLength === void 0) {
  24912. phiLength = Math.PI * 2;
  24913. }
  24914. if (thetaStart === void 0) {
  24915. thetaStart = 0;
  24916. }
  24917. if (thetaLength === void 0) {
  24918. thetaLength = Math.PI;
  24919. }
  24920. _this = _BufferGeometry.call(this) || this;
  24921. _this.type = 'SphereGeometry';
  24922. _this.parameters = {
  24923. radius: radius,
  24924. widthSegments: widthSegments,
  24925. heightSegments: heightSegments,
  24926. phiStart: phiStart,
  24927. phiLength: phiLength,
  24928. thetaStart: thetaStart,
  24929. thetaLength: thetaLength
  24930. };
  24931. widthSegments = Math.max(3, Math.floor(widthSegments));
  24932. heightSegments = Math.max(2, Math.floor(heightSegments));
  24933. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  24934. var index = 0;
  24935. var grid = [];
  24936. var vertex = new Vector3();
  24937. var normal = new Vector3(); // buffers
  24938. var indices = [];
  24939. var vertices = [];
  24940. var normals = [];
  24941. var uvs = []; // generate vertices, normals and uvs
  24942. for (var iy = 0; iy <= heightSegments; iy++) {
  24943. var verticesRow = [];
  24944. var v = iy / heightSegments; // special case for the poles
  24945. var uOffset = 0;
  24946. if (iy == 0 && thetaStart == 0) {
  24947. uOffset = 0.5 / widthSegments;
  24948. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  24949. uOffset = -0.5 / widthSegments;
  24950. }
  24951. for (var ix = 0; ix <= widthSegments; ix++) {
  24952. var u = ix / widthSegments; // vertex
  24953. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  24954. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  24955. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  24956. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  24957. normal.copy(vertex).normalize();
  24958. normals.push(normal.x, normal.y, normal.z); // uv
  24959. uvs.push(u + uOffset, 1 - v);
  24960. verticesRow.push(index++);
  24961. }
  24962. grid.push(verticesRow);
  24963. } // indices
  24964. for (var _iy = 0; _iy < heightSegments; _iy++) {
  24965. for (var _ix = 0; _ix < widthSegments; _ix++) {
  24966. var a = grid[_iy][_ix + 1];
  24967. var b = grid[_iy][_ix];
  24968. var c = grid[_iy + 1][_ix];
  24969. var d = grid[_iy + 1][_ix + 1];
  24970. if (_iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  24971. if (_iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  24972. }
  24973. } // build geometry
  24974. _this.setIndex(indices);
  24975. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24976. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24977. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24978. return _this;
  24979. }
  24980. return SphereGeometry;
  24981. }(BufferGeometry);
  24982. var TetrahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24983. _inheritsLoose(TetrahedronGeometry, _PolyhedronGeometry);
  24984. function TetrahedronGeometry(radius, detail) {
  24985. var _this;
  24986. if (radius === void 0) {
  24987. radius = 1;
  24988. }
  24989. if (detail === void 0) {
  24990. detail = 0;
  24991. }
  24992. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  24993. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  24994. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24995. _this.type = 'TetrahedronGeometry';
  24996. _this.parameters = {
  24997. radius: radius,
  24998. detail: detail
  24999. };
  25000. return _this;
  25001. }
  25002. return TetrahedronGeometry;
  25003. }(PolyhedronGeometry);
  25004. var TextGeometry = /*#__PURE__*/function (_ExtrudeGeometry) {
  25005. _inheritsLoose(TextGeometry, _ExtrudeGeometry);
  25006. function TextGeometry(text, parameters) {
  25007. var _this;
  25008. if (parameters === void 0) {
  25009. parameters = {};
  25010. }
  25011. var font = parameters.font;
  25012. if (!(font && font.isFont)) {
  25013. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  25014. return new BufferGeometry() || _assertThisInitialized(_this);
  25015. }
  25016. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  25017. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  25018. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  25019. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  25020. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  25021. _this = _ExtrudeGeometry.call(this, shapes, parameters) || this;
  25022. _this.type = 'TextGeometry';
  25023. return _this;
  25024. }
  25025. return TextGeometry;
  25026. }(ExtrudeGeometry);
  25027. var TorusGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25028. _inheritsLoose(TorusGeometry, _BufferGeometry);
  25029. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  25030. var _this;
  25031. if (radius === void 0) {
  25032. radius = 1;
  25033. }
  25034. if (tube === void 0) {
  25035. tube = 0.4;
  25036. }
  25037. if (radialSegments === void 0) {
  25038. radialSegments = 8;
  25039. }
  25040. if (tubularSegments === void 0) {
  25041. tubularSegments = 6;
  25042. }
  25043. if (arc === void 0) {
  25044. arc = Math.PI * 2;
  25045. }
  25046. _this = _BufferGeometry.call(this) || this;
  25047. _this.type = 'TorusGeometry';
  25048. _this.parameters = {
  25049. radius: radius,
  25050. tube: tube,
  25051. radialSegments: radialSegments,
  25052. tubularSegments: tubularSegments,
  25053. arc: arc
  25054. };
  25055. radialSegments = Math.floor(radialSegments);
  25056. tubularSegments = Math.floor(tubularSegments); // buffers
  25057. var indices = [];
  25058. var vertices = [];
  25059. var normals = [];
  25060. var uvs = []; // helper variables
  25061. var center = new Vector3();
  25062. var vertex = new Vector3();
  25063. var normal = new Vector3(); // generate vertices, normals and uvs
  25064. for (var j = 0; j <= radialSegments; j++) {
  25065. for (var i = 0; i <= tubularSegments; i++) {
  25066. var u = i / tubularSegments * arc;
  25067. var v = j / radialSegments * Math.PI * 2; // vertex
  25068. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  25069. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  25070. vertex.z = tube * Math.sin(v);
  25071. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  25072. center.x = radius * Math.cos(u);
  25073. center.y = radius * Math.sin(u);
  25074. normal.subVectors(vertex, center).normalize();
  25075. normals.push(normal.x, normal.y, normal.z); // uv
  25076. uvs.push(i / tubularSegments);
  25077. uvs.push(j / radialSegments);
  25078. }
  25079. } // generate indices
  25080. for (var _j = 1; _j <= radialSegments; _j++) {
  25081. for (var _i = 1; _i <= tubularSegments; _i++) {
  25082. // indices
  25083. var a = (tubularSegments + 1) * _j + _i - 1;
  25084. var b = (tubularSegments + 1) * (_j - 1) + _i - 1;
  25085. var c = (tubularSegments + 1) * (_j - 1) + _i;
  25086. var d = (tubularSegments + 1) * _j + _i; // faces
  25087. indices.push(a, b, d);
  25088. indices.push(b, c, d);
  25089. }
  25090. } // build geometry
  25091. _this.setIndex(indices);
  25092. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25093. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25094. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25095. return _this;
  25096. }
  25097. return TorusGeometry;
  25098. }(BufferGeometry);
  25099. var TorusKnotGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25100. _inheritsLoose(TorusKnotGeometry, _BufferGeometry);
  25101. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  25102. var _this;
  25103. if (radius === void 0) {
  25104. radius = 1;
  25105. }
  25106. if (tube === void 0) {
  25107. tube = 0.4;
  25108. }
  25109. if (tubularSegments === void 0) {
  25110. tubularSegments = 64;
  25111. }
  25112. if (radialSegments === void 0) {
  25113. radialSegments = 8;
  25114. }
  25115. if (p === void 0) {
  25116. p = 2;
  25117. }
  25118. if (q === void 0) {
  25119. q = 3;
  25120. }
  25121. _this = _BufferGeometry.call(this) || this;
  25122. _this.type = 'TorusKnotGeometry';
  25123. _this.parameters = {
  25124. radius: radius,
  25125. tube: tube,
  25126. tubularSegments: tubularSegments,
  25127. radialSegments: radialSegments,
  25128. p: p,
  25129. q: q
  25130. };
  25131. tubularSegments = Math.floor(tubularSegments);
  25132. radialSegments = Math.floor(radialSegments); // buffers
  25133. var indices = [];
  25134. var vertices = [];
  25135. var normals = [];
  25136. var uvs = []; // helper variables
  25137. var vertex = new Vector3();
  25138. var normal = new Vector3();
  25139. var P1 = new Vector3();
  25140. var P2 = new Vector3();
  25141. var B = new Vector3();
  25142. var T = new Vector3();
  25143. var N = new Vector3(); // generate vertices, normals and uvs
  25144. for (var i = 0; i <= tubularSegments; ++i) {
  25145. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  25146. 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.
  25147. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  25148. calculatePositionOnCurve(u, p, q, radius, P1);
  25149. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  25150. T.subVectors(P2, P1);
  25151. N.addVectors(P2, P1);
  25152. B.crossVectors(T, N);
  25153. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  25154. B.normalize();
  25155. N.normalize();
  25156. for (var j = 0; j <= radialSegments; ++j) {
  25157. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  25158. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  25159. var v = j / radialSegments * Math.PI * 2;
  25160. var cx = -tube * Math.cos(v);
  25161. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  25162. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  25163. vertex.x = P1.x + (cx * N.x + cy * B.x);
  25164. vertex.y = P1.y + (cx * N.y + cy * B.y);
  25165. vertex.z = P1.z + (cx * N.z + cy * B.z);
  25166. 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)
  25167. normal.subVectors(vertex, P1).normalize();
  25168. normals.push(normal.x, normal.y, normal.z); // uv
  25169. uvs.push(i / tubularSegments);
  25170. uvs.push(j / radialSegments);
  25171. }
  25172. } // generate indices
  25173. for (var _j = 1; _j <= tubularSegments; _j++) {
  25174. for (var _i = 1; _i <= radialSegments; _i++) {
  25175. // indices
  25176. var a = (radialSegments + 1) * (_j - 1) + (_i - 1);
  25177. var b = (radialSegments + 1) * _j + (_i - 1);
  25178. var c = (radialSegments + 1) * _j + _i;
  25179. var d = (radialSegments + 1) * (_j - 1) + _i; // faces
  25180. indices.push(a, b, d);
  25181. indices.push(b, c, d);
  25182. }
  25183. } // build geometry
  25184. _this.setIndex(indices);
  25185. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25186. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25187. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  25188. function calculatePositionOnCurve(u, p, q, radius, position) {
  25189. var cu = Math.cos(u);
  25190. var su = Math.sin(u);
  25191. var quOverP = q / p * u;
  25192. var cs = Math.cos(quOverP);
  25193. position.x = radius * (2 + cs) * 0.5 * cu;
  25194. position.y = radius * (2 + cs) * su * 0.5;
  25195. position.z = radius * Math.sin(quOverP) * 0.5;
  25196. }
  25197. return _this;
  25198. }
  25199. return TorusKnotGeometry;
  25200. }(BufferGeometry);
  25201. var TubeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25202. _inheritsLoose(TubeGeometry, _BufferGeometry);
  25203. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed) {
  25204. var _this;
  25205. if (tubularSegments === void 0) {
  25206. tubularSegments = 64;
  25207. }
  25208. if (radius === void 0) {
  25209. radius = 1;
  25210. }
  25211. if (radialSegments === void 0) {
  25212. radialSegments = 8;
  25213. }
  25214. if (closed === void 0) {
  25215. closed = false;
  25216. }
  25217. _this = _BufferGeometry.call(this) || this;
  25218. _this.type = 'TubeGeometry';
  25219. _this.parameters = {
  25220. path: path,
  25221. tubularSegments: tubularSegments,
  25222. radius: radius,
  25223. radialSegments: radialSegments,
  25224. closed: closed
  25225. };
  25226. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  25227. _this.tangents = frames.tangents;
  25228. _this.normals = frames.normals;
  25229. _this.binormals = frames.binormals; // helper variables
  25230. var vertex = new Vector3();
  25231. var normal = new Vector3();
  25232. var uv = new Vector2();
  25233. var P = new Vector3(); // buffer
  25234. var vertices = [];
  25235. var normals = [];
  25236. var uvs = [];
  25237. var indices = []; // create buffer data
  25238. generateBufferData(); // build geometry
  25239. _this.setIndex(indices);
  25240. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25241. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25242. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  25243. function generateBufferData() {
  25244. for (var i = 0; i < tubularSegments; i++) {
  25245. generateSegment(i);
  25246. } // if the geometry is not closed, generate the last row of vertices and normals
  25247. // at the regular position on the given path
  25248. //
  25249. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  25250. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  25251. // this makes it easy compute correct values for closed geometries
  25252. generateUVs(); // finally create faces
  25253. generateIndices();
  25254. }
  25255. function generateSegment(i) {
  25256. // we use getPointAt to sample evenly distributed points from the given path
  25257. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  25258. var N = frames.normals[i];
  25259. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  25260. for (var j = 0; j <= radialSegments; j++) {
  25261. var v = j / radialSegments * Math.PI * 2;
  25262. var sin = Math.sin(v);
  25263. var cos = -Math.cos(v); // normal
  25264. normal.x = cos * N.x + sin * B.x;
  25265. normal.y = cos * N.y + sin * B.y;
  25266. normal.z = cos * N.z + sin * B.z;
  25267. normal.normalize();
  25268. normals.push(normal.x, normal.y, normal.z); // vertex
  25269. vertex.x = P.x + radius * normal.x;
  25270. vertex.y = P.y + radius * normal.y;
  25271. vertex.z = P.z + radius * normal.z;
  25272. vertices.push(vertex.x, vertex.y, vertex.z);
  25273. }
  25274. }
  25275. function generateIndices() {
  25276. for (var j = 1; j <= tubularSegments; j++) {
  25277. for (var i = 1; i <= radialSegments; i++) {
  25278. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  25279. var b = (radialSegments + 1) * j + (i - 1);
  25280. var c = (radialSegments + 1) * j + i;
  25281. var d = (radialSegments + 1) * (j - 1) + i; // faces
  25282. indices.push(a, b, d);
  25283. indices.push(b, c, d);
  25284. }
  25285. }
  25286. }
  25287. function generateUVs() {
  25288. for (var i = 0; i <= tubularSegments; i++) {
  25289. for (var j = 0; j <= radialSegments; j++) {
  25290. uv.x = i / tubularSegments;
  25291. uv.y = j / radialSegments;
  25292. uvs.push(uv.x, uv.y);
  25293. }
  25294. }
  25295. }
  25296. return _this;
  25297. }
  25298. var _proto = TubeGeometry.prototype;
  25299. _proto.toJSON = function toJSON() {
  25300. var data = BufferGeometry.prototype.toJSON.call(this);
  25301. data.path = this.parameters.path.toJSON();
  25302. return data;
  25303. };
  25304. return TubeGeometry;
  25305. }(BufferGeometry);
  25306. var WireframeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25307. _inheritsLoose(WireframeGeometry, _BufferGeometry);
  25308. function WireframeGeometry(geometry) {
  25309. var _this;
  25310. _this = _BufferGeometry.call(this) || this;
  25311. _this.type = 'WireframeGeometry';
  25312. if (geometry.isGeometry === true) {
  25313. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  25314. return _assertThisInitialized(_this);
  25315. } // buffer
  25316. var vertices = []; // helper variables
  25317. var edge = [0, 0],
  25318. edges = {};
  25319. var vertex = new Vector3();
  25320. if (geometry.index !== null) {
  25321. // indexed BufferGeometry
  25322. var position = geometry.attributes.position;
  25323. var indices = geometry.index;
  25324. var groups = geometry.groups;
  25325. if (groups.length === 0) {
  25326. groups = [{
  25327. start: 0,
  25328. count: indices.count,
  25329. materialIndex: 0
  25330. }];
  25331. } // create a data structure that contains all eges without duplicates
  25332. for (var o = 0, ol = groups.length; o < ol; ++o) {
  25333. var group = groups[o];
  25334. var start = group.start;
  25335. var count = group.count;
  25336. for (var i = start, l = start + count; i < l; i += 3) {
  25337. for (var j = 0; j < 3; j++) {
  25338. var edge1 = indices.getX(i + j);
  25339. var edge2 = indices.getX(i + (j + 1) % 3);
  25340. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  25341. edge[1] = Math.max(edge1, edge2);
  25342. var key = edge[0] + ',' + edge[1];
  25343. if (edges[key] === undefined) {
  25344. edges[key] = {
  25345. index1: edge[0],
  25346. index2: edge[1]
  25347. };
  25348. }
  25349. }
  25350. }
  25351. } // generate vertices
  25352. for (var _key in edges) {
  25353. var e = edges[_key];
  25354. vertex.fromBufferAttribute(position, e.index1);
  25355. vertices.push(vertex.x, vertex.y, vertex.z);
  25356. vertex.fromBufferAttribute(position, e.index2);
  25357. vertices.push(vertex.x, vertex.y, vertex.z);
  25358. }
  25359. } else {
  25360. // non-indexed BufferGeometry
  25361. var _position = geometry.attributes.position;
  25362. for (var _i = 0, _l = _position.count / 3; _i < _l; _i++) {
  25363. for (var _j = 0; _j < 3; _j++) {
  25364. // three edges per triangle, an edge is represented as (index1, index2)
  25365. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  25366. var index1 = 3 * _i + _j;
  25367. vertex.fromBufferAttribute(_position, index1);
  25368. vertices.push(vertex.x, vertex.y, vertex.z);
  25369. var index2 = 3 * _i + (_j + 1) % 3;
  25370. vertex.fromBufferAttribute(_position, index2);
  25371. vertices.push(vertex.x, vertex.y, vertex.z);
  25372. }
  25373. }
  25374. } // build geometry
  25375. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25376. return _this;
  25377. }
  25378. return WireframeGeometry;
  25379. }(BufferGeometry);
  25380. var Geometries = /*#__PURE__*/Object.freeze({
  25381. __proto__: null,
  25382. BoxGeometry: BoxGeometry,
  25383. BoxBufferGeometry: BoxGeometry,
  25384. CircleGeometry: CircleGeometry,
  25385. CircleBufferGeometry: CircleGeometry,
  25386. ConeGeometry: ConeGeometry,
  25387. ConeBufferGeometry: ConeGeometry,
  25388. CylinderGeometry: CylinderGeometry,
  25389. CylinderBufferGeometry: CylinderGeometry,
  25390. DodecahedronGeometry: DodecahedronGeometry,
  25391. DodecahedronBufferGeometry: DodecahedronGeometry,
  25392. EdgesGeometry: EdgesGeometry,
  25393. ExtrudeGeometry: ExtrudeGeometry,
  25394. ExtrudeBufferGeometry: ExtrudeGeometry,
  25395. IcosahedronGeometry: IcosahedronGeometry,
  25396. IcosahedronBufferGeometry: IcosahedronGeometry,
  25397. LatheGeometry: LatheGeometry,
  25398. LatheBufferGeometry: LatheGeometry,
  25399. OctahedronGeometry: OctahedronGeometry,
  25400. OctahedronBufferGeometry: OctahedronGeometry,
  25401. ParametricGeometry: ParametricGeometry,
  25402. ParametricBufferGeometry: ParametricGeometry,
  25403. PlaneGeometry: PlaneGeometry,
  25404. PlaneBufferGeometry: PlaneGeometry,
  25405. PolyhedronGeometry: PolyhedronGeometry,
  25406. PolyhedronBufferGeometry: PolyhedronGeometry,
  25407. RingGeometry: RingGeometry,
  25408. RingBufferGeometry: RingGeometry,
  25409. ShapeGeometry: ShapeGeometry,
  25410. ShapeBufferGeometry: ShapeGeometry,
  25411. SphereGeometry: SphereGeometry,
  25412. SphereBufferGeometry: SphereGeometry,
  25413. TetrahedronGeometry: TetrahedronGeometry,
  25414. TetrahedronBufferGeometry: TetrahedronGeometry,
  25415. TextGeometry: TextGeometry,
  25416. TextBufferGeometry: TextGeometry,
  25417. TorusGeometry: TorusGeometry,
  25418. TorusBufferGeometry: TorusGeometry,
  25419. TorusKnotGeometry: TorusKnotGeometry,
  25420. TorusKnotBufferGeometry: TorusKnotGeometry,
  25421. TubeGeometry: TubeGeometry,
  25422. TubeBufferGeometry: TubeGeometry,
  25423. WireframeGeometry: WireframeGeometry
  25424. });
  25425. /**
  25426. * parameters = {
  25427. * color: <THREE.Color>
  25428. * }
  25429. */
  25430. function ShadowMaterial(parameters) {
  25431. Material.call(this);
  25432. this.type = 'ShadowMaterial';
  25433. this.color = new Color(0x000000);
  25434. this.transparent = true;
  25435. this.setValues(parameters);
  25436. }
  25437. ShadowMaterial.prototype = Object.create(Material.prototype);
  25438. ShadowMaterial.prototype.constructor = ShadowMaterial;
  25439. ShadowMaterial.prototype.isShadowMaterial = true;
  25440. ShadowMaterial.prototype.copy = function (source) {
  25441. Material.prototype.copy.call(this, source);
  25442. this.color.copy(source.color);
  25443. return this;
  25444. };
  25445. function RawShaderMaterial(parameters) {
  25446. ShaderMaterial.call(this, parameters);
  25447. this.type = 'RawShaderMaterial';
  25448. }
  25449. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  25450. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  25451. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  25452. /**
  25453. * parameters = {
  25454. * color: <hex>,
  25455. * roughness: <float>,
  25456. * metalness: <float>,
  25457. * opacity: <float>,
  25458. *
  25459. * map: new THREE.Texture( <Image> ),
  25460. *
  25461. * lightMap: new THREE.Texture( <Image> ),
  25462. * lightMapIntensity: <float>
  25463. *
  25464. * aoMap: new THREE.Texture( <Image> ),
  25465. * aoMapIntensity: <float>
  25466. *
  25467. * emissive: <hex>,
  25468. * emissiveIntensity: <float>
  25469. * emissiveMap: new THREE.Texture( <Image> ),
  25470. *
  25471. * bumpMap: new THREE.Texture( <Image> ),
  25472. * bumpScale: <float>,
  25473. *
  25474. * normalMap: new THREE.Texture( <Image> ),
  25475. * normalMapType: THREE.TangentSpaceNormalMap,
  25476. * normalScale: <Vector2>,
  25477. *
  25478. * displacementMap: new THREE.Texture( <Image> ),
  25479. * displacementScale: <float>,
  25480. * displacementBias: <float>,
  25481. *
  25482. * roughnessMap: new THREE.Texture( <Image> ),
  25483. *
  25484. * metalnessMap: new THREE.Texture( <Image> ),
  25485. *
  25486. * alphaMap: new THREE.Texture( <Image> ),
  25487. *
  25488. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25489. * envMapIntensity: <float>
  25490. *
  25491. * refractionRatio: <float>,
  25492. *
  25493. * wireframe: <boolean>,
  25494. * wireframeLinewidth: <float>,
  25495. *
  25496. * skinning: <bool>,
  25497. * morphTargets: <bool>,
  25498. * morphNormals: <bool>
  25499. * }
  25500. */
  25501. function MeshStandardMaterial(parameters) {
  25502. Material.call(this);
  25503. this.defines = {
  25504. 'STANDARD': ''
  25505. };
  25506. this.type = 'MeshStandardMaterial';
  25507. this.color = new Color(0xffffff); // diffuse
  25508. this.roughness = 1.0;
  25509. this.metalness = 0.0;
  25510. this.map = null;
  25511. this.lightMap = null;
  25512. this.lightMapIntensity = 1.0;
  25513. this.aoMap = null;
  25514. this.aoMapIntensity = 1.0;
  25515. this.emissive = new Color(0x000000);
  25516. this.emissiveIntensity = 1.0;
  25517. this.emissiveMap = null;
  25518. this.bumpMap = null;
  25519. this.bumpScale = 1;
  25520. this.normalMap = null;
  25521. this.normalMapType = TangentSpaceNormalMap;
  25522. this.normalScale = new Vector2(1, 1);
  25523. this.displacementMap = null;
  25524. this.displacementScale = 1;
  25525. this.displacementBias = 0;
  25526. this.roughnessMap = null;
  25527. this.metalnessMap = null;
  25528. this.alphaMap = null;
  25529. this.envMap = null;
  25530. this.envMapIntensity = 1.0;
  25531. this.refractionRatio = 0.98;
  25532. this.wireframe = false;
  25533. this.wireframeLinewidth = 1;
  25534. this.wireframeLinecap = 'round';
  25535. this.wireframeLinejoin = 'round';
  25536. this.skinning = false;
  25537. this.morphTargets = false;
  25538. this.morphNormals = false;
  25539. this.vertexTangents = false;
  25540. this.setValues(parameters);
  25541. }
  25542. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  25543. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  25544. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  25545. MeshStandardMaterial.prototype.copy = function (source) {
  25546. Material.prototype.copy.call(this, source);
  25547. this.defines = {
  25548. 'STANDARD': ''
  25549. };
  25550. this.color.copy(source.color);
  25551. this.roughness = source.roughness;
  25552. this.metalness = source.metalness;
  25553. this.map = source.map;
  25554. this.lightMap = source.lightMap;
  25555. this.lightMapIntensity = source.lightMapIntensity;
  25556. this.aoMap = source.aoMap;
  25557. this.aoMapIntensity = source.aoMapIntensity;
  25558. this.emissive.copy(source.emissive);
  25559. this.emissiveMap = source.emissiveMap;
  25560. this.emissiveIntensity = source.emissiveIntensity;
  25561. this.bumpMap = source.bumpMap;
  25562. this.bumpScale = source.bumpScale;
  25563. this.normalMap = source.normalMap;
  25564. this.normalMapType = source.normalMapType;
  25565. this.normalScale.copy(source.normalScale);
  25566. this.displacementMap = source.displacementMap;
  25567. this.displacementScale = source.displacementScale;
  25568. this.displacementBias = source.displacementBias;
  25569. this.roughnessMap = source.roughnessMap;
  25570. this.metalnessMap = source.metalnessMap;
  25571. this.alphaMap = source.alphaMap;
  25572. this.envMap = source.envMap;
  25573. this.envMapIntensity = source.envMapIntensity;
  25574. this.refractionRatio = source.refractionRatio;
  25575. this.wireframe = source.wireframe;
  25576. this.wireframeLinewidth = source.wireframeLinewidth;
  25577. this.wireframeLinecap = source.wireframeLinecap;
  25578. this.wireframeLinejoin = source.wireframeLinejoin;
  25579. this.skinning = source.skinning;
  25580. this.morphTargets = source.morphTargets;
  25581. this.morphNormals = source.morphNormals;
  25582. this.vertexTangents = source.vertexTangents;
  25583. return this;
  25584. };
  25585. /**
  25586. * parameters = {
  25587. * clearcoat: <float>,
  25588. * clearcoatMap: new THREE.Texture( <Image> ),
  25589. * clearcoatRoughness: <float>,
  25590. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  25591. * clearcoatNormalScale: <Vector2>,
  25592. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  25593. *
  25594. * reflectivity: <float>,
  25595. * ior: <float>,
  25596. *
  25597. * sheen: <Color>,
  25598. *
  25599. * transmission: <float>,
  25600. * transmissionMap: new THREE.Texture( <Image> )
  25601. * }
  25602. */
  25603. function MeshPhysicalMaterial(parameters) {
  25604. MeshStandardMaterial.call(this);
  25605. this.defines = {
  25606. 'STANDARD': '',
  25607. 'PHYSICAL': ''
  25608. };
  25609. this.type = 'MeshPhysicalMaterial';
  25610. this.clearcoat = 0.0;
  25611. this.clearcoatMap = null;
  25612. this.clearcoatRoughness = 0.0;
  25613. this.clearcoatRoughnessMap = null;
  25614. this.clearcoatNormalScale = new Vector2(1, 1);
  25615. this.clearcoatNormalMap = null;
  25616. this.reflectivity = 0.5; // maps to F0 = 0.04
  25617. Object.defineProperty(this, 'ior', {
  25618. get: function get() {
  25619. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  25620. },
  25621. set: function set(ior) {
  25622. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  25623. }
  25624. });
  25625. this.sheen = null; // null will disable sheen bsdf
  25626. this.transmission = 0.0;
  25627. this.transmissionMap = null;
  25628. this.setValues(parameters);
  25629. }
  25630. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  25631. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  25632. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  25633. MeshPhysicalMaterial.prototype.copy = function (source) {
  25634. MeshStandardMaterial.prototype.copy.call(this, source);
  25635. this.defines = {
  25636. 'STANDARD': '',
  25637. 'PHYSICAL': ''
  25638. };
  25639. this.clearcoat = source.clearcoat;
  25640. this.clearcoatMap = source.clearcoatMap;
  25641. this.clearcoatRoughness = source.clearcoatRoughness;
  25642. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  25643. this.clearcoatNormalMap = source.clearcoatNormalMap;
  25644. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  25645. this.reflectivity = source.reflectivity;
  25646. if (source.sheen) {
  25647. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  25648. } else {
  25649. this.sheen = null;
  25650. }
  25651. this.transmission = source.transmission;
  25652. this.transmissionMap = source.transmissionMap;
  25653. return this;
  25654. };
  25655. /**
  25656. * parameters = {
  25657. * color: <hex>,
  25658. * specular: <hex>,
  25659. * shininess: <float>,
  25660. * opacity: <float>,
  25661. *
  25662. * map: new THREE.Texture( <Image> ),
  25663. *
  25664. * lightMap: new THREE.Texture( <Image> ),
  25665. * lightMapIntensity: <float>
  25666. *
  25667. * aoMap: new THREE.Texture( <Image> ),
  25668. * aoMapIntensity: <float>
  25669. *
  25670. * emissive: <hex>,
  25671. * emissiveIntensity: <float>
  25672. * emissiveMap: new THREE.Texture( <Image> ),
  25673. *
  25674. * bumpMap: new THREE.Texture( <Image> ),
  25675. * bumpScale: <float>,
  25676. *
  25677. * normalMap: new THREE.Texture( <Image> ),
  25678. * normalMapType: THREE.TangentSpaceNormalMap,
  25679. * normalScale: <Vector2>,
  25680. *
  25681. * displacementMap: new THREE.Texture( <Image> ),
  25682. * displacementScale: <float>,
  25683. * displacementBias: <float>,
  25684. *
  25685. * specularMap: new THREE.Texture( <Image> ),
  25686. *
  25687. * alphaMap: new THREE.Texture( <Image> ),
  25688. *
  25689. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25690. * combine: THREE.MultiplyOperation,
  25691. * reflectivity: <float>,
  25692. * refractionRatio: <float>,
  25693. *
  25694. * wireframe: <boolean>,
  25695. * wireframeLinewidth: <float>,
  25696. *
  25697. * skinning: <bool>,
  25698. * morphTargets: <bool>,
  25699. * morphNormals: <bool>
  25700. * }
  25701. */
  25702. function MeshPhongMaterial(parameters) {
  25703. Material.call(this);
  25704. this.type = 'MeshPhongMaterial';
  25705. this.color = new Color(0xffffff); // diffuse
  25706. this.specular = new Color(0x111111);
  25707. this.shininess = 30;
  25708. this.map = null;
  25709. this.lightMap = null;
  25710. this.lightMapIntensity = 1.0;
  25711. this.aoMap = null;
  25712. this.aoMapIntensity = 1.0;
  25713. this.emissive = new Color(0x000000);
  25714. this.emissiveIntensity = 1.0;
  25715. this.emissiveMap = null;
  25716. this.bumpMap = null;
  25717. this.bumpScale = 1;
  25718. this.normalMap = null;
  25719. this.normalMapType = TangentSpaceNormalMap;
  25720. this.normalScale = new Vector2(1, 1);
  25721. this.displacementMap = null;
  25722. this.displacementScale = 1;
  25723. this.displacementBias = 0;
  25724. this.specularMap = null;
  25725. this.alphaMap = null;
  25726. this.envMap = null;
  25727. this.combine = MultiplyOperation;
  25728. this.reflectivity = 1;
  25729. this.refractionRatio = 0.98;
  25730. this.wireframe = false;
  25731. this.wireframeLinewidth = 1;
  25732. this.wireframeLinecap = 'round';
  25733. this.wireframeLinejoin = 'round';
  25734. this.skinning = false;
  25735. this.morphTargets = false;
  25736. this.morphNormals = false;
  25737. this.setValues(parameters);
  25738. }
  25739. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  25740. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  25741. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  25742. MeshPhongMaterial.prototype.copy = function (source) {
  25743. Material.prototype.copy.call(this, source);
  25744. this.color.copy(source.color);
  25745. this.specular.copy(source.specular);
  25746. this.shininess = source.shininess;
  25747. this.map = source.map;
  25748. this.lightMap = source.lightMap;
  25749. this.lightMapIntensity = source.lightMapIntensity;
  25750. this.aoMap = source.aoMap;
  25751. this.aoMapIntensity = source.aoMapIntensity;
  25752. this.emissive.copy(source.emissive);
  25753. this.emissiveMap = source.emissiveMap;
  25754. this.emissiveIntensity = source.emissiveIntensity;
  25755. this.bumpMap = source.bumpMap;
  25756. this.bumpScale = source.bumpScale;
  25757. this.normalMap = source.normalMap;
  25758. this.normalMapType = source.normalMapType;
  25759. this.normalScale.copy(source.normalScale);
  25760. this.displacementMap = source.displacementMap;
  25761. this.displacementScale = source.displacementScale;
  25762. this.displacementBias = source.displacementBias;
  25763. this.specularMap = source.specularMap;
  25764. this.alphaMap = source.alphaMap;
  25765. this.envMap = source.envMap;
  25766. this.combine = source.combine;
  25767. this.reflectivity = source.reflectivity;
  25768. this.refractionRatio = source.refractionRatio;
  25769. this.wireframe = source.wireframe;
  25770. this.wireframeLinewidth = source.wireframeLinewidth;
  25771. this.wireframeLinecap = source.wireframeLinecap;
  25772. this.wireframeLinejoin = source.wireframeLinejoin;
  25773. this.skinning = source.skinning;
  25774. this.morphTargets = source.morphTargets;
  25775. this.morphNormals = source.morphNormals;
  25776. return this;
  25777. };
  25778. /**
  25779. * parameters = {
  25780. * color: <hex>,
  25781. *
  25782. * map: new THREE.Texture( <Image> ),
  25783. * gradientMap: new THREE.Texture( <Image> ),
  25784. *
  25785. * lightMap: new THREE.Texture( <Image> ),
  25786. * lightMapIntensity: <float>
  25787. *
  25788. * aoMap: new THREE.Texture( <Image> ),
  25789. * aoMapIntensity: <float>
  25790. *
  25791. * emissive: <hex>,
  25792. * emissiveIntensity: <float>
  25793. * emissiveMap: new THREE.Texture( <Image> ),
  25794. *
  25795. * bumpMap: new THREE.Texture( <Image> ),
  25796. * bumpScale: <float>,
  25797. *
  25798. * normalMap: new THREE.Texture( <Image> ),
  25799. * normalMapType: THREE.TangentSpaceNormalMap,
  25800. * normalScale: <Vector2>,
  25801. *
  25802. * displacementMap: new THREE.Texture( <Image> ),
  25803. * displacementScale: <float>,
  25804. * displacementBias: <float>,
  25805. *
  25806. * alphaMap: new THREE.Texture( <Image> ),
  25807. *
  25808. * wireframe: <boolean>,
  25809. * wireframeLinewidth: <float>,
  25810. *
  25811. * skinning: <bool>,
  25812. * morphTargets: <bool>,
  25813. * morphNormals: <bool>
  25814. * }
  25815. */
  25816. function MeshToonMaterial(parameters) {
  25817. Material.call(this);
  25818. this.defines = {
  25819. 'TOON': ''
  25820. };
  25821. this.type = 'MeshToonMaterial';
  25822. this.color = new Color(0xffffff);
  25823. this.map = null;
  25824. this.gradientMap = null;
  25825. this.lightMap = null;
  25826. this.lightMapIntensity = 1.0;
  25827. this.aoMap = null;
  25828. this.aoMapIntensity = 1.0;
  25829. this.emissive = new Color(0x000000);
  25830. this.emissiveIntensity = 1.0;
  25831. this.emissiveMap = null;
  25832. this.bumpMap = null;
  25833. this.bumpScale = 1;
  25834. this.normalMap = null;
  25835. this.normalMapType = TangentSpaceNormalMap;
  25836. this.normalScale = new Vector2(1, 1);
  25837. this.displacementMap = null;
  25838. this.displacementScale = 1;
  25839. this.displacementBias = 0;
  25840. this.alphaMap = null;
  25841. this.wireframe = false;
  25842. this.wireframeLinewidth = 1;
  25843. this.wireframeLinecap = 'round';
  25844. this.wireframeLinejoin = 'round';
  25845. this.skinning = false;
  25846. this.morphTargets = false;
  25847. this.morphNormals = false;
  25848. this.setValues(parameters);
  25849. }
  25850. MeshToonMaterial.prototype = Object.create(Material.prototype);
  25851. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  25852. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  25853. MeshToonMaterial.prototype.copy = function (source) {
  25854. Material.prototype.copy.call(this, source);
  25855. this.color.copy(source.color);
  25856. this.map = source.map;
  25857. this.gradientMap = source.gradientMap;
  25858. this.lightMap = source.lightMap;
  25859. this.lightMapIntensity = source.lightMapIntensity;
  25860. this.aoMap = source.aoMap;
  25861. this.aoMapIntensity = source.aoMapIntensity;
  25862. this.emissive.copy(source.emissive);
  25863. this.emissiveMap = source.emissiveMap;
  25864. this.emissiveIntensity = source.emissiveIntensity;
  25865. this.bumpMap = source.bumpMap;
  25866. this.bumpScale = source.bumpScale;
  25867. this.normalMap = source.normalMap;
  25868. this.normalMapType = source.normalMapType;
  25869. this.normalScale.copy(source.normalScale);
  25870. this.displacementMap = source.displacementMap;
  25871. this.displacementScale = source.displacementScale;
  25872. this.displacementBias = source.displacementBias;
  25873. this.alphaMap = source.alphaMap;
  25874. this.wireframe = source.wireframe;
  25875. this.wireframeLinewidth = source.wireframeLinewidth;
  25876. this.wireframeLinecap = source.wireframeLinecap;
  25877. this.wireframeLinejoin = source.wireframeLinejoin;
  25878. this.skinning = source.skinning;
  25879. this.morphTargets = source.morphTargets;
  25880. this.morphNormals = source.morphNormals;
  25881. return this;
  25882. };
  25883. /**
  25884. * parameters = {
  25885. * opacity: <float>,
  25886. *
  25887. * bumpMap: new THREE.Texture( <Image> ),
  25888. * bumpScale: <float>,
  25889. *
  25890. * normalMap: new THREE.Texture( <Image> ),
  25891. * normalMapType: THREE.TangentSpaceNormalMap,
  25892. * normalScale: <Vector2>,
  25893. *
  25894. * displacementMap: new THREE.Texture( <Image> ),
  25895. * displacementScale: <float>,
  25896. * displacementBias: <float>,
  25897. *
  25898. * wireframe: <boolean>,
  25899. * wireframeLinewidth: <float>
  25900. *
  25901. * skinning: <bool>,
  25902. * morphTargets: <bool>,
  25903. * morphNormals: <bool>
  25904. * }
  25905. */
  25906. function MeshNormalMaterial(parameters) {
  25907. Material.call(this);
  25908. this.type = 'MeshNormalMaterial';
  25909. this.bumpMap = null;
  25910. this.bumpScale = 1;
  25911. this.normalMap = null;
  25912. this.normalMapType = TangentSpaceNormalMap;
  25913. this.normalScale = new Vector2(1, 1);
  25914. this.displacementMap = null;
  25915. this.displacementScale = 1;
  25916. this.displacementBias = 0;
  25917. this.wireframe = false;
  25918. this.wireframeLinewidth = 1;
  25919. this.fog = false;
  25920. this.skinning = false;
  25921. this.morphTargets = false;
  25922. this.morphNormals = false;
  25923. this.setValues(parameters);
  25924. }
  25925. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  25926. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  25927. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  25928. MeshNormalMaterial.prototype.copy = function (source) {
  25929. Material.prototype.copy.call(this, source);
  25930. this.bumpMap = source.bumpMap;
  25931. this.bumpScale = source.bumpScale;
  25932. this.normalMap = source.normalMap;
  25933. this.normalMapType = source.normalMapType;
  25934. this.normalScale.copy(source.normalScale);
  25935. this.displacementMap = source.displacementMap;
  25936. this.displacementScale = source.displacementScale;
  25937. this.displacementBias = source.displacementBias;
  25938. this.wireframe = source.wireframe;
  25939. this.wireframeLinewidth = source.wireframeLinewidth;
  25940. this.skinning = source.skinning;
  25941. this.morphTargets = source.morphTargets;
  25942. this.morphNormals = source.morphNormals;
  25943. return this;
  25944. };
  25945. /**
  25946. * parameters = {
  25947. * color: <hex>,
  25948. * opacity: <float>,
  25949. *
  25950. * map: new THREE.Texture( <Image> ),
  25951. *
  25952. * lightMap: new THREE.Texture( <Image> ),
  25953. * lightMapIntensity: <float>
  25954. *
  25955. * aoMap: new THREE.Texture( <Image> ),
  25956. * aoMapIntensity: <float>
  25957. *
  25958. * emissive: <hex>,
  25959. * emissiveIntensity: <float>
  25960. * emissiveMap: new THREE.Texture( <Image> ),
  25961. *
  25962. * specularMap: new THREE.Texture( <Image> ),
  25963. *
  25964. * alphaMap: new THREE.Texture( <Image> ),
  25965. *
  25966. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25967. * combine: THREE.Multiply,
  25968. * reflectivity: <float>,
  25969. * refractionRatio: <float>,
  25970. *
  25971. * wireframe: <boolean>,
  25972. * wireframeLinewidth: <float>,
  25973. *
  25974. * skinning: <bool>,
  25975. * morphTargets: <bool>,
  25976. * morphNormals: <bool>
  25977. * }
  25978. */
  25979. function MeshLambertMaterial(parameters) {
  25980. Material.call(this);
  25981. this.type = 'MeshLambertMaterial';
  25982. this.color = new Color(0xffffff); // diffuse
  25983. this.map = null;
  25984. this.lightMap = null;
  25985. this.lightMapIntensity = 1.0;
  25986. this.aoMap = null;
  25987. this.aoMapIntensity = 1.0;
  25988. this.emissive = new Color(0x000000);
  25989. this.emissiveIntensity = 1.0;
  25990. this.emissiveMap = null;
  25991. this.specularMap = null;
  25992. this.alphaMap = null;
  25993. this.envMap = null;
  25994. this.combine = MultiplyOperation;
  25995. this.reflectivity = 1;
  25996. this.refractionRatio = 0.98;
  25997. this.wireframe = false;
  25998. this.wireframeLinewidth = 1;
  25999. this.wireframeLinecap = 'round';
  26000. this.wireframeLinejoin = 'round';
  26001. this.skinning = false;
  26002. this.morphTargets = false;
  26003. this.morphNormals = false;
  26004. this.setValues(parameters);
  26005. }
  26006. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  26007. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  26008. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  26009. MeshLambertMaterial.prototype.copy = function (source) {
  26010. Material.prototype.copy.call(this, source);
  26011. this.color.copy(source.color);
  26012. this.map = source.map;
  26013. this.lightMap = source.lightMap;
  26014. this.lightMapIntensity = source.lightMapIntensity;
  26015. this.aoMap = source.aoMap;
  26016. this.aoMapIntensity = source.aoMapIntensity;
  26017. this.emissive.copy(source.emissive);
  26018. this.emissiveMap = source.emissiveMap;
  26019. this.emissiveIntensity = source.emissiveIntensity;
  26020. this.specularMap = source.specularMap;
  26021. this.alphaMap = source.alphaMap;
  26022. this.envMap = source.envMap;
  26023. this.combine = source.combine;
  26024. this.reflectivity = source.reflectivity;
  26025. this.refractionRatio = source.refractionRatio;
  26026. this.wireframe = source.wireframe;
  26027. this.wireframeLinewidth = source.wireframeLinewidth;
  26028. this.wireframeLinecap = source.wireframeLinecap;
  26029. this.wireframeLinejoin = source.wireframeLinejoin;
  26030. this.skinning = source.skinning;
  26031. this.morphTargets = source.morphTargets;
  26032. this.morphNormals = source.morphNormals;
  26033. return this;
  26034. };
  26035. /**
  26036. * parameters = {
  26037. * color: <hex>,
  26038. * opacity: <float>,
  26039. *
  26040. * matcap: new THREE.Texture( <Image> ),
  26041. *
  26042. * map: new THREE.Texture( <Image> ),
  26043. *
  26044. * bumpMap: new THREE.Texture( <Image> ),
  26045. * bumpScale: <float>,
  26046. *
  26047. * normalMap: new THREE.Texture( <Image> ),
  26048. * normalMapType: THREE.TangentSpaceNormalMap,
  26049. * normalScale: <Vector2>,
  26050. *
  26051. * displacementMap: new THREE.Texture( <Image> ),
  26052. * displacementScale: <float>,
  26053. * displacementBias: <float>,
  26054. *
  26055. * alphaMap: new THREE.Texture( <Image> ),
  26056. *
  26057. * skinning: <bool>,
  26058. * morphTargets: <bool>,
  26059. * morphNormals: <bool>
  26060. * }
  26061. */
  26062. function MeshMatcapMaterial(parameters) {
  26063. Material.call(this);
  26064. this.defines = {
  26065. 'MATCAP': ''
  26066. };
  26067. this.type = 'MeshMatcapMaterial';
  26068. this.color = new Color(0xffffff); // diffuse
  26069. this.matcap = null;
  26070. this.map = null;
  26071. this.bumpMap = null;
  26072. this.bumpScale = 1;
  26073. this.normalMap = null;
  26074. this.normalMapType = TangentSpaceNormalMap;
  26075. this.normalScale = new Vector2(1, 1);
  26076. this.displacementMap = null;
  26077. this.displacementScale = 1;
  26078. this.displacementBias = 0;
  26079. this.alphaMap = null;
  26080. this.skinning = false;
  26081. this.morphTargets = false;
  26082. this.morphNormals = false;
  26083. this.setValues(parameters);
  26084. }
  26085. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  26086. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  26087. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  26088. MeshMatcapMaterial.prototype.copy = function (source) {
  26089. Material.prototype.copy.call(this, source);
  26090. this.defines = {
  26091. 'MATCAP': ''
  26092. };
  26093. this.color.copy(source.color);
  26094. this.matcap = source.matcap;
  26095. this.map = source.map;
  26096. this.bumpMap = source.bumpMap;
  26097. this.bumpScale = source.bumpScale;
  26098. this.normalMap = source.normalMap;
  26099. this.normalMapType = source.normalMapType;
  26100. this.normalScale.copy(source.normalScale);
  26101. this.displacementMap = source.displacementMap;
  26102. this.displacementScale = source.displacementScale;
  26103. this.displacementBias = source.displacementBias;
  26104. this.alphaMap = source.alphaMap;
  26105. this.skinning = source.skinning;
  26106. this.morphTargets = source.morphTargets;
  26107. this.morphNormals = source.morphNormals;
  26108. return this;
  26109. };
  26110. /**
  26111. * parameters = {
  26112. * color: <hex>,
  26113. * opacity: <float>,
  26114. *
  26115. * linewidth: <float>,
  26116. *
  26117. * scale: <float>,
  26118. * dashSize: <float>,
  26119. * gapSize: <float>
  26120. * }
  26121. */
  26122. function LineDashedMaterial(parameters) {
  26123. LineBasicMaterial.call(this);
  26124. this.type = 'LineDashedMaterial';
  26125. this.scale = 1;
  26126. this.dashSize = 3;
  26127. this.gapSize = 1;
  26128. this.setValues(parameters);
  26129. }
  26130. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  26131. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  26132. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  26133. LineDashedMaterial.prototype.copy = function (source) {
  26134. LineBasicMaterial.prototype.copy.call(this, source);
  26135. this.scale = source.scale;
  26136. this.dashSize = source.dashSize;
  26137. this.gapSize = source.gapSize;
  26138. return this;
  26139. };
  26140. var Materials = /*#__PURE__*/Object.freeze({
  26141. __proto__: null,
  26142. ShadowMaterial: ShadowMaterial,
  26143. SpriteMaterial: SpriteMaterial,
  26144. RawShaderMaterial: RawShaderMaterial,
  26145. ShaderMaterial: ShaderMaterial,
  26146. PointsMaterial: PointsMaterial,
  26147. MeshPhysicalMaterial: MeshPhysicalMaterial,
  26148. MeshStandardMaterial: MeshStandardMaterial,
  26149. MeshPhongMaterial: MeshPhongMaterial,
  26150. MeshToonMaterial: MeshToonMaterial,
  26151. MeshNormalMaterial: MeshNormalMaterial,
  26152. MeshLambertMaterial: MeshLambertMaterial,
  26153. MeshDepthMaterial: MeshDepthMaterial,
  26154. MeshDistanceMaterial: MeshDistanceMaterial,
  26155. MeshBasicMaterial: MeshBasicMaterial,
  26156. MeshMatcapMaterial: MeshMatcapMaterial,
  26157. LineDashedMaterial: LineDashedMaterial,
  26158. LineBasicMaterial: LineBasicMaterial,
  26159. Material: Material
  26160. });
  26161. var AnimationUtils = {
  26162. // same as Array.prototype.slice, but also works on typed arrays
  26163. arraySlice: function arraySlice(array, from, to) {
  26164. if (AnimationUtils.isTypedArray(array)) {
  26165. // in ios9 array.subarray(from, undefined) will return empty array
  26166. // but array.subarray(from) or array.subarray(from, len) is correct
  26167. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  26168. }
  26169. return array.slice(from, to);
  26170. },
  26171. // converts an array to a specific type
  26172. convertArray: function convertArray(array, type, forceClone) {
  26173. if (!array || // let 'undefined' and 'null' pass
  26174. !forceClone && array.constructor === type) return array;
  26175. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  26176. return new type(array); // create typed array
  26177. }
  26178. return Array.prototype.slice.call(array); // create Array
  26179. },
  26180. isTypedArray: function isTypedArray(object) {
  26181. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  26182. },
  26183. // returns an array by which times and values can be sorted
  26184. getKeyframeOrder: function getKeyframeOrder(times) {
  26185. function compareTime(i, j) {
  26186. return times[i] - times[j];
  26187. }
  26188. var n = times.length;
  26189. var result = new Array(n);
  26190. for (var i = 0; i !== n; ++i) {
  26191. result[i] = i;
  26192. }
  26193. result.sort(compareTime);
  26194. return result;
  26195. },
  26196. // uses the array previously returned by 'getKeyframeOrder' to sort data
  26197. sortedArray: function sortedArray(values, stride, order) {
  26198. var nValues = values.length;
  26199. var result = new values.constructor(nValues);
  26200. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  26201. var srcOffset = order[i] * stride;
  26202. for (var j = 0; j !== stride; ++j) {
  26203. result[dstOffset++] = values[srcOffset + j];
  26204. }
  26205. }
  26206. return result;
  26207. },
  26208. // function for parsing AOS keyframe formats
  26209. flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  26210. var i = 1,
  26211. key = jsonKeys[0];
  26212. while (key !== undefined && key[valuePropertyName] === undefined) {
  26213. key = jsonKeys[i++];
  26214. }
  26215. if (key === undefined) return; // no data
  26216. var value = key[valuePropertyName];
  26217. if (value === undefined) return; // no data
  26218. if (Array.isArray(value)) {
  26219. do {
  26220. value = key[valuePropertyName];
  26221. if (value !== undefined) {
  26222. times.push(key.time);
  26223. values.push.apply(values, value); // push all elements
  26224. }
  26225. key = jsonKeys[i++];
  26226. } while (key !== undefined);
  26227. } else if (value.toArray !== undefined) {
  26228. // ...assume THREE.Math-ish
  26229. do {
  26230. value = key[valuePropertyName];
  26231. if (value !== undefined) {
  26232. times.push(key.time);
  26233. value.toArray(values, values.length);
  26234. }
  26235. key = jsonKeys[i++];
  26236. } while (key !== undefined);
  26237. } else {
  26238. // otherwise push as-is
  26239. do {
  26240. value = key[valuePropertyName];
  26241. if (value !== undefined) {
  26242. times.push(key.time);
  26243. values.push(value);
  26244. }
  26245. key = jsonKeys[i++];
  26246. } while (key !== undefined);
  26247. }
  26248. },
  26249. subclip: function subclip(sourceClip, name, startFrame, endFrame, fps) {
  26250. if (fps === void 0) {
  26251. fps = 30;
  26252. }
  26253. var clip = sourceClip.clone();
  26254. clip.name = name;
  26255. var tracks = [];
  26256. for (var i = 0; i < clip.tracks.length; ++i) {
  26257. var track = clip.tracks[i];
  26258. var valueSize = track.getValueSize();
  26259. var times = [];
  26260. var values = [];
  26261. for (var j = 0; j < track.times.length; ++j) {
  26262. var frame = track.times[j] * fps;
  26263. if (frame < startFrame || frame >= endFrame) continue;
  26264. times.push(track.times[j]);
  26265. for (var k = 0; k < valueSize; ++k) {
  26266. values.push(track.values[j * valueSize + k]);
  26267. }
  26268. }
  26269. if (times.length === 0) continue;
  26270. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  26271. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  26272. tracks.push(track);
  26273. }
  26274. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  26275. var minStartTime = Infinity;
  26276. for (var _i = 0; _i < clip.tracks.length; ++_i) {
  26277. if (minStartTime > clip.tracks[_i].times[0]) {
  26278. minStartTime = clip.tracks[_i].times[0];
  26279. }
  26280. } // shift all tracks such that clip begins at t=0
  26281. for (var _i2 = 0; _i2 < clip.tracks.length; ++_i2) {
  26282. clip.tracks[_i2].shift(-1 * minStartTime);
  26283. }
  26284. clip.resetDuration();
  26285. return clip;
  26286. },
  26287. makeClipAdditive: function makeClipAdditive(targetClip, referenceFrame, referenceClip, fps) {
  26288. if (referenceFrame === void 0) {
  26289. referenceFrame = 0;
  26290. }
  26291. if (referenceClip === void 0) {
  26292. referenceClip = targetClip;
  26293. }
  26294. if (fps === void 0) {
  26295. fps = 30;
  26296. }
  26297. if (fps <= 0) fps = 30;
  26298. var numTracks = referenceClip.tracks.length;
  26299. var referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  26300. var _loop = function _loop(i) {
  26301. var referenceTrack = referenceClip.tracks[i];
  26302. var referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  26303. if (referenceTrackType === 'bool' || referenceTrackType === 'string') return "continue"; // Find the track in the target clip whose name and type matches the reference track
  26304. var targetTrack = targetClip.tracks.find(function (track) {
  26305. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  26306. });
  26307. if (targetTrack === undefined) return "continue";
  26308. var referenceOffset = 0;
  26309. var referenceValueSize = referenceTrack.getValueSize();
  26310. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  26311. referenceOffset = referenceValueSize / 3;
  26312. }
  26313. var targetOffset = 0;
  26314. var targetValueSize = targetTrack.getValueSize();
  26315. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  26316. targetOffset = targetValueSize / 3;
  26317. }
  26318. var lastIndex = referenceTrack.times.length - 1;
  26319. var referenceValue = void 0; // Find the value to subtract out of the track
  26320. if (referenceTime <= referenceTrack.times[0]) {
  26321. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  26322. var startIndex = referenceOffset;
  26323. var endIndex = referenceValueSize - referenceOffset;
  26324. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  26325. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  26326. // Reference frame is after the last keyframe, so just use the last keyframe
  26327. var _startIndex = lastIndex * referenceValueSize + referenceOffset;
  26328. var _endIndex = _startIndex + referenceValueSize - referenceOffset;
  26329. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, _startIndex, _endIndex);
  26330. } else {
  26331. // Interpolate to the reference value
  26332. var interpolant = referenceTrack.createInterpolant();
  26333. var _startIndex2 = referenceOffset;
  26334. var _endIndex2 = referenceValueSize - referenceOffset;
  26335. interpolant.evaluate(referenceTime);
  26336. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, _startIndex2, _endIndex2);
  26337. } // Conjugate the quaternion
  26338. if (referenceTrackType === 'quaternion') {
  26339. var referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  26340. referenceQuat.toArray(referenceValue);
  26341. } // Subtract the reference value from all of the track values
  26342. var numTimes = targetTrack.times.length;
  26343. for (var j = 0; j < numTimes; ++j) {
  26344. var valueStart = j * targetValueSize + targetOffset;
  26345. if (referenceTrackType === 'quaternion') {
  26346. // Multiply the conjugate for quaternion track types
  26347. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  26348. } else {
  26349. var valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  26350. for (var k = 0; k < valueEnd; ++k) {
  26351. targetTrack.values[valueStart + k] -= referenceValue[k];
  26352. }
  26353. }
  26354. }
  26355. };
  26356. for (var i = 0; i < numTracks; ++i) {
  26357. var _ret = _loop(i);
  26358. if (_ret === "continue") continue;
  26359. }
  26360. targetClip.blendMode = AdditiveAnimationBlendMode;
  26361. return targetClip;
  26362. }
  26363. };
  26364. /**
  26365. * Abstract base class of interpolants over parametric samples.
  26366. *
  26367. * The parameter domain is one dimensional, typically the time or a path
  26368. * along a curve defined by the data.
  26369. *
  26370. * The sample values can have any dimensionality and derived classes may
  26371. * apply special interpretations to the data.
  26372. *
  26373. * This class provides the interval seek in a Template Method, deferring
  26374. * the actual interpolation to derived classes.
  26375. *
  26376. * Time complexity is O(1) for linear access crossing at most two points
  26377. * and O(log N) for random access, where N is the number of positions.
  26378. *
  26379. * References:
  26380. *
  26381. * http://www.oodesign.com/template-method-pattern.html
  26382. *
  26383. */
  26384. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26385. this.parameterPositions = parameterPositions;
  26386. this._cachedIndex = 0;
  26387. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  26388. this.sampleValues = sampleValues;
  26389. this.valueSize = sampleSize;
  26390. }
  26391. Object.assign(Interpolant.prototype, {
  26392. evaluate: function evaluate(t) {
  26393. var pp = this.parameterPositions;
  26394. var i1 = this._cachedIndex,
  26395. t1 = pp[i1],
  26396. t0 = pp[i1 - 1];
  26397. validate_interval: {
  26398. seek: {
  26399. var right;
  26400. linear_scan: {
  26401. //- See http://jsperf.com/comparison-to-undefined/3
  26402. //- slower code:
  26403. //-
  26404. //- if ( t >= t1 || t1 === undefined ) {
  26405. forward_scan: if (!(t < t1)) {
  26406. for (var giveUpAt = i1 + 2;;) {
  26407. if (t1 === undefined) {
  26408. if (t < t0) break forward_scan; // after end
  26409. i1 = pp.length;
  26410. this._cachedIndex = i1;
  26411. return this.afterEnd_(i1 - 1, t, t0);
  26412. }
  26413. if (i1 === giveUpAt) break; // this loop
  26414. t0 = t1;
  26415. t1 = pp[++i1];
  26416. if (t < t1) {
  26417. // we have arrived at the sought interval
  26418. break seek;
  26419. }
  26420. } // prepare binary search on the right side of the index
  26421. right = pp.length;
  26422. break linear_scan;
  26423. } //- slower code:
  26424. //- if ( t < t0 || t0 === undefined ) {
  26425. if (!(t >= t0)) {
  26426. // looping?
  26427. var t1global = pp[1];
  26428. if (t < t1global) {
  26429. i1 = 2; // + 1, using the scan for the details
  26430. t0 = t1global;
  26431. } // linear reverse scan
  26432. for (var _giveUpAt = i1 - 2;;) {
  26433. if (t0 === undefined) {
  26434. // before start
  26435. this._cachedIndex = 0;
  26436. return this.beforeStart_(0, t, t1);
  26437. }
  26438. if (i1 === _giveUpAt) break; // this loop
  26439. t1 = t0;
  26440. t0 = pp[--i1 - 1];
  26441. if (t >= t0) {
  26442. // we have arrived at the sought interval
  26443. break seek;
  26444. }
  26445. } // prepare binary search on the left side of the index
  26446. right = i1;
  26447. i1 = 0;
  26448. break linear_scan;
  26449. } // the interval is valid
  26450. break validate_interval;
  26451. } // linear scan
  26452. // binary search
  26453. while (i1 < right) {
  26454. var mid = i1 + right >>> 1;
  26455. if (t < pp[mid]) {
  26456. right = mid;
  26457. } else {
  26458. i1 = mid + 1;
  26459. }
  26460. }
  26461. t1 = pp[i1];
  26462. t0 = pp[i1 - 1]; // check boundary cases, again
  26463. if (t0 === undefined) {
  26464. this._cachedIndex = 0;
  26465. return this.beforeStart_(0, t, t1);
  26466. }
  26467. if (t1 === undefined) {
  26468. i1 = pp.length;
  26469. this._cachedIndex = i1;
  26470. return this.afterEnd_(i1 - 1, t0, t);
  26471. }
  26472. } // seek
  26473. this._cachedIndex = i1;
  26474. this.intervalChanged_(i1, t0, t1);
  26475. } // validate_interval
  26476. return this.interpolate_(i1, t0, t, t1);
  26477. },
  26478. settings: null,
  26479. // optional, subclass-specific settings structure
  26480. // Note: The indirection allows central control of many interpolants.
  26481. // --- Protected interface
  26482. DefaultSettings_: {},
  26483. getSettings_: function getSettings_() {
  26484. return this.settings || this.DefaultSettings_;
  26485. },
  26486. copySampleValue_: function copySampleValue_(index) {
  26487. // copies a sample value to the result buffer
  26488. var result = this.resultBuffer,
  26489. values = this.sampleValues,
  26490. stride = this.valueSize,
  26491. offset = index * stride;
  26492. for (var i = 0; i !== stride; ++i) {
  26493. result[i] = values[offset + i];
  26494. }
  26495. return result;
  26496. },
  26497. // Template methods for derived classes:
  26498. interpolate_: function interpolate_()
  26499. /* i1, t0, t, t1 */
  26500. {
  26501. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  26502. },
  26503. intervalChanged_: function intervalChanged_()
  26504. /* i1, t0, t1 */
  26505. {// empty
  26506. }
  26507. }); // DECLARE ALIAS AFTER assign prototype
  26508. Object.assign(Interpolant.prototype, {
  26509. //( 0, t, t0 ), returns this.resultBuffer
  26510. beforeStart_: Interpolant.prototype.copySampleValue_,
  26511. //( N-1, tN-1, t ), returns this.resultBuffer
  26512. afterEnd_: Interpolant.prototype.copySampleValue_
  26513. });
  26514. /**
  26515. * Fast and simple cubic spline interpolant.
  26516. *
  26517. * It was derived from a Hermitian construction setting the first derivative
  26518. * at each sample position to the linear slope between neighboring positions
  26519. * over their parameter interval.
  26520. */
  26521. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26522. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26523. this._weightPrev = -0;
  26524. this._offsetPrev = -0;
  26525. this._weightNext = -0;
  26526. this._offsetNext = -0;
  26527. }
  26528. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26529. constructor: CubicInterpolant,
  26530. DefaultSettings_: {
  26531. endingStart: ZeroCurvatureEnding,
  26532. endingEnd: ZeroCurvatureEnding
  26533. },
  26534. intervalChanged_: function intervalChanged_(i1, t0, t1) {
  26535. var pp = this.parameterPositions;
  26536. var iPrev = i1 - 2,
  26537. iNext = i1 + 1,
  26538. tPrev = pp[iPrev],
  26539. tNext = pp[iNext];
  26540. if (tPrev === undefined) {
  26541. switch (this.getSettings_().endingStart) {
  26542. case ZeroSlopeEnding:
  26543. // f'(t0) = 0
  26544. iPrev = i1;
  26545. tPrev = 2 * t0 - t1;
  26546. break;
  26547. case WrapAroundEnding:
  26548. // use the other end of the curve
  26549. iPrev = pp.length - 2;
  26550. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  26551. break;
  26552. default:
  26553. // ZeroCurvatureEnding
  26554. // f''(t0) = 0 a.k.a. Natural Spline
  26555. iPrev = i1;
  26556. tPrev = t1;
  26557. }
  26558. }
  26559. if (tNext === undefined) {
  26560. switch (this.getSettings_().endingEnd) {
  26561. case ZeroSlopeEnding:
  26562. // f'(tN) = 0
  26563. iNext = i1;
  26564. tNext = 2 * t1 - t0;
  26565. break;
  26566. case WrapAroundEnding:
  26567. // use the other end of the curve
  26568. iNext = 1;
  26569. tNext = t1 + pp[1] - pp[0];
  26570. break;
  26571. default:
  26572. // ZeroCurvatureEnding
  26573. // f''(tN) = 0, a.k.a. Natural Spline
  26574. iNext = i1 - 1;
  26575. tNext = t0;
  26576. }
  26577. }
  26578. var halfDt = (t1 - t0) * 0.5,
  26579. stride = this.valueSize;
  26580. this._weightPrev = halfDt / (t0 - tPrev);
  26581. this._weightNext = halfDt / (tNext - t1);
  26582. this._offsetPrev = iPrev * stride;
  26583. this._offsetNext = iNext * stride;
  26584. },
  26585. interpolate_: function interpolate_(i1, t0, t, t1) {
  26586. var result = this.resultBuffer,
  26587. values = this.sampleValues,
  26588. stride = this.valueSize,
  26589. o1 = i1 * stride,
  26590. o0 = o1 - stride,
  26591. oP = this._offsetPrev,
  26592. oN = this._offsetNext,
  26593. wP = this._weightPrev,
  26594. wN = this._weightNext,
  26595. p = (t - t0) / (t1 - t0),
  26596. pp = p * p,
  26597. ppp = pp * p; // evaluate polynomials
  26598. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  26599. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  26600. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  26601. var sN = wN * ppp - wN * pp; // combine data linearly
  26602. for (var i = 0; i !== stride; ++i) {
  26603. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  26604. }
  26605. return result;
  26606. }
  26607. });
  26608. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26609. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26610. }
  26611. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26612. constructor: LinearInterpolant,
  26613. interpolate_: function interpolate_(i1, t0, t, t1) {
  26614. var result = this.resultBuffer,
  26615. values = this.sampleValues,
  26616. stride = this.valueSize,
  26617. offset1 = i1 * stride,
  26618. offset0 = offset1 - stride,
  26619. weight1 = (t - t0) / (t1 - t0),
  26620. weight0 = 1 - weight1;
  26621. for (var i = 0; i !== stride; ++i) {
  26622. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  26623. }
  26624. return result;
  26625. }
  26626. });
  26627. /**
  26628. *
  26629. * Interpolant that evaluates to the sample value at the position preceeding
  26630. * the parameter.
  26631. */
  26632. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26633. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26634. }
  26635. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26636. constructor: DiscreteInterpolant,
  26637. interpolate_: function interpolate_(i1
  26638. /*, t0, t, t1 */
  26639. ) {
  26640. return this.copySampleValue_(i1 - 1);
  26641. }
  26642. });
  26643. function KeyframeTrack(name, times, values, interpolation) {
  26644. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  26645. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  26646. this.name = name;
  26647. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  26648. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  26649. this.setInterpolation(interpolation || this.DefaultInterpolation);
  26650. } // Static methods
  26651. Object.assign(KeyframeTrack, {
  26652. // Serialization (in static context, because of constructor invocation
  26653. // and automatic invocation of .toJSON):
  26654. toJSON: function toJSON(track) {
  26655. var trackType = track.constructor;
  26656. var json; // derived classes can define a static toJSON method
  26657. if (trackType.toJSON !== undefined) {
  26658. json = trackType.toJSON(track);
  26659. } else {
  26660. // by default, we assume the data can be serialized as-is
  26661. json = {
  26662. 'name': track.name,
  26663. 'times': AnimationUtils.convertArray(track.times, Array),
  26664. 'values': AnimationUtils.convertArray(track.values, Array)
  26665. };
  26666. var interpolation = track.getInterpolation();
  26667. if (interpolation !== track.DefaultInterpolation) {
  26668. json.interpolation = interpolation;
  26669. }
  26670. }
  26671. json.type = track.ValueTypeName; // mandatory
  26672. return json;
  26673. }
  26674. });
  26675. Object.assign(KeyframeTrack.prototype, {
  26676. constructor: KeyframeTrack,
  26677. TimeBufferType: Float32Array,
  26678. ValueBufferType: Float32Array,
  26679. DefaultInterpolation: InterpolateLinear,
  26680. InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {
  26681. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  26682. },
  26683. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  26684. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  26685. },
  26686. InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {
  26687. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  26688. },
  26689. setInterpolation: function setInterpolation(interpolation) {
  26690. var factoryMethod;
  26691. switch (interpolation) {
  26692. case InterpolateDiscrete:
  26693. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  26694. break;
  26695. case InterpolateLinear:
  26696. factoryMethod = this.InterpolantFactoryMethodLinear;
  26697. break;
  26698. case InterpolateSmooth:
  26699. factoryMethod = this.InterpolantFactoryMethodSmooth;
  26700. break;
  26701. }
  26702. if (factoryMethod === undefined) {
  26703. var message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  26704. if (this.createInterpolant === undefined) {
  26705. // fall back to default, unless the default itself is messed up
  26706. if (interpolation !== this.DefaultInterpolation) {
  26707. this.setInterpolation(this.DefaultInterpolation);
  26708. } else {
  26709. throw new Error(message); // fatal, in this case
  26710. }
  26711. }
  26712. console.warn('THREE.KeyframeTrack:', message);
  26713. return this;
  26714. }
  26715. this.createInterpolant = factoryMethod;
  26716. return this;
  26717. },
  26718. getInterpolation: function getInterpolation() {
  26719. switch (this.createInterpolant) {
  26720. case this.InterpolantFactoryMethodDiscrete:
  26721. return InterpolateDiscrete;
  26722. case this.InterpolantFactoryMethodLinear:
  26723. return InterpolateLinear;
  26724. case this.InterpolantFactoryMethodSmooth:
  26725. return InterpolateSmooth;
  26726. }
  26727. },
  26728. getValueSize: function getValueSize() {
  26729. return this.values.length / this.times.length;
  26730. },
  26731. // move all keyframes either forwards or backwards in time
  26732. shift: function shift(timeOffset) {
  26733. if (timeOffset !== 0.0) {
  26734. var times = this.times;
  26735. for (var i = 0, n = times.length; i !== n; ++i) {
  26736. times[i] += timeOffset;
  26737. }
  26738. }
  26739. return this;
  26740. },
  26741. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  26742. scale: function scale(timeScale) {
  26743. if (timeScale !== 1.0) {
  26744. var times = this.times;
  26745. for (var i = 0, n = times.length; i !== n; ++i) {
  26746. times[i] *= timeScale;
  26747. }
  26748. }
  26749. return this;
  26750. },
  26751. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  26752. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  26753. trim: function trim(startTime, endTime) {
  26754. var times = this.times,
  26755. nKeys = times.length;
  26756. var from = 0,
  26757. to = nKeys - 1;
  26758. while (from !== nKeys && times[from] < startTime) {
  26759. ++from;
  26760. }
  26761. while (to !== -1 && times[to] > endTime) {
  26762. --to;
  26763. }
  26764. ++to; // inclusive -> exclusive bound
  26765. if (from !== 0 || to !== nKeys) {
  26766. // empty tracks are forbidden, so keep at least one keyframe
  26767. if (from >= to) {
  26768. to = Math.max(to, 1);
  26769. from = to - 1;
  26770. }
  26771. var stride = this.getValueSize();
  26772. this.times = AnimationUtils.arraySlice(times, from, to);
  26773. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  26774. }
  26775. return this;
  26776. },
  26777. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  26778. validate: function validate() {
  26779. var valid = true;
  26780. var valueSize = this.getValueSize();
  26781. if (valueSize - Math.floor(valueSize) !== 0) {
  26782. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  26783. valid = false;
  26784. }
  26785. var times = this.times,
  26786. values = this.values,
  26787. nKeys = times.length;
  26788. if (nKeys === 0) {
  26789. console.error('THREE.KeyframeTrack: Track is empty.', this);
  26790. valid = false;
  26791. }
  26792. var prevTime = null;
  26793. for (var i = 0; i !== nKeys; i++) {
  26794. var currTime = times[i];
  26795. if (typeof currTime === 'number' && isNaN(currTime)) {
  26796. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  26797. valid = false;
  26798. break;
  26799. }
  26800. if (prevTime !== null && prevTime > currTime) {
  26801. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  26802. valid = false;
  26803. break;
  26804. }
  26805. prevTime = currTime;
  26806. }
  26807. if (values !== undefined) {
  26808. if (AnimationUtils.isTypedArray(values)) {
  26809. for (var _i = 0, n = values.length; _i !== n; ++_i) {
  26810. var value = values[_i];
  26811. if (isNaN(value)) {
  26812. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, _i, value);
  26813. valid = false;
  26814. break;
  26815. }
  26816. }
  26817. }
  26818. }
  26819. return valid;
  26820. },
  26821. // removes equivalent sequential keys as common in morph target sequences
  26822. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  26823. optimize: function optimize() {
  26824. // times or values may be shared with other tracks, so overwriting is unsafe
  26825. var times = AnimationUtils.arraySlice(this.times),
  26826. values = AnimationUtils.arraySlice(this.values),
  26827. stride = this.getValueSize(),
  26828. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  26829. lastIndex = times.length - 1;
  26830. var writeIndex = 1;
  26831. for (var i = 1; i < lastIndex; ++i) {
  26832. var keep = false;
  26833. var time = times[i];
  26834. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  26835. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  26836. if (!smoothInterpolation) {
  26837. // remove unnecessary keyframes same as their neighbors
  26838. var offset = i * stride,
  26839. offsetP = offset - stride,
  26840. offsetN = offset + stride;
  26841. for (var j = 0; j !== stride; ++j) {
  26842. var value = values[offset + j];
  26843. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  26844. keep = true;
  26845. break;
  26846. }
  26847. }
  26848. } else {
  26849. keep = true;
  26850. }
  26851. } // in-place compaction
  26852. if (keep) {
  26853. if (i !== writeIndex) {
  26854. times[writeIndex] = times[i];
  26855. var readOffset = i * stride,
  26856. writeOffset = writeIndex * stride;
  26857. for (var _j = 0; _j !== stride; ++_j) {
  26858. values[writeOffset + _j] = values[readOffset + _j];
  26859. }
  26860. }
  26861. ++writeIndex;
  26862. }
  26863. } // flush last keyframe (compaction looks ahead)
  26864. if (lastIndex > 0) {
  26865. times[writeIndex] = times[lastIndex];
  26866. for (var _readOffset = lastIndex * stride, _writeOffset = writeIndex * stride, _j2 = 0; _j2 !== stride; ++_j2) {
  26867. values[_writeOffset + _j2] = values[_readOffset + _j2];
  26868. }
  26869. ++writeIndex;
  26870. }
  26871. if (writeIndex !== times.length) {
  26872. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  26873. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  26874. } else {
  26875. this.times = times;
  26876. this.values = values;
  26877. }
  26878. return this;
  26879. },
  26880. clone: function clone() {
  26881. var times = AnimationUtils.arraySlice(this.times, 0);
  26882. var values = AnimationUtils.arraySlice(this.values, 0);
  26883. var TypedKeyframeTrack = this.constructor;
  26884. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  26885. track.createInterpolant = this.createInterpolant;
  26886. return track;
  26887. }
  26888. });
  26889. /**
  26890. * A Track of Boolean keyframe values.
  26891. */
  26892. function BooleanKeyframeTrack(name, times, values) {
  26893. KeyframeTrack.call(this, name, times, values);
  26894. }
  26895. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26896. constructor: BooleanKeyframeTrack,
  26897. ValueTypeName: 'bool',
  26898. ValueBufferType: Array,
  26899. DefaultInterpolation: InterpolateDiscrete,
  26900. InterpolantFactoryMethodLinear: undefined,
  26901. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  26902. // representation of a single value and a custom interpolant that
  26903. // computes "firstValue ^ isOdd( index )".
  26904. });
  26905. /**
  26906. * A Track of keyframe values that represent color.
  26907. */
  26908. function ColorKeyframeTrack(name, times, values, interpolation) {
  26909. KeyframeTrack.call(this, name, times, values, interpolation);
  26910. }
  26911. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26912. constructor: ColorKeyframeTrack,
  26913. ValueTypeName: 'color' // ValueBufferType is inherited
  26914. // DefaultInterpolation is inherited
  26915. // Note: Very basic implementation and nothing special yet.
  26916. // However, this is the place for color space parameterization.
  26917. });
  26918. /**
  26919. * A Track of numeric keyframe values.
  26920. */
  26921. function NumberKeyframeTrack(name, times, values, interpolation) {
  26922. KeyframeTrack.call(this, name, times, values, interpolation);
  26923. }
  26924. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26925. constructor: NumberKeyframeTrack,
  26926. ValueTypeName: 'number' // ValueBufferType is inherited
  26927. // DefaultInterpolation is inherited
  26928. });
  26929. /**
  26930. * Spherical linear unit quaternion interpolant.
  26931. */
  26932. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26933. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26934. }
  26935. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26936. constructor: QuaternionLinearInterpolant,
  26937. interpolate_: function interpolate_(i1, t0, t, t1) {
  26938. var result = this.resultBuffer,
  26939. values = this.sampleValues,
  26940. stride = this.valueSize,
  26941. alpha = (t - t0) / (t1 - t0);
  26942. var offset = i1 * stride;
  26943. for (var end = offset + stride; offset !== end; offset += 4) {
  26944. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  26945. }
  26946. return result;
  26947. }
  26948. });
  26949. /**
  26950. * A Track of quaternion keyframe values.
  26951. */
  26952. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  26953. KeyframeTrack.call(this, name, times, values, interpolation);
  26954. }
  26955. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26956. constructor: QuaternionKeyframeTrack,
  26957. ValueTypeName: 'quaternion',
  26958. // ValueBufferType is inherited
  26959. DefaultInterpolation: InterpolateLinear,
  26960. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  26961. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  26962. },
  26963. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  26964. });
  26965. /**
  26966. * A Track that interpolates Strings
  26967. */
  26968. function StringKeyframeTrack(name, times, values, interpolation) {
  26969. KeyframeTrack.call(this, name, times, values, interpolation);
  26970. }
  26971. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26972. constructor: StringKeyframeTrack,
  26973. ValueTypeName: 'string',
  26974. ValueBufferType: Array,
  26975. DefaultInterpolation: InterpolateDiscrete,
  26976. InterpolantFactoryMethodLinear: undefined,
  26977. InterpolantFactoryMethodSmooth: undefined
  26978. });
  26979. /**
  26980. * A Track of vectored keyframe values.
  26981. */
  26982. function VectorKeyframeTrack(name, times, values, interpolation) {
  26983. KeyframeTrack.call(this, name, times, values, interpolation);
  26984. }
  26985. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26986. constructor: VectorKeyframeTrack,
  26987. ValueTypeName: 'vector' // ValueBufferType is inherited
  26988. // DefaultInterpolation is inherited
  26989. });
  26990. function AnimationClip(name, duration, tracks, blendMode) {
  26991. if (duration === void 0) {
  26992. duration = -1;
  26993. }
  26994. if (blendMode === void 0) {
  26995. blendMode = NormalAnimationBlendMode;
  26996. }
  26997. this.name = name;
  26998. this.tracks = tracks;
  26999. this.duration = duration;
  27000. this.blendMode = blendMode;
  27001. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  27002. if (this.duration < 0) {
  27003. this.resetDuration();
  27004. }
  27005. }
  27006. function getTrackTypeForValueTypeName(typeName) {
  27007. switch (typeName.toLowerCase()) {
  27008. case 'scalar':
  27009. case 'double':
  27010. case 'float':
  27011. case 'number':
  27012. case 'integer':
  27013. return NumberKeyframeTrack;
  27014. case 'vector':
  27015. case 'vector2':
  27016. case 'vector3':
  27017. case 'vector4':
  27018. return VectorKeyframeTrack;
  27019. case 'color':
  27020. return ColorKeyframeTrack;
  27021. case 'quaternion':
  27022. return QuaternionKeyframeTrack;
  27023. case 'bool':
  27024. case 'boolean':
  27025. return BooleanKeyframeTrack;
  27026. case 'string':
  27027. return StringKeyframeTrack;
  27028. }
  27029. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  27030. }
  27031. function parseKeyframeTrack(json) {
  27032. if (json.type === undefined) {
  27033. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  27034. }
  27035. var trackType = getTrackTypeForValueTypeName(json.type);
  27036. if (json.times === undefined) {
  27037. var times = [],
  27038. values = [];
  27039. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  27040. json.times = times;
  27041. json.values = values;
  27042. } // derived classes can define a static parse method
  27043. if (trackType.parse !== undefined) {
  27044. return trackType.parse(json);
  27045. } else {
  27046. // by default, we assume a constructor compatible with the base
  27047. return new trackType(json.name, json.times, json.values, json.interpolation);
  27048. }
  27049. }
  27050. Object.assign(AnimationClip, {
  27051. parse: function parse(json) {
  27052. var tracks = [],
  27053. jsonTracks = json.tracks,
  27054. frameTime = 1.0 / (json.fps || 1.0);
  27055. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  27056. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  27057. }
  27058. var clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  27059. clip.uuid = json.uuid;
  27060. return clip;
  27061. },
  27062. toJSON: function toJSON(clip) {
  27063. var tracks = [],
  27064. clipTracks = clip.tracks;
  27065. var json = {
  27066. 'name': clip.name,
  27067. 'duration': clip.duration,
  27068. 'tracks': tracks,
  27069. 'uuid': clip.uuid,
  27070. 'blendMode': clip.blendMode
  27071. };
  27072. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  27073. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  27074. }
  27075. return json;
  27076. },
  27077. CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  27078. var numMorphTargets = morphTargetSequence.length;
  27079. var tracks = [];
  27080. for (var i = 0; i < numMorphTargets; i++) {
  27081. var times = [];
  27082. var values = [];
  27083. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  27084. values.push(0, 1, 0);
  27085. var order = AnimationUtils.getKeyframeOrder(times);
  27086. times = AnimationUtils.sortedArray(times, 1, order);
  27087. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  27088. // last frame as well for perfect loop.
  27089. if (!noLoop && times[0] === 0) {
  27090. times.push(numMorphTargets);
  27091. values.push(values[0]);
  27092. }
  27093. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  27094. }
  27095. return new AnimationClip(name, -1, tracks);
  27096. },
  27097. findByName: function findByName(objectOrClipArray, name) {
  27098. var clipArray = objectOrClipArray;
  27099. if (!Array.isArray(objectOrClipArray)) {
  27100. var o = objectOrClipArray;
  27101. clipArray = o.geometry && o.geometry.animations || o.animations;
  27102. }
  27103. for (var i = 0; i < clipArray.length; i++) {
  27104. if (clipArray[i].name === name) {
  27105. return clipArray[i];
  27106. }
  27107. }
  27108. return null;
  27109. },
  27110. CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  27111. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  27112. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  27113. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  27114. // patterns like Walk_001, Walk_002, Run_001, Run_002
  27115. for (var i = 0, il = morphTargets.length; i < il; i++) {
  27116. var morphTarget = morphTargets[i];
  27117. var parts = morphTarget.name.match(pattern);
  27118. if (parts && parts.length > 1) {
  27119. var name = parts[1];
  27120. var animationMorphTargets = animationToMorphTargets[name];
  27121. if (!animationMorphTargets) {
  27122. animationToMorphTargets[name] = animationMorphTargets = [];
  27123. }
  27124. animationMorphTargets.push(morphTarget);
  27125. }
  27126. }
  27127. var clips = [];
  27128. for (var _name in animationToMorphTargets) {
  27129. clips.push(AnimationClip.CreateFromMorphTargetSequence(_name, animationToMorphTargets[_name], fps, noLoop));
  27130. }
  27131. return clips;
  27132. },
  27133. // parse the animation.hierarchy format
  27134. parseAnimation: function parseAnimation(animation, bones) {
  27135. if (!animation) {
  27136. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  27137. return null;
  27138. }
  27139. var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {
  27140. // only return track if there are actually keys.
  27141. if (animationKeys.length !== 0) {
  27142. var times = [];
  27143. var values = [];
  27144. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  27145. if (times.length !== 0) {
  27146. destTracks.push(new trackType(trackName, times, values));
  27147. }
  27148. }
  27149. };
  27150. var tracks = [];
  27151. var clipName = animation.name || 'default';
  27152. var fps = animation.fps || 30;
  27153. var blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  27154. var duration = animation.length || -1;
  27155. var hierarchyTracks = animation.hierarchy || [];
  27156. for (var h = 0; h < hierarchyTracks.length; h++) {
  27157. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  27158. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  27159. if (animationKeys[0].morphTargets) {
  27160. // figure out all morph targets used in this track
  27161. var morphTargetNames = {};
  27162. var k = void 0;
  27163. for (k = 0; k < animationKeys.length; k++) {
  27164. if (animationKeys[k].morphTargets) {
  27165. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  27166. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  27167. }
  27168. }
  27169. } // create a track for each morph target with all zero
  27170. // morphTargetInfluences except for the keys in which
  27171. // the morphTarget is named.
  27172. for (var morphTargetName in morphTargetNames) {
  27173. var times = [];
  27174. var values = [];
  27175. for (var _m = 0; _m !== animationKeys[k].morphTargets.length; ++_m) {
  27176. var animationKey = animationKeys[k];
  27177. times.push(animationKey.time);
  27178. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  27179. }
  27180. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  27181. }
  27182. duration = morphTargetNames.length * (fps || 1.0);
  27183. } else {
  27184. // ...assume skeletal animation
  27185. var boneName = '.bones[' + bones[h].name + ']';
  27186. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  27187. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  27188. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  27189. }
  27190. }
  27191. if (tracks.length === 0) {
  27192. return null;
  27193. }
  27194. var clip = new AnimationClip(clipName, duration, tracks, blendMode);
  27195. return clip;
  27196. }
  27197. });
  27198. Object.assign(AnimationClip.prototype, {
  27199. resetDuration: function resetDuration() {
  27200. var tracks = this.tracks;
  27201. var duration = 0;
  27202. for (var i = 0, n = tracks.length; i !== n; ++i) {
  27203. var track = this.tracks[i];
  27204. duration = Math.max(duration, track.times[track.times.length - 1]);
  27205. }
  27206. this.duration = duration;
  27207. return this;
  27208. },
  27209. trim: function trim() {
  27210. for (var i = 0; i < this.tracks.length; i++) {
  27211. this.tracks[i].trim(0, this.duration);
  27212. }
  27213. return this;
  27214. },
  27215. validate: function validate() {
  27216. var valid = true;
  27217. for (var i = 0; i < this.tracks.length; i++) {
  27218. valid = valid && this.tracks[i].validate();
  27219. }
  27220. return valid;
  27221. },
  27222. optimize: function optimize() {
  27223. for (var i = 0; i < this.tracks.length; i++) {
  27224. this.tracks[i].optimize();
  27225. }
  27226. return this;
  27227. },
  27228. clone: function clone() {
  27229. var tracks = [];
  27230. for (var i = 0; i < this.tracks.length; i++) {
  27231. tracks.push(this.tracks[i].clone());
  27232. }
  27233. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  27234. },
  27235. toJSON: function toJSON() {
  27236. return AnimationClip.toJSON(this);
  27237. }
  27238. });
  27239. var Cache = {
  27240. enabled: false,
  27241. files: {},
  27242. add: function add(key, file) {
  27243. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  27244. this.files[key] = file;
  27245. },
  27246. get: function get(key) {
  27247. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  27248. return this.files[key];
  27249. },
  27250. remove: function remove(key) {
  27251. delete this.files[key];
  27252. },
  27253. clear: function clear() {
  27254. this.files = {};
  27255. }
  27256. };
  27257. function LoadingManager(onLoad, onProgress, onError) {
  27258. var scope = this;
  27259. var isLoading = false;
  27260. var itemsLoaded = 0;
  27261. var itemsTotal = 0;
  27262. var urlModifier = undefined;
  27263. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  27264. // in the constructor
  27265. this.onStart = undefined;
  27266. this.onLoad = onLoad;
  27267. this.onProgress = onProgress;
  27268. this.onError = onError;
  27269. this.itemStart = function (url) {
  27270. itemsTotal++;
  27271. if (isLoading === false) {
  27272. if (scope.onStart !== undefined) {
  27273. scope.onStart(url, itemsLoaded, itemsTotal);
  27274. }
  27275. }
  27276. isLoading = true;
  27277. };
  27278. this.itemEnd = function (url) {
  27279. itemsLoaded++;
  27280. if (scope.onProgress !== undefined) {
  27281. scope.onProgress(url, itemsLoaded, itemsTotal);
  27282. }
  27283. if (itemsLoaded === itemsTotal) {
  27284. isLoading = false;
  27285. if (scope.onLoad !== undefined) {
  27286. scope.onLoad();
  27287. }
  27288. }
  27289. };
  27290. this.itemError = function (url) {
  27291. if (scope.onError !== undefined) {
  27292. scope.onError(url);
  27293. }
  27294. };
  27295. this.resolveURL = function (url) {
  27296. if (urlModifier) {
  27297. return urlModifier(url);
  27298. }
  27299. return url;
  27300. };
  27301. this.setURLModifier = function (transform) {
  27302. urlModifier = transform;
  27303. return this;
  27304. };
  27305. this.addHandler = function (regex, loader) {
  27306. handlers.push(regex, loader);
  27307. return this;
  27308. };
  27309. this.removeHandler = function (regex) {
  27310. var index = handlers.indexOf(regex);
  27311. if (index !== -1) {
  27312. handlers.splice(index, 2);
  27313. }
  27314. return this;
  27315. };
  27316. this.getHandler = function (file) {
  27317. for (var i = 0, l = handlers.length; i < l; i += 2) {
  27318. var regex = handlers[i];
  27319. var loader = handlers[i + 1];
  27320. if (regex.global) regex.lastIndex = 0; // see #17920
  27321. if (regex.test(file)) {
  27322. return loader;
  27323. }
  27324. }
  27325. return null;
  27326. };
  27327. }
  27328. var DefaultLoadingManager = new LoadingManager();
  27329. function Loader(manager) {
  27330. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  27331. this.crossOrigin = 'anonymous';
  27332. this.withCredentials = false;
  27333. this.path = '';
  27334. this.resourcePath = '';
  27335. this.requestHeader = {};
  27336. }
  27337. Object.assign(Loader.prototype, {
  27338. load: function load()
  27339. /* url, onLoad, onProgress, onError */
  27340. {},
  27341. loadAsync: function loadAsync(url, onProgress) {
  27342. var scope = this;
  27343. return new Promise(function (resolve, reject) {
  27344. scope.load(url, resolve, onProgress, reject);
  27345. });
  27346. },
  27347. parse: function parse()
  27348. /* data */
  27349. {},
  27350. setCrossOrigin: function setCrossOrigin(crossOrigin) {
  27351. this.crossOrigin = crossOrigin;
  27352. return this;
  27353. },
  27354. setWithCredentials: function setWithCredentials(value) {
  27355. this.withCredentials = value;
  27356. return this;
  27357. },
  27358. setPath: function setPath(path) {
  27359. this.path = path;
  27360. return this;
  27361. },
  27362. setResourcePath: function setResourcePath(resourcePath) {
  27363. this.resourcePath = resourcePath;
  27364. return this;
  27365. },
  27366. setRequestHeader: function setRequestHeader(requestHeader) {
  27367. this.requestHeader = requestHeader;
  27368. return this;
  27369. }
  27370. });
  27371. var loading = {};
  27372. function FileLoader(manager) {
  27373. Loader.call(this, manager);
  27374. }
  27375. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27376. constructor: FileLoader,
  27377. load: function load(url, onLoad, onProgress, onError) {
  27378. if (url === undefined) url = '';
  27379. if (this.path !== undefined) url = this.path + url;
  27380. url = this.manager.resolveURL(url);
  27381. var scope = this;
  27382. var cached = Cache.get(url);
  27383. if (cached !== undefined) {
  27384. scope.manager.itemStart(url);
  27385. setTimeout(function () {
  27386. if (onLoad) onLoad(cached);
  27387. scope.manager.itemEnd(url);
  27388. }, 0);
  27389. return cached;
  27390. } // Check if request is duplicate
  27391. if (loading[url] !== undefined) {
  27392. loading[url].push({
  27393. onLoad: onLoad,
  27394. onProgress: onProgress,
  27395. onError: onError
  27396. });
  27397. return;
  27398. } // Check for data: URI
  27399. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  27400. var dataUriRegexResult = url.match(dataUriRegex);
  27401. var request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  27402. if (dataUriRegexResult) {
  27403. var mimeType = dataUriRegexResult[1];
  27404. var isBase64 = !!dataUriRegexResult[2];
  27405. var data = dataUriRegexResult[3];
  27406. data = decodeURIComponent(data);
  27407. if (isBase64) data = atob(data);
  27408. try {
  27409. var response;
  27410. var responseType = (this.responseType || '').toLowerCase();
  27411. switch (responseType) {
  27412. case 'arraybuffer':
  27413. case 'blob':
  27414. var view = new Uint8Array(data.length);
  27415. for (var i = 0; i < data.length; i++) {
  27416. view[i] = data.charCodeAt(i);
  27417. }
  27418. if (responseType === 'blob') {
  27419. response = new Blob([view.buffer], {
  27420. type: mimeType
  27421. });
  27422. } else {
  27423. response = view.buffer;
  27424. }
  27425. break;
  27426. case 'document':
  27427. var parser = new DOMParser();
  27428. response = parser.parseFromString(data, mimeType);
  27429. break;
  27430. case 'json':
  27431. response = JSON.parse(data);
  27432. break;
  27433. default:
  27434. // 'text' or other
  27435. response = data;
  27436. break;
  27437. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27438. setTimeout(function () {
  27439. if (onLoad) onLoad(response);
  27440. scope.manager.itemEnd(url);
  27441. }, 0);
  27442. } catch (error) {
  27443. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27444. setTimeout(function () {
  27445. if (onError) onError(error);
  27446. scope.manager.itemError(url);
  27447. scope.manager.itemEnd(url);
  27448. }, 0);
  27449. }
  27450. } else {
  27451. // Initialise array for duplicate requests
  27452. loading[url] = [];
  27453. loading[url].push({
  27454. onLoad: onLoad,
  27455. onProgress: onProgress,
  27456. onError: onError
  27457. });
  27458. request = new XMLHttpRequest();
  27459. request.open('GET', url, true);
  27460. request.addEventListener('load', function (event) {
  27461. var response = this.response;
  27462. var callbacks = loading[url];
  27463. delete loading[url];
  27464. if (this.status === 200 || this.status === 0) {
  27465. // Some browsers return HTTP Status 0 when using non-http protocol
  27466. // e.g. 'file://' or 'data://'. Handle as success.
  27467. 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
  27468. // error response bodies as proper responses to requests.
  27469. Cache.add(url, response);
  27470. for (var _i = 0, il = callbacks.length; _i < il; _i++) {
  27471. var callback = callbacks[_i];
  27472. if (callback.onLoad) callback.onLoad(response);
  27473. }
  27474. scope.manager.itemEnd(url);
  27475. } else {
  27476. for (var _i2 = 0, _il = callbacks.length; _i2 < _il; _i2++) {
  27477. var _callback = callbacks[_i2];
  27478. if (_callback.onError) _callback.onError(event);
  27479. }
  27480. scope.manager.itemError(url);
  27481. scope.manager.itemEnd(url);
  27482. }
  27483. }, false);
  27484. request.addEventListener('progress', function (event) {
  27485. var callbacks = loading[url];
  27486. for (var _i3 = 0, il = callbacks.length; _i3 < il; _i3++) {
  27487. var callback = callbacks[_i3];
  27488. if (callback.onProgress) callback.onProgress(event);
  27489. }
  27490. }, false);
  27491. request.addEventListener('error', function (event) {
  27492. var callbacks = loading[url];
  27493. delete loading[url];
  27494. for (var _i4 = 0, il = callbacks.length; _i4 < il; _i4++) {
  27495. var callback = callbacks[_i4];
  27496. if (callback.onError) callback.onError(event);
  27497. }
  27498. scope.manager.itemError(url);
  27499. scope.manager.itemEnd(url);
  27500. }, false);
  27501. request.addEventListener('abort', function (event) {
  27502. var callbacks = loading[url];
  27503. delete loading[url];
  27504. for (var _i5 = 0, il = callbacks.length; _i5 < il; _i5++) {
  27505. var callback = callbacks[_i5];
  27506. if (callback.onError) callback.onError(event);
  27507. }
  27508. scope.manager.itemError(url);
  27509. scope.manager.itemEnd(url);
  27510. }, false);
  27511. if (this.responseType !== undefined) request.responseType = this.responseType;
  27512. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  27513. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  27514. for (var header in this.requestHeader) {
  27515. request.setRequestHeader(header, this.requestHeader[header]);
  27516. }
  27517. request.send(null);
  27518. }
  27519. scope.manager.itemStart(url);
  27520. return request;
  27521. },
  27522. setResponseType: function setResponseType(value) {
  27523. this.responseType = value;
  27524. return this;
  27525. },
  27526. setMimeType: function setMimeType(value) {
  27527. this.mimeType = value;
  27528. return this;
  27529. }
  27530. });
  27531. function AnimationLoader(manager) {
  27532. Loader.call(this, manager);
  27533. }
  27534. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27535. constructor: AnimationLoader,
  27536. load: function load(url, onLoad, onProgress, onError) {
  27537. var scope = this;
  27538. var loader = new FileLoader(scope.manager);
  27539. loader.setPath(scope.path);
  27540. loader.setRequestHeader(scope.requestHeader);
  27541. loader.setWithCredentials(scope.withCredentials);
  27542. loader.load(url, function (text) {
  27543. try {
  27544. onLoad(scope.parse(JSON.parse(text)));
  27545. } catch (e) {
  27546. if (onError) {
  27547. onError(e);
  27548. } else {
  27549. console.error(e);
  27550. }
  27551. scope.manager.itemError(url);
  27552. }
  27553. }, onProgress, onError);
  27554. },
  27555. parse: function parse(json) {
  27556. var animations = [];
  27557. for (var i = 0; i < json.length; i++) {
  27558. var clip = AnimationClip.parse(json[i]);
  27559. animations.push(clip);
  27560. }
  27561. return animations;
  27562. }
  27563. });
  27564. /**
  27565. * Abstract Base class to block based textures loader (dds, pvr, ...)
  27566. *
  27567. * Sub classes have to implement the parse() method which will be used in load().
  27568. */
  27569. function CompressedTextureLoader(manager) {
  27570. Loader.call(this, manager);
  27571. }
  27572. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27573. constructor: CompressedTextureLoader,
  27574. load: function load(url, onLoad, onProgress, onError) {
  27575. var scope = this;
  27576. var images = [];
  27577. var texture = new CompressedTexture();
  27578. var loader = new FileLoader(this.manager);
  27579. loader.setPath(this.path);
  27580. loader.setResponseType('arraybuffer');
  27581. loader.setRequestHeader(this.requestHeader);
  27582. loader.setWithCredentials(scope.withCredentials);
  27583. var loaded = 0;
  27584. function loadTexture(i) {
  27585. loader.load(url[i], function (buffer) {
  27586. var texDatas = scope.parse(buffer, true);
  27587. images[i] = {
  27588. width: texDatas.width,
  27589. height: texDatas.height,
  27590. format: texDatas.format,
  27591. mipmaps: texDatas.mipmaps
  27592. };
  27593. loaded += 1;
  27594. if (loaded === 6) {
  27595. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  27596. texture.image = images;
  27597. texture.format = texDatas.format;
  27598. texture.needsUpdate = true;
  27599. if (onLoad) onLoad(texture);
  27600. }
  27601. }, onProgress, onError);
  27602. }
  27603. if (Array.isArray(url)) {
  27604. for (var i = 0, il = url.length; i < il; ++i) {
  27605. loadTexture(i);
  27606. }
  27607. } else {
  27608. // compressed cubemap texture stored in a single DDS file
  27609. loader.load(url, function (buffer) {
  27610. var texDatas = scope.parse(buffer, true);
  27611. if (texDatas.isCubemap) {
  27612. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  27613. for (var f = 0; f < faces; f++) {
  27614. images[f] = {
  27615. mipmaps: []
  27616. };
  27617. for (var _i = 0; _i < texDatas.mipmapCount; _i++) {
  27618. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + _i]);
  27619. images[f].format = texDatas.format;
  27620. images[f].width = texDatas.width;
  27621. images[f].height = texDatas.height;
  27622. }
  27623. }
  27624. texture.image = images;
  27625. } else {
  27626. texture.image.width = texDatas.width;
  27627. texture.image.height = texDatas.height;
  27628. texture.mipmaps = texDatas.mipmaps;
  27629. }
  27630. if (texDatas.mipmapCount === 1) {
  27631. texture.minFilter = LinearFilter;
  27632. }
  27633. texture.format = texDatas.format;
  27634. texture.needsUpdate = true;
  27635. if (onLoad) onLoad(texture);
  27636. }, onProgress, onError);
  27637. }
  27638. return texture;
  27639. }
  27640. });
  27641. function ImageLoader(manager) {
  27642. Loader.call(this, manager);
  27643. }
  27644. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27645. constructor: ImageLoader,
  27646. load: function load(url, onLoad, onProgress, onError) {
  27647. if (this.path !== undefined) url = this.path + url;
  27648. url = this.manager.resolveURL(url);
  27649. var scope = this;
  27650. var cached = Cache.get(url);
  27651. if (cached !== undefined) {
  27652. scope.manager.itemStart(url);
  27653. setTimeout(function () {
  27654. if (onLoad) onLoad(cached);
  27655. scope.manager.itemEnd(url);
  27656. }, 0);
  27657. return cached;
  27658. }
  27659. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  27660. function onImageLoad() {
  27661. image.removeEventListener('load', onImageLoad, false);
  27662. image.removeEventListener('error', onImageError, false);
  27663. Cache.add(url, this);
  27664. if (onLoad) onLoad(this);
  27665. scope.manager.itemEnd(url);
  27666. }
  27667. function onImageError(event) {
  27668. image.removeEventListener('load', onImageLoad, false);
  27669. image.removeEventListener('error', onImageError, false);
  27670. if (onError) onError(event);
  27671. scope.manager.itemError(url);
  27672. scope.manager.itemEnd(url);
  27673. }
  27674. image.addEventListener('load', onImageLoad, false);
  27675. image.addEventListener('error', onImageError, false);
  27676. if (url.substr(0, 5) !== 'data:') {
  27677. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  27678. }
  27679. scope.manager.itemStart(url);
  27680. image.src = url;
  27681. return image;
  27682. }
  27683. });
  27684. function CubeTextureLoader(manager) {
  27685. Loader.call(this, manager);
  27686. }
  27687. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27688. constructor: CubeTextureLoader,
  27689. load: function load(urls, onLoad, onProgress, onError) {
  27690. var texture = new CubeTexture();
  27691. var loader = new ImageLoader(this.manager);
  27692. loader.setCrossOrigin(this.crossOrigin);
  27693. loader.setPath(this.path);
  27694. var loaded = 0;
  27695. function loadTexture(i) {
  27696. loader.load(urls[i], function (image) {
  27697. texture.images[i] = image;
  27698. loaded++;
  27699. if (loaded === 6) {
  27700. texture.needsUpdate = true;
  27701. if (onLoad) onLoad(texture);
  27702. }
  27703. }, undefined, onError);
  27704. }
  27705. for (var i = 0; i < urls.length; ++i) {
  27706. loadTexture(i);
  27707. }
  27708. return texture;
  27709. }
  27710. });
  27711. /**
  27712. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  27713. *
  27714. * Sub classes have to implement the parse() method which will be used in load().
  27715. */
  27716. function DataTextureLoader(manager) {
  27717. Loader.call(this, manager);
  27718. }
  27719. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27720. constructor: DataTextureLoader,
  27721. load: function load(url, onLoad, onProgress, onError) {
  27722. var scope = this;
  27723. var texture = new DataTexture();
  27724. var loader = new FileLoader(this.manager);
  27725. loader.setResponseType('arraybuffer');
  27726. loader.setRequestHeader(this.requestHeader);
  27727. loader.setPath(this.path);
  27728. loader.setWithCredentials(scope.withCredentials);
  27729. loader.load(url, function (buffer) {
  27730. var texData = scope.parse(buffer);
  27731. if (!texData) return;
  27732. if (texData.image !== undefined) {
  27733. texture.image = texData.image;
  27734. } else if (texData.data !== undefined) {
  27735. texture.image.width = texData.width;
  27736. texture.image.height = texData.height;
  27737. texture.image.data = texData.data;
  27738. }
  27739. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  27740. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  27741. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  27742. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  27743. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  27744. if (texData.encoding !== undefined) {
  27745. texture.encoding = texData.encoding;
  27746. }
  27747. if (texData.flipY !== undefined) {
  27748. texture.flipY = texData.flipY;
  27749. }
  27750. if (texData.format !== undefined) {
  27751. texture.format = texData.format;
  27752. }
  27753. if (texData.type !== undefined) {
  27754. texture.type = texData.type;
  27755. }
  27756. if (texData.mipmaps !== undefined) {
  27757. texture.mipmaps = texData.mipmaps;
  27758. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  27759. }
  27760. if (texData.mipmapCount === 1) {
  27761. texture.minFilter = LinearFilter;
  27762. }
  27763. texture.needsUpdate = true;
  27764. if (onLoad) onLoad(texture, texData);
  27765. }, onProgress, onError);
  27766. return texture;
  27767. }
  27768. });
  27769. function TextureLoader(manager) {
  27770. Loader.call(this, manager);
  27771. }
  27772. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27773. constructor: TextureLoader,
  27774. load: function load(url, onLoad, onProgress, onError) {
  27775. var texture = new Texture();
  27776. var loader = new ImageLoader(this.manager);
  27777. loader.setCrossOrigin(this.crossOrigin);
  27778. loader.setPath(this.path);
  27779. loader.load(url, function (image) {
  27780. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  27781. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  27782. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  27783. texture.needsUpdate = true;
  27784. if (onLoad !== undefined) {
  27785. onLoad(texture);
  27786. }
  27787. }, onProgress, onError);
  27788. return texture;
  27789. }
  27790. });
  27791. /**
  27792. * Extensible curve object.
  27793. *
  27794. * Some common of curve methods:
  27795. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  27796. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  27797. * .getPoints(), .getSpacedPoints()
  27798. * .getLength()
  27799. * .updateArcLengths()
  27800. *
  27801. * This following curves inherit from THREE.Curve:
  27802. *
  27803. * -- 2D curves --
  27804. * THREE.ArcCurve
  27805. * THREE.CubicBezierCurve
  27806. * THREE.EllipseCurve
  27807. * THREE.LineCurve
  27808. * THREE.QuadraticBezierCurve
  27809. * THREE.SplineCurve
  27810. *
  27811. * -- 3D curves --
  27812. * THREE.CatmullRomCurve3
  27813. * THREE.CubicBezierCurve3
  27814. * THREE.LineCurve3
  27815. * THREE.QuadraticBezierCurve3
  27816. *
  27817. * A series of curves can be represented as a THREE.CurvePath.
  27818. *
  27819. **/
  27820. function Curve() {
  27821. this.type = 'Curve';
  27822. this.arcLengthDivisions = 200;
  27823. }
  27824. Object.assign(Curve.prototype, {
  27825. // Virtual base class method to overwrite and implement in subclasses
  27826. // - t [0 .. 1]
  27827. getPoint: function getPoint()
  27828. /* t, optionalTarget */
  27829. {
  27830. console.warn('THREE.Curve: .getPoint() not implemented.');
  27831. return null;
  27832. },
  27833. // Get point at relative position in curve according to arc length
  27834. // - u [0 .. 1]
  27835. getPointAt: function getPointAt(u, optionalTarget) {
  27836. var t = this.getUtoTmapping(u);
  27837. return this.getPoint(t, optionalTarget);
  27838. },
  27839. // Get sequence of points using getPoint( t )
  27840. getPoints: function getPoints(divisions) {
  27841. if (divisions === void 0) {
  27842. divisions = 5;
  27843. }
  27844. var points = [];
  27845. for (var d = 0; d <= divisions; d++) {
  27846. points.push(this.getPoint(d / divisions));
  27847. }
  27848. return points;
  27849. },
  27850. // Get sequence of points using getPointAt( u )
  27851. getSpacedPoints: function getSpacedPoints(divisions) {
  27852. if (divisions === void 0) {
  27853. divisions = 5;
  27854. }
  27855. var points = [];
  27856. for (var d = 0; d <= divisions; d++) {
  27857. points.push(this.getPointAt(d / divisions));
  27858. }
  27859. return points;
  27860. },
  27861. // Get total curve arc length
  27862. getLength: function getLength() {
  27863. var lengths = this.getLengths();
  27864. return lengths[lengths.length - 1];
  27865. },
  27866. // Get list of cumulative segment lengths
  27867. getLengths: function getLengths(divisions) {
  27868. if (divisions === undefined) divisions = this.arcLengthDivisions;
  27869. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  27870. return this.cacheArcLengths;
  27871. }
  27872. this.needsUpdate = false;
  27873. var cache = [];
  27874. var current,
  27875. last = this.getPoint(0);
  27876. var sum = 0;
  27877. cache.push(0);
  27878. for (var p = 1; p <= divisions; p++) {
  27879. current = this.getPoint(p / divisions);
  27880. sum += current.distanceTo(last);
  27881. cache.push(sum);
  27882. last = current;
  27883. }
  27884. this.cacheArcLengths = cache;
  27885. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  27886. },
  27887. updateArcLengths: function updateArcLengths() {
  27888. this.needsUpdate = true;
  27889. this.getLengths();
  27890. },
  27891. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  27892. getUtoTmapping: function getUtoTmapping(u, distance) {
  27893. var arcLengths = this.getLengths();
  27894. var i = 0;
  27895. var il = arcLengths.length;
  27896. var targetArcLength; // The targeted u distance value to get
  27897. if (distance) {
  27898. targetArcLength = distance;
  27899. } else {
  27900. targetArcLength = u * arcLengths[il - 1];
  27901. } // binary search for the index with largest value smaller than target u distance
  27902. var low = 0,
  27903. high = il - 1,
  27904. comparison;
  27905. while (low <= high) {
  27906. 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
  27907. comparison = arcLengths[i] - targetArcLength;
  27908. if (comparison < 0) {
  27909. low = i + 1;
  27910. } else if (comparison > 0) {
  27911. high = i - 1;
  27912. } else {
  27913. high = i;
  27914. break; // DONE
  27915. }
  27916. }
  27917. i = high;
  27918. if (arcLengths[i] === targetArcLength) {
  27919. return i / (il - 1);
  27920. } // we could get finer grain at lengths, or use simple interpolation between two points
  27921. var lengthBefore = arcLengths[i];
  27922. var lengthAfter = arcLengths[i + 1];
  27923. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  27924. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  27925. var t = (i + segmentFraction) / (il - 1);
  27926. return t;
  27927. },
  27928. // Returns a unit vector tangent at t
  27929. // In case any sub curve does not implement its tangent derivation,
  27930. // 2 points a small delta apart will be used to find its gradient
  27931. // which seems to give a reasonable approximation
  27932. getTangent: function getTangent(t, optionalTarget) {
  27933. var delta = 0.0001;
  27934. var t1 = t - delta;
  27935. var t2 = t + delta; // Capping in case of danger
  27936. if (t1 < 0) t1 = 0;
  27937. if (t2 > 1) t2 = 1;
  27938. var pt1 = this.getPoint(t1);
  27939. var pt2 = this.getPoint(t2);
  27940. var tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  27941. tangent.copy(pt2).sub(pt1).normalize();
  27942. return tangent;
  27943. },
  27944. getTangentAt: function getTangentAt(u, optionalTarget) {
  27945. var t = this.getUtoTmapping(u);
  27946. return this.getTangent(t, optionalTarget);
  27947. },
  27948. computeFrenetFrames: function computeFrenetFrames(segments, closed) {
  27949. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  27950. var normal = new Vector3();
  27951. var tangents = [];
  27952. var normals = [];
  27953. var binormals = [];
  27954. var vec = new Vector3();
  27955. var mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  27956. for (var i = 0; i <= segments; i++) {
  27957. var u = i / segments;
  27958. tangents[i] = this.getTangentAt(u, new Vector3());
  27959. tangents[i].normalize();
  27960. } // select an initial normal vector perpendicular to the first tangent vector,
  27961. // and in the direction of the minimum tangent xyz component
  27962. normals[0] = new Vector3();
  27963. binormals[0] = new Vector3();
  27964. var min = Number.MAX_VALUE;
  27965. var tx = Math.abs(tangents[0].x);
  27966. var ty = Math.abs(tangents[0].y);
  27967. var tz = Math.abs(tangents[0].z);
  27968. if (tx <= min) {
  27969. min = tx;
  27970. normal.set(1, 0, 0);
  27971. }
  27972. if (ty <= min) {
  27973. min = ty;
  27974. normal.set(0, 1, 0);
  27975. }
  27976. if (tz <= min) {
  27977. normal.set(0, 0, 1);
  27978. }
  27979. vec.crossVectors(tangents[0], normal).normalize();
  27980. normals[0].crossVectors(tangents[0], vec);
  27981. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  27982. for (var _i = 1; _i <= segments; _i++) {
  27983. normals[_i] = normals[_i - 1].clone();
  27984. binormals[_i] = binormals[_i - 1].clone();
  27985. vec.crossVectors(tangents[_i - 1], tangents[_i]);
  27986. if (vec.length() > Number.EPSILON) {
  27987. vec.normalize();
  27988. var theta = Math.acos(MathUtils.clamp(tangents[_i - 1].dot(tangents[_i]), -1, 1)); // clamp for floating pt errors
  27989. normals[_i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  27990. }
  27991. binormals[_i].crossVectors(tangents[_i], normals[_i]);
  27992. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  27993. if (closed === true) {
  27994. var _theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  27995. _theta /= segments;
  27996. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  27997. _theta = -_theta;
  27998. }
  27999. for (var _i2 = 1; _i2 <= segments; _i2++) {
  28000. // twist a little...
  28001. normals[_i2].applyMatrix4(mat.makeRotationAxis(tangents[_i2], _theta * _i2));
  28002. binormals[_i2].crossVectors(tangents[_i2], normals[_i2]);
  28003. }
  28004. }
  28005. return {
  28006. tangents: tangents,
  28007. normals: normals,
  28008. binormals: binormals
  28009. };
  28010. },
  28011. clone: function clone() {
  28012. return new this.constructor().copy(this);
  28013. },
  28014. copy: function copy(source) {
  28015. this.arcLengthDivisions = source.arcLengthDivisions;
  28016. return this;
  28017. },
  28018. toJSON: function toJSON() {
  28019. var data = {
  28020. metadata: {
  28021. version: 4.5,
  28022. type: 'Curve',
  28023. generator: 'Curve.toJSON'
  28024. }
  28025. };
  28026. data.arcLengthDivisions = this.arcLengthDivisions;
  28027. data.type = this.type;
  28028. return data;
  28029. },
  28030. fromJSON: function fromJSON(json) {
  28031. this.arcLengthDivisions = json.arcLengthDivisions;
  28032. return this;
  28033. }
  28034. });
  28035. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28036. Curve.call(this);
  28037. this.type = 'EllipseCurve';
  28038. this.aX = aX || 0;
  28039. this.aY = aY || 0;
  28040. this.xRadius = xRadius || 1;
  28041. this.yRadius = yRadius || 1;
  28042. this.aStartAngle = aStartAngle || 0;
  28043. this.aEndAngle = aEndAngle || 2 * Math.PI;
  28044. this.aClockwise = aClockwise || false;
  28045. this.aRotation = aRotation || 0;
  28046. }
  28047. EllipseCurve.prototype = Object.create(Curve.prototype);
  28048. EllipseCurve.prototype.constructor = EllipseCurve;
  28049. EllipseCurve.prototype.isEllipseCurve = true;
  28050. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  28051. var point = optionalTarget || new Vector2();
  28052. var twoPi = Math.PI * 2;
  28053. var deltaAngle = this.aEndAngle - this.aStartAngle;
  28054. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  28055. while (deltaAngle < 0) {
  28056. deltaAngle += twoPi;
  28057. }
  28058. while (deltaAngle > twoPi) {
  28059. deltaAngle -= twoPi;
  28060. }
  28061. if (deltaAngle < Number.EPSILON) {
  28062. if (samePoints) {
  28063. deltaAngle = 0;
  28064. } else {
  28065. deltaAngle = twoPi;
  28066. }
  28067. }
  28068. if (this.aClockwise === true && !samePoints) {
  28069. if (deltaAngle === twoPi) {
  28070. deltaAngle = -twoPi;
  28071. } else {
  28072. deltaAngle = deltaAngle - twoPi;
  28073. }
  28074. }
  28075. var angle = this.aStartAngle + t * deltaAngle;
  28076. var x = this.aX + this.xRadius * Math.cos(angle);
  28077. var y = this.aY + this.yRadius * Math.sin(angle);
  28078. if (this.aRotation !== 0) {
  28079. var cos = Math.cos(this.aRotation);
  28080. var sin = Math.sin(this.aRotation);
  28081. var tx = x - this.aX;
  28082. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  28083. x = tx * cos - ty * sin + this.aX;
  28084. y = tx * sin + ty * cos + this.aY;
  28085. }
  28086. return point.set(x, y);
  28087. };
  28088. EllipseCurve.prototype.copy = function (source) {
  28089. Curve.prototype.copy.call(this, source);
  28090. this.aX = source.aX;
  28091. this.aY = source.aY;
  28092. this.xRadius = source.xRadius;
  28093. this.yRadius = source.yRadius;
  28094. this.aStartAngle = source.aStartAngle;
  28095. this.aEndAngle = source.aEndAngle;
  28096. this.aClockwise = source.aClockwise;
  28097. this.aRotation = source.aRotation;
  28098. return this;
  28099. };
  28100. EllipseCurve.prototype.toJSON = function () {
  28101. var data = Curve.prototype.toJSON.call(this);
  28102. data.aX = this.aX;
  28103. data.aY = this.aY;
  28104. data.xRadius = this.xRadius;
  28105. data.yRadius = this.yRadius;
  28106. data.aStartAngle = this.aStartAngle;
  28107. data.aEndAngle = this.aEndAngle;
  28108. data.aClockwise = this.aClockwise;
  28109. data.aRotation = this.aRotation;
  28110. return data;
  28111. };
  28112. EllipseCurve.prototype.fromJSON = function (json) {
  28113. Curve.prototype.fromJSON.call(this, json);
  28114. this.aX = json.aX;
  28115. this.aY = json.aY;
  28116. this.xRadius = json.xRadius;
  28117. this.yRadius = json.yRadius;
  28118. this.aStartAngle = json.aStartAngle;
  28119. this.aEndAngle = json.aEndAngle;
  28120. this.aClockwise = json.aClockwise;
  28121. this.aRotation = json.aRotation;
  28122. return this;
  28123. };
  28124. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28125. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  28126. this.type = 'ArcCurve';
  28127. }
  28128. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  28129. ArcCurve.prototype.constructor = ArcCurve;
  28130. ArcCurve.prototype.isArcCurve = true;
  28131. /**
  28132. * Centripetal CatmullRom Curve - which is useful for avoiding
  28133. * cusps and self-intersections in non-uniform catmull rom curves.
  28134. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28135. *
  28136. * curve.type accepts centripetal(default), chordal and catmullrom
  28137. * curve.tension is used for catmullrom which defaults to 0.5
  28138. */
  28139. /*
  28140. Based on an optimized c++ solution in
  28141. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28142. - http://ideone.com/NoEbVM
  28143. This CubicPoly class could be used for reusing some variables and calculations,
  28144. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28145. which can be placed in CurveUtils.
  28146. */
  28147. function CubicPoly() {
  28148. var c0 = 0,
  28149. c1 = 0,
  28150. c2 = 0,
  28151. c3 = 0;
  28152. /*
  28153. * Compute coefficients for a cubic polynomial
  28154. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28155. * such that
  28156. * p(0) = x0, p(1) = x1
  28157. * and
  28158. * p'(0) = t0, p'(1) = t1.
  28159. */
  28160. function init(x0, x1, t0, t1) {
  28161. c0 = x0;
  28162. c1 = t0;
  28163. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  28164. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28165. }
  28166. return {
  28167. initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {
  28168. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  28169. },
  28170. initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {
  28171. // compute tangents when parameterized in [t1,t2]
  28172. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  28173. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  28174. t1 *= dt1;
  28175. t2 *= dt1;
  28176. init(x1, x2, t1, t2);
  28177. },
  28178. calc: function calc(t) {
  28179. var t2 = t * t;
  28180. var t3 = t2 * t;
  28181. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28182. }
  28183. };
  28184. } //
  28185. var tmp = new Vector3();
  28186. var px = new CubicPoly(),
  28187. py = new CubicPoly(),
  28188. pz = new CubicPoly();
  28189. function CatmullRomCurve3(points, closed, curveType, tension) {
  28190. if (points === void 0) {
  28191. points = [];
  28192. }
  28193. if (closed === void 0) {
  28194. closed = false;
  28195. }
  28196. if (curveType === void 0) {
  28197. curveType = 'centripetal';
  28198. }
  28199. if (tension === void 0) {
  28200. tension = 0.5;
  28201. }
  28202. Curve.call(this);
  28203. this.type = 'CatmullRomCurve3';
  28204. this.points = points;
  28205. this.closed = closed;
  28206. this.curveType = curveType;
  28207. this.tension = tension;
  28208. }
  28209. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  28210. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28211. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  28212. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  28213. if (optionalTarget === void 0) {
  28214. optionalTarget = new Vector3();
  28215. }
  28216. var point = optionalTarget;
  28217. var points = this.points;
  28218. var l = points.length;
  28219. var p = (l - (this.closed ? 0 : 1)) * t;
  28220. var intPoint = Math.floor(p);
  28221. var weight = p - intPoint;
  28222. if (this.closed) {
  28223. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  28224. } else if (weight === 0 && intPoint === l - 1) {
  28225. intPoint = l - 2;
  28226. weight = 1;
  28227. }
  28228. var p0, p3; // 4 points (p1 & p2 defined below)
  28229. if (this.closed || intPoint > 0) {
  28230. p0 = points[(intPoint - 1) % l];
  28231. } else {
  28232. // extrapolate first point
  28233. tmp.subVectors(points[0], points[1]).add(points[0]);
  28234. p0 = tmp;
  28235. }
  28236. var p1 = points[intPoint % l];
  28237. var p2 = points[(intPoint + 1) % l];
  28238. if (this.closed || intPoint + 2 < l) {
  28239. p3 = points[(intPoint + 2) % l];
  28240. } else {
  28241. // extrapolate last point
  28242. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  28243. p3 = tmp;
  28244. }
  28245. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  28246. // init Centripetal / Chordal Catmull-Rom
  28247. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  28248. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  28249. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  28250. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  28251. if (dt1 < 1e-4) dt1 = 1.0;
  28252. if (dt0 < 1e-4) dt0 = dt1;
  28253. if (dt2 < 1e-4) dt2 = dt1;
  28254. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  28255. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  28256. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  28257. } else if (this.curveType === 'catmullrom') {
  28258. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  28259. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  28260. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  28261. }
  28262. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  28263. return point;
  28264. };
  28265. CatmullRomCurve3.prototype.copy = function (source) {
  28266. Curve.prototype.copy.call(this, source);
  28267. this.points = [];
  28268. for (var i = 0, l = source.points.length; i < l; i++) {
  28269. var point = source.points[i];
  28270. this.points.push(point.clone());
  28271. }
  28272. this.closed = source.closed;
  28273. this.curveType = source.curveType;
  28274. this.tension = source.tension;
  28275. return this;
  28276. };
  28277. CatmullRomCurve3.prototype.toJSON = function () {
  28278. var data = Curve.prototype.toJSON.call(this);
  28279. data.points = [];
  28280. for (var i = 0, l = this.points.length; i < l; i++) {
  28281. var point = this.points[i];
  28282. data.points.push(point.toArray());
  28283. }
  28284. data.closed = this.closed;
  28285. data.curveType = this.curveType;
  28286. data.tension = this.tension;
  28287. return data;
  28288. };
  28289. CatmullRomCurve3.prototype.fromJSON = function (json) {
  28290. Curve.prototype.fromJSON.call(this, json);
  28291. this.points = [];
  28292. for (var i = 0, l = json.points.length; i < l; i++) {
  28293. var point = json.points[i];
  28294. this.points.push(new Vector3().fromArray(point));
  28295. }
  28296. this.closed = json.closed;
  28297. this.curveType = json.curveType;
  28298. this.tension = json.tension;
  28299. return this;
  28300. };
  28301. /**
  28302. * Bezier Curves formulas obtained from
  28303. * http://en.wikipedia.org/wiki/Bézier_curve
  28304. */
  28305. function CatmullRom(t, p0, p1, p2, p3) {
  28306. var v0 = (p2 - p0) * 0.5;
  28307. var v1 = (p3 - p1) * 0.5;
  28308. var t2 = t * t;
  28309. var t3 = t * t2;
  28310. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  28311. } //
  28312. function QuadraticBezierP0(t, p) {
  28313. var k = 1 - t;
  28314. return k * k * p;
  28315. }
  28316. function QuadraticBezierP1(t, p) {
  28317. return 2 * (1 - t) * t * p;
  28318. }
  28319. function QuadraticBezierP2(t, p) {
  28320. return t * t * p;
  28321. }
  28322. function QuadraticBezier(t, p0, p1, p2) {
  28323. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  28324. } //
  28325. function CubicBezierP0(t, p) {
  28326. var k = 1 - t;
  28327. return k * k * k * p;
  28328. }
  28329. function CubicBezierP1(t, p) {
  28330. var k = 1 - t;
  28331. return 3 * k * k * t * p;
  28332. }
  28333. function CubicBezierP2(t, p) {
  28334. return 3 * (1 - t) * t * t * p;
  28335. }
  28336. function CubicBezierP3(t, p) {
  28337. return t * t * t * p;
  28338. }
  28339. function CubicBezier(t, p0, p1, p2, p3) {
  28340. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  28341. }
  28342. function CubicBezierCurve(v0, v1, v2, v3) {
  28343. if (v0 === void 0) {
  28344. v0 = new Vector2();
  28345. }
  28346. if (v1 === void 0) {
  28347. v1 = new Vector2();
  28348. }
  28349. if (v2 === void 0) {
  28350. v2 = new Vector2();
  28351. }
  28352. if (v3 === void 0) {
  28353. v3 = new Vector2();
  28354. }
  28355. Curve.call(this);
  28356. this.type = 'CubicBezierCurve';
  28357. this.v0 = v0;
  28358. this.v1 = v1;
  28359. this.v2 = v2;
  28360. this.v3 = v3;
  28361. }
  28362. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  28363. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  28364. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  28365. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  28366. if (optionalTarget === void 0) {
  28367. optionalTarget = new Vector2();
  28368. }
  28369. var point = optionalTarget;
  28370. var v0 = this.v0,
  28371. v1 = this.v1,
  28372. v2 = this.v2,
  28373. v3 = this.v3;
  28374. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  28375. return point;
  28376. };
  28377. CubicBezierCurve.prototype.copy = function (source) {
  28378. Curve.prototype.copy.call(this, source);
  28379. this.v0.copy(source.v0);
  28380. this.v1.copy(source.v1);
  28381. this.v2.copy(source.v2);
  28382. this.v3.copy(source.v3);
  28383. return this;
  28384. };
  28385. CubicBezierCurve.prototype.toJSON = function () {
  28386. var data = Curve.prototype.toJSON.call(this);
  28387. data.v0 = this.v0.toArray();
  28388. data.v1 = this.v1.toArray();
  28389. data.v2 = this.v2.toArray();
  28390. data.v3 = this.v3.toArray();
  28391. return data;
  28392. };
  28393. CubicBezierCurve.prototype.fromJSON = function (json) {
  28394. Curve.prototype.fromJSON.call(this, json);
  28395. this.v0.fromArray(json.v0);
  28396. this.v1.fromArray(json.v1);
  28397. this.v2.fromArray(json.v2);
  28398. this.v3.fromArray(json.v3);
  28399. return this;
  28400. };
  28401. function CubicBezierCurve3(v0, v1, v2, v3) {
  28402. if (v0 === void 0) {
  28403. v0 = new Vector3();
  28404. }
  28405. if (v1 === void 0) {
  28406. v1 = new Vector3();
  28407. }
  28408. if (v2 === void 0) {
  28409. v2 = new Vector3();
  28410. }
  28411. if (v3 === void 0) {
  28412. v3 = new Vector3();
  28413. }
  28414. Curve.call(this);
  28415. this.type = 'CubicBezierCurve3';
  28416. this.v0 = v0;
  28417. this.v1 = v1;
  28418. this.v2 = v2;
  28419. this.v3 = v3;
  28420. }
  28421. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  28422. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  28423. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  28424. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  28425. if (optionalTarget === void 0) {
  28426. optionalTarget = new Vector3();
  28427. }
  28428. var point = optionalTarget;
  28429. var v0 = this.v0,
  28430. v1 = this.v1,
  28431. v2 = this.v2,
  28432. v3 = this.v3;
  28433. 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));
  28434. return point;
  28435. };
  28436. CubicBezierCurve3.prototype.copy = function (source) {
  28437. Curve.prototype.copy.call(this, source);
  28438. this.v0.copy(source.v0);
  28439. this.v1.copy(source.v1);
  28440. this.v2.copy(source.v2);
  28441. this.v3.copy(source.v3);
  28442. return this;
  28443. };
  28444. CubicBezierCurve3.prototype.toJSON = function () {
  28445. var data = Curve.prototype.toJSON.call(this);
  28446. data.v0 = this.v0.toArray();
  28447. data.v1 = this.v1.toArray();
  28448. data.v2 = this.v2.toArray();
  28449. data.v3 = this.v3.toArray();
  28450. return data;
  28451. };
  28452. CubicBezierCurve3.prototype.fromJSON = function (json) {
  28453. Curve.prototype.fromJSON.call(this, json);
  28454. this.v0.fromArray(json.v0);
  28455. this.v1.fromArray(json.v1);
  28456. this.v2.fromArray(json.v2);
  28457. this.v3.fromArray(json.v3);
  28458. return this;
  28459. };
  28460. function LineCurve(v1, v2) {
  28461. if (v1 === void 0) {
  28462. v1 = new Vector2();
  28463. }
  28464. if (v2 === void 0) {
  28465. v2 = new Vector2();
  28466. }
  28467. Curve.call(this);
  28468. this.type = 'LineCurve';
  28469. this.v1 = v1;
  28470. this.v2 = v2;
  28471. }
  28472. LineCurve.prototype = Object.create(Curve.prototype);
  28473. LineCurve.prototype.constructor = LineCurve;
  28474. LineCurve.prototype.isLineCurve = true;
  28475. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  28476. if (optionalTarget === void 0) {
  28477. optionalTarget = new Vector2();
  28478. }
  28479. var point = optionalTarget;
  28480. if (t === 1) {
  28481. point.copy(this.v2);
  28482. } else {
  28483. point.copy(this.v2).sub(this.v1);
  28484. point.multiplyScalar(t).add(this.v1);
  28485. }
  28486. return point;
  28487. }; // Line curve is linear, so we can overwrite default getPointAt
  28488. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  28489. return this.getPoint(u, optionalTarget);
  28490. };
  28491. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  28492. var tangent = optionalTarget || new Vector2();
  28493. tangent.copy(this.v2).sub(this.v1).normalize();
  28494. return tangent;
  28495. };
  28496. LineCurve.prototype.copy = function (source) {
  28497. Curve.prototype.copy.call(this, source);
  28498. this.v1.copy(source.v1);
  28499. this.v2.copy(source.v2);
  28500. return this;
  28501. };
  28502. LineCurve.prototype.toJSON = function () {
  28503. var data = Curve.prototype.toJSON.call(this);
  28504. data.v1 = this.v1.toArray();
  28505. data.v2 = this.v2.toArray();
  28506. return data;
  28507. };
  28508. LineCurve.prototype.fromJSON = function (json) {
  28509. Curve.prototype.fromJSON.call(this, json);
  28510. this.v1.fromArray(json.v1);
  28511. this.v2.fromArray(json.v2);
  28512. return this;
  28513. };
  28514. function LineCurve3(v1, v2) {
  28515. if (v1 === void 0) {
  28516. v1 = new Vector3();
  28517. }
  28518. if (v2 === void 0) {
  28519. v2 = new Vector3();
  28520. }
  28521. Curve.call(this);
  28522. this.type = 'LineCurve3';
  28523. this.v1 = v1;
  28524. this.v2 = v2;
  28525. }
  28526. LineCurve3.prototype = Object.create(Curve.prototype);
  28527. LineCurve3.prototype.constructor = LineCurve3;
  28528. LineCurve3.prototype.isLineCurve3 = true;
  28529. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  28530. if (optionalTarget === void 0) {
  28531. optionalTarget = new Vector3();
  28532. }
  28533. var point = optionalTarget;
  28534. if (t === 1) {
  28535. point.copy(this.v2);
  28536. } else {
  28537. point.copy(this.v2).sub(this.v1);
  28538. point.multiplyScalar(t).add(this.v1);
  28539. }
  28540. return point;
  28541. }; // Line curve is linear, so we can overwrite default getPointAt
  28542. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  28543. return this.getPoint(u, optionalTarget);
  28544. };
  28545. LineCurve3.prototype.copy = function (source) {
  28546. Curve.prototype.copy.call(this, source);
  28547. this.v1.copy(source.v1);
  28548. this.v2.copy(source.v2);
  28549. return this;
  28550. };
  28551. LineCurve3.prototype.toJSON = function () {
  28552. var data = Curve.prototype.toJSON.call(this);
  28553. data.v1 = this.v1.toArray();
  28554. data.v2 = this.v2.toArray();
  28555. return data;
  28556. };
  28557. LineCurve3.prototype.fromJSON = function (json) {
  28558. Curve.prototype.fromJSON.call(this, json);
  28559. this.v1.fromArray(json.v1);
  28560. this.v2.fromArray(json.v2);
  28561. return this;
  28562. };
  28563. function QuadraticBezierCurve(v0, v1, v2) {
  28564. if (v0 === void 0) {
  28565. v0 = new Vector2();
  28566. }
  28567. if (v1 === void 0) {
  28568. v1 = new Vector2();
  28569. }
  28570. if (v2 === void 0) {
  28571. v2 = new Vector2();
  28572. }
  28573. Curve.call(this);
  28574. this.type = 'QuadraticBezierCurve';
  28575. this.v0 = v0;
  28576. this.v1 = v1;
  28577. this.v2 = v2;
  28578. }
  28579. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  28580. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  28581. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  28582. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  28583. if (optionalTarget === void 0) {
  28584. optionalTarget = new Vector2();
  28585. }
  28586. var point = optionalTarget;
  28587. var v0 = this.v0,
  28588. v1 = this.v1,
  28589. v2 = this.v2;
  28590. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  28591. return point;
  28592. };
  28593. QuadraticBezierCurve.prototype.copy = function (source) {
  28594. Curve.prototype.copy.call(this, source);
  28595. this.v0.copy(source.v0);
  28596. this.v1.copy(source.v1);
  28597. this.v2.copy(source.v2);
  28598. return this;
  28599. };
  28600. QuadraticBezierCurve.prototype.toJSON = function () {
  28601. var data = Curve.prototype.toJSON.call(this);
  28602. data.v0 = this.v0.toArray();
  28603. data.v1 = this.v1.toArray();
  28604. data.v2 = this.v2.toArray();
  28605. return data;
  28606. };
  28607. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  28608. Curve.prototype.fromJSON.call(this, json);
  28609. this.v0.fromArray(json.v0);
  28610. this.v1.fromArray(json.v1);
  28611. this.v2.fromArray(json.v2);
  28612. return this;
  28613. };
  28614. function QuadraticBezierCurve3(v0, v1, v2) {
  28615. if (v0 === void 0) {
  28616. v0 = new Vector3();
  28617. }
  28618. if (v1 === void 0) {
  28619. v1 = new Vector3();
  28620. }
  28621. if (v2 === void 0) {
  28622. v2 = new Vector3();
  28623. }
  28624. Curve.call(this);
  28625. this.type = 'QuadraticBezierCurve3';
  28626. this.v0 = v0;
  28627. this.v1 = v1;
  28628. this.v2 = v2;
  28629. }
  28630. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  28631. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  28632. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  28633. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  28634. if (optionalTarget === void 0) {
  28635. optionalTarget = new Vector3();
  28636. }
  28637. var point = optionalTarget;
  28638. var v0 = this.v0,
  28639. v1 = this.v1,
  28640. v2 = this.v2;
  28641. 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));
  28642. return point;
  28643. };
  28644. QuadraticBezierCurve3.prototype.copy = function (source) {
  28645. Curve.prototype.copy.call(this, source);
  28646. this.v0.copy(source.v0);
  28647. this.v1.copy(source.v1);
  28648. this.v2.copy(source.v2);
  28649. return this;
  28650. };
  28651. QuadraticBezierCurve3.prototype.toJSON = function () {
  28652. var data = Curve.prototype.toJSON.call(this);
  28653. data.v0 = this.v0.toArray();
  28654. data.v1 = this.v1.toArray();
  28655. data.v2 = this.v2.toArray();
  28656. return data;
  28657. };
  28658. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  28659. Curve.prototype.fromJSON.call(this, json);
  28660. this.v0.fromArray(json.v0);
  28661. this.v1.fromArray(json.v1);
  28662. this.v2.fromArray(json.v2);
  28663. return this;
  28664. };
  28665. function SplineCurve(points) {
  28666. if (points === void 0) {
  28667. points = [];
  28668. }
  28669. Curve.call(this);
  28670. this.type = 'SplineCurve';
  28671. this.points = points;
  28672. }
  28673. SplineCurve.prototype = Object.create(Curve.prototype);
  28674. SplineCurve.prototype.constructor = SplineCurve;
  28675. SplineCurve.prototype.isSplineCurve = true;
  28676. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  28677. if (optionalTarget === void 0) {
  28678. optionalTarget = new Vector2();
  28679. }
  28680. var point = optionalTarget;
  28681. var points = this.points;
  28682. var p = (points.length - 1) * t;
  28683. var intPoint = Math.floor(p);
  28684. var weight = p - intPoint;
  28685. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  28686. var p1 = points[intPoint];
  28687. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  28688. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  28689. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  28690. return point;
  28691. };
  28692. SplineCurve.prototype.copy = function (source) {
  28693. Curve.prototype.copy.call(this, source);
  28694. this.points = [];
  28695. for (var i = 0, l = source.points.length; i < l; i++) {
  28696. var point = source.points[i];
  28697. this.points.push(point.clone());
  28698. }
  28699. return this;
  28700. };
  28701. SplineCurve.prototype.toJSON = function () {
  28702. var data = Curve.prototype.toJSON.call(this);
  28703. data.points = [];
  28704. for (var i = 0, l = this.points.length; i < l; i++) {
  28705. var point = this.points[i];
  28706. data.points.push(point.toArray());
  28707. }
  28708. return data;
  28709. };
  28710. SplineCurve.prototype.fromJSON = function (json) {
  28711. Curve.prototype.fromJSON.call(this, json);
  28712. this.points = [];
  28713. for (var i = 0, l = json.points.length; i < l; i++) {
  28714. var point = json.points[i];
  28715. this.points.push(new Vector2().fromArray(point));
  28716. }
  28717. return this;
  28718. };
  28719. var Curves = /*#__PURE__*/Object.freeze({
  28720. __proto__: null,
  28721. ArcCurve: ArcCurve,
  28722. CatmullRomCurve3: CatmullRomCurve3,
  28723. CubicBezierCurve: CubicBezierCurve,
  28724. CubicBezierCurve3: CubicBezierCurve3,
  28725. EllipseCurve: EllipseCurve,
  28726. LineCurve: LineCurve,
  28727. LineCurve3: LineCurve3,
  28728. QuadraticBezierCurve: QuadraticBezierCurve,
  28729. QuadraticBezierCurve3: QuadraticBezierCurve3,
  28730. SplineCurve: SplineCurve
  28731. });
  28732. /**************************************************************
  28733. * Curved Path - a curve path is simply a array of connected
  28734. * curves, but retains the api of a curve
  28735. **************************************************************/
  28736. function CurvePath() {
  28737. Curve.call(this);
  28738. this.type = 'CurvePath';
  28739. this.curves = [];
  28740. this.autoClose = false; // Automatically closes the path
  28741. }
  28742. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  28743. constructor: CurvePath,
  28744. add: function add(curve) {
  28745. this.curves.push(curve);
  28746. },
  28747. closePath: function closePath() {
  28748. // Add a line curve if start and end of lines are not connected
  28749. var startPoint = this.curves[0].getPoint(0);
  28750. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  28751. if (!startPoint.equals(endPoint)) {
  28752. this.curves.push(new LineCurve(endPoint, startPoint));
  28753. }
  28754. },
  28755. // To get accurate point with reference to
  28756. // entire path distance at time t,
  28757. // following has to be done:
  28758. // 1. Length of each sub path have to be known
  28759. // 2. Locate and identify type of curve
  28760. // 3. Get t for the curve
  28761. // 4. Return curve.getPointAt(t')
  28762. getPoint: function getPoint(t) {
  28763. var d = t * this.getLength();
  28764. var curveLengths = this.getCurveLengths();
  28765. var i = 0; // To think about boundaries points.
  28766. while (i < curveLengths.length) {
  28767. if (curveLengths[i] >= d) {
  28768. var diff = curveLengths[i] - d;
  28769. var curve = this.curves[i];
  28770. var segmentLength = curve.getLength();
  28771. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  28772. return curve.getPointAt(u);
  28773. }
  28774. i++;
  28775. }
  28776. return null; // loop where sum != 0, sum > d , sum+1 <d
  28777. },
  28778. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  28779. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  28780. // getPoint() depends on getLength
  28781. getLength: function getLength() {
  28782. var lens = this.getCurveLengths();
  28783. return lens[lens.length - 1];
  28784. },
  28785. // cacheLengths must be recalculated.
  28786. updateArcLengths: function updateArcLengths() {
  28787. this.needsUpdate = true;
  28788. this.cacheLengths = null;
  28789. this.getCurveLengths();
  28790. },
  28791. // Compute lengths and cache them
  28792. // We cannot overwrite getLengths() because UtoT mapping uses it.
  28793. getCurveLengths: function getCurveLengths() {
  28794. // We use cache values if curves and cache array are same length
  28795. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  28796. return this.cacheLengths;
  28797. } // Get length of sub-curve
  28798. // Push sums into cached array
  28799. var lengths = [];
  28800. var sums = 0;
  28801. for (var i = 0, l = this.curves.length; i < l; i++) {
  28802. sums += this.curves[i].getLength();
  28803. lengths.push(sums);
  28804. }
  28805. this.cacheLengths = lengths;
  28806. return lengths;
  28807. },
  28808. getSpacedPoints: function getSpacedPoints(divisions) {
  28809. if (divisions === void 0) {
  28810. divisions = 40;
  28811. }
  28812. var points = [];
  28813. for (var i = 0; i <= divisions; i++) {
  28814. points.push(this.getPoint(i / divisions));
  28815. }
  28816. if (this.autoClose) {
  28817. points.push(points[0]);
  28818. }
  28819. return points;
  28820. },
  28821. getPoints: function getPoints(divisions) {
  28822. if (divisions === void 0) {
  28823. divisions = 12;
  28824. }
  28825. var points = [];
  28826. var last;
  28827. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  28828. var curve = curves[i];
  28829. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  28830. var pts = curve.getPoints(resolution);
  28831. for (var j = 0; j < pts.length; j++) {
  28832. var point = pts[j];
  28833. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  28834. points.push(point);
  28835. last = point;
  28836. }
  28837. }
  28838. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  28839. points.push(points[0]);
  28840. }
  28841. return points;
  28842. },
  28843. copy: function copy(source) {
  28844. Curve.prototype.copy.call(this, source);
  28845. this.curves = [];
  28846. for (var i = 0, l = source.curves.length; i < l; i++) {
  28847. var curve = source.curves[i];
  28848. this.curves.push(curve.clone());
  28849. }
  28850. this.autoClose = source.autoClose;
  28851. return this;
  28852. },
  28853. toJSON: function toJSON() {
  28854. var data = Curve.prototype.toJSON.call(this);
  28855. data.autoClose = this.autoClose;
  28856. data.curves = [];
  28857. for (var i = 0, l = this.curves.length; i < l; i++) {
  28858. var curve = this.curves[i];
  28859. data.curves.push(curve.toJSON());
  28860. }
  28861. return data;
  28862. },
  28863. fromJSON: function fromJSON(json) {
  28864. Curve.prototype.fromJSON.call(this, json);
  28865. this.autoClose = json.autoClose;
  28866. this.curves = [];
  28867. for (var i = 0, l = json.curves.length; i < l; i++) {
  28868. var curve = json.curves[i];
  28869. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  28870. }
  28871. return this;
  28872. }
  28873. });
  28874. function Path(points) {
  28875. CurvePath.call(this);
  28876. this.type = 'Path';
  28877. this.currentPoint = new Vector2();
  28878. if (points) {
  28879. this.setFromPoints(points);
  28880. }
  28881. }
  28882. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  28883. constructor: Path,
  28884. setFromPoints: function setFromPoints(points) {
  28885. this.moveTo(points[0].x, points[0].y);
  28886. for (var i = 1, l = points.length; i < l; i++) {
  28887. this.lineTo(points[i].x, points[i].y);
  28888. }
  28889. return this;
  28890. },
  28891. moveTo: function moveTo(x, y) {
  28892. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  28893. return this;
  28894. },
  28895. lineTo: function lineTo(x, y) {
  28896. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  28897. this.curves.push(curve);
  28898. this.currentPoint.set(x, y);
  28899. return this;
  28900. },
  28901. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28902. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  28903. this.curves.push(curve);
  28904. this.currentPoint.set(aX, aY);
  28905. return this;
  28906. },
  28907. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28908. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  28909. this.curves.push(curve);
  28910. this.currentPoint.set(aX, aY);
  28911. return this;
  28912. },
  28913. splineThru: function splineThru(pts
  28914. /*Array of Vector*/
  28915. ) {
  28916. var npts = [this.currentPoint.clone()].concat(pts);
  28917. var curve = new SplineCurve(npts);
  28918. this.curves.push(curve);
  28919. this.currentPoint.copy(pts[pts.length - 1]);
  28920. return this;
  28921. },
  28922. arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28923. var x0 = this.currentPoint.x;
  28924. var y0 = this.currentPoint.y;
  28925. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  28926. return this;
  28927. },
  28928. absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28929. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  28930. return this;
  28931. },
  28932. ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28933. var x0 = this.currentPoint.x;
  28934. var y0 = this.currentPoint.y;
  28935. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  28936. return this;
  28937. },
  28938. absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28939. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  28940. if (this.curves.length > 0) {
  28941. // if a previous curve is present, attempt to join
  28942. var firstPoint = curve.getPoint(0);
  28943. if (!firstPoint.equals(this.currentPoint)) {
  28944. this.lineTo(firstPoint.x, firstPoint.y);
  28945. }
  28946. }
  28947. this.curves.push(curve);
  28948. var lastPoint = curve.getPoint(1);
  28949. this.currentPoint.copy(lastPoint);
  28950. return this;
  28951. },
  28952. copy: function copy(source) {
  28953. CurvePath.prototype.copy.call(this, source);
  28954. this.currentPoint.copy(source.currentPoint);
  28955. return this;
  28956. },
  28957. toJSON: function toJSON() {
  28958. var data = CurvePath.prototype.toJSON.call(this);
  28959. data.currentPoint = this.currentPoint.toArray();
  28960. return data;
  28961. },
  28962. fromJSON: function fromJSON(json) {
  28963. CurvePath.prototype.fromJSON.call(this, json);
  28964. this.currentPoint.fromArray(json.currentPoint);
  28965. return this;
  28966. }
  28967. });
  28968. function Shape(points) {
  28969. Path.call(this, points);
  28970. this.uuid = MathUtils.generateUUID();
  28971. this.type = 'Shape';
  28972. this.holes = [];
  28973. }
  28974. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  28975. constructor: Shape,
  28976. getPointsHoles: function getPointsHoles(divisions) {
  28977. var holesPts = [];
  28978. for (var i = 0, l = this.holes.length; i < l; i++) {
  28979. holesPts[i] = this.holes[i].getPoints(divisions);
  28980. }
  28981. return holesPts;
  28982. },
  28983. // get points of shape and holes (keypoints based on segments parameter)
  28984. extractPoints: function extractPoints(divisions) {
  28985. return {
  28986. shape: this.getPoints(divisions),
  28987. holes: this.getPointsHoles(divisions)
  28988. };
  28989. },
  28990. copy: function copy(source) {
  28991. Path.prototype.copy.call(this, source);
  28992. this.holes = [];
  28993. for (var i = 0, l = source.holes.length; i < l; i++) {
  28994. var hole = source.holes[i];
  28995. this.holes.push(hole.clone());
  28996. }
  28997. return this;
  28998. },
  28999. toJSON: function toJSON() {
  29000. var data = Path.prototype.toJSON.call(this);
  29001. data.uuid = this.uuid;
  29002. data.holes = [];
  29003. for (var i = 0, l = this.holes.length; i < l; i++) {
  29004. var hole = this.holes[i];
  29005. data.holes.push(hole.toJSON());
  29006. }
  29007. return data;
  29008. },
  29009. fromJSON: function fromJSON(json) {
  29010. Path.prototype.fromJSON.call(this, json);
  29011. this.uuid = json.uuid;
  29012. this.holes = [];
  29013. for (var i = 0, l = json.holes.length; i < l; i++) {
  29014. var hole = json.holes[i];
  29015. this.holes.push(new Path().fromJSON(hole));
  29016. }
  29017. return this;
  29018. }
  29019. });
  29020. function Light(color, intensity) {
  29021. if (intensity === void 0) {
  29022. intensity = 1;
  29023. }
  29024. Object3D.call(this);
  29025. this.type = 'Light';
  29026. this.color = new Color(color);
  29027. this.intensity = intensity;
  29028. }
  29029. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  29030. constructor: Light,
  29031. isLight: true,
  29032. copy: function copy(source) {
  29033. Object3D.prototype.copy.call(this, source);
  29034. this.color.copy(source.color);
  29035. this.intensity = source.intensity;
  29036. return this;
  29037. },
  29038. toJSON: function toJSON(meta) {
  29039. var data = Object3D.prototype.toJSON.call(this, meta);
  29040. data.object.color = this.color.getHex();
  29041. data.object.intensity = this.intensity;
  29042. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  29043. if (this.distance !== undefined) data.object.distance = this.distance;
  29044. if (this.angle !== undefined) data.object.angle = this.angle;
  29045. if (this.decay !== undefined) data.object.decay = this.decay;
  29046. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  29047. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  29048. return data;
  29049. }
  29050. });
  29051. function HemisphereLight(skyColor, groundColor, intensity) {
  29052. Light.call(this, skyColor, intensity);
  29053. this.type = 'HemisphereLight';
  29054. this.position.copy(Object3D.DefaultUp);
  29055. this.updateMatrix();
  29056. this.groundColor = new Color(groundColor);
  29057. }
  29058. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  29059. constructor: HemisphereLight,
  29060. isHemisphereLight: true,
  29061. copy: function copy(source) {
  29062. Light.prototype.copy.call(this, source);
  29063. this.groundColor.copy(source.groundColor);
  29064. return this;
  29065. }
  29066. });
  29067. function LightShadow(camera) {
  29068. this.camera = camera;
  29069. this.bias = 0;
  29070. this.normalBias = 0;
  29071. this.radius = 1;
  29072. this.mapSize = new Vector2(512, 512);
  29073. this.map = null;
  29074. this.mapPass = null;
  29075. this.matrix = new Matrix4();
  29076. this.autoUpdate = true;
  29077. this.needsUpdate = false;
  29078. this._frustum = new Frustum();
  29079. this._frameExtents = new Vector2(1, 1);
  29080. this._viewportCount = 1;
  29081. this._viewports = [new Vector4(0, 0, 1, 1)];
  29082. }
  29083. Object.assign(LightShadow.prototype, {
  29084. _projScreenMatrix: new Matrix4(),
  29085. _lightPositionWorld: new Vector3(),
  29086. _lookTarget: new Vector3(),
  29087. getViewportCount: function getViewportCount() {
  29088. return this._viewportCount;
  29089. },
  29090. getFrustum: function getFrustum() {
  29091. return this._frustum;
  29092. },
  29093. updateMatrices: function updateMatrices(light) {
  29094. var shadowCamera = this.camera,
  29095. shadowMatrix = this.matrix,
  29096. projScreenMatrix = this._projScreenMatrix,
  29097. lookTarget = this._lookTarget,
  29098. lightPositionWorld = this._lightPositionWorld;
  29099. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29100. shadowCamera.position.copy(lightPositionWorld);
  29101. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  29102. shadowCamera.lookAt(lookTarget);
  29103. shadowCamera.updateMatrixWorld();
  29104. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  29105. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29106. 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);
  29107. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  29108. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  29109. },
  29110. getViewport: function getViewport(viewportIndex) {
  29111. return this._viewports[viewportIndex];
  29112. },
  29113. getFrameExtents: function getFrameExtents() {
  29114. return this._frameExtents;
  29115. },
  29116. copy: function copy(source) {
  29117. this.camera = source.camera.clone();
  29118. this.bias = source.bias;
  29119. this.radius = source.radius;
  29120. this.mapSize.copy(source.mapSize);
  29121. return this;
  29122. },
  29123. clone: function clone() {
  29124. return new this.constructor().copy(this);
  29125. },
  29126. toJSON: function toJSON() {
  29127. var object = {};
  29128. if (this.bias !== 0) object.bias = this.bias;
  29129. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  29130. if (this.radius !== 1) object.radius = this.radius;
  29131. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  29132. object.camera = this.camera.toJSON(false).object;
  29133. delete object.camera.matrix;
  29134. return object;
  29135. }
  29136. });
  29137. function SpotLightShadow() {
  29138. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  29139. this.focus = 1;
  29140. }
  29141. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29142. constructor: SpotLightShadow,
  29143. isSpotLightShadow: true,
  29144. updateMatrices: function updateMatrices(light) {
  29145. var camera = this.camera;
  29146. var fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  29147. var aspect = this.mapSize.width / this.mapSize.height;
  29148. var far = light.distance || camera.far;
  29149. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  29150. camera.fov = fov;
  29151. camera.aspect = aspect;
  29152. camera.far = far;
  29153. camera.updateProjectionMatrix();
  29154. }
  29155. LightShadow.prototype.updateMatrices.call(this, light);
  29156. }
  29157. });
  29158. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  29159. Light.call(this, color, intensity);
  29160. this.type = 'SpotLight';
  29161. this.position.copy(Object3D.DefaultUp);
  29162. this.updateMatrix();
  29163. this.target = new Object3D();
  29164. Object.defineProperty(this, 'power', {
  29165. get: function get() {
  29166. // intensity = power per solid angle.
  29167. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29168. return this.intensity * Math.PI;
  29169. },
  29170. set: function set(power) {
  29171. // intensity = power per solid angle.
  29172. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29173. this.intensity = power / Math.PI;
  29174. }
  29175. });
  29176. this.distance = distance !== undefined ? distance : 0;
  29177. this.angle = angle !== undefined ? angle : Math.PI / 3;
  29178. this.penumbra = penumbra !== undefined ? penumbra : 0;
  29179. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29180. this.shadow = new SpotLightShadow();
  29181. }
  29182. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  29183. constructor: SpotLight,
  29184. isSpotLight: true,
  29185. copy: function copy(source) {
  29186. Light.prototype.copy.call(this, source);
  29187. this.distance = source.distance;
  29188. this.angle = source.angle;
  29189. this.penumbra = source.penumbra;
  29190. this.decay = source.decay;
  29191. this.target = source.target.clone();
  29192. this.shadow = source.shadow.clone();
  29193. return this;
  29194. }
  29195. });
  29196. function PointLightShadow() {
  29197. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  29198. this._frameExtents = new Vector2(4, 2);
  29199. this._viewportCount = 6;
  29200. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  29201. // following orientation:
  29202. //
  29203. // xzXZ
  29204. // y Y
  29205. //
  29206. // X - Positive x direction
  29207. // x - Negative x direction
  29208. // Y - Positive y direction
  29209. // y - Negative y direction
  29210. // Z - Positive z direction
  29211. // z - Negative z direction
  29212. // positive X
  29213. new Vector4(2, 1, 1, 1), // negative X
  29214. new Vector4(0, 1, 1, 1), // positive Z
  29215. new Vector4(3, 1, 1, 1), // negative Z
  29216. new Vector4(1, 1, 1, 1), // positive Y
  29217. new Vector4(3, 0, 1, 1), // negative Y
  29218. new Vector4(1, 0, 1, 1)];
  29219. 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)];
  29220. 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)];
  29221. }
  29222. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29223. constructor: PointLightShadow,
  29224. isPointLightShadow: true,
  29225. updateMatrices: function updateMatrices(light, viewportIndex) {
  29226. if (viewportIndex === void 0) {
  29227. viewportIndex = 0;
  29228. }
  29229. var camera = this.camera,
  29230. shadowMatrix = this.matrix,
  29231. lightPositionWorld = this._lightPositionWorld,
  29232. lookTarget = this._lookTarget,
  29233. projScreenMatrix = this._projScreenMatrix;
  29234. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29235. camera.position.copy(lightPositionWorld);
  29236. lookTarget.copy(camera.position);
  29237. lookTarget.add(this._cubeDirections[viewportIndex]);
  29238. camera.up.copy(this._cubeUps[viewportIndex]);
  29239. camera.lookAt(lookTarget);
  29240. camera.updateMatrixWorld();
  29241. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  29242. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  29243. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29244. }
  29245. });
  29246. function PointLight(color, intensity, distance, decay) {
  29247. Light.call(this, color, intensity);
  29248. this.type = 'PointLight';
  29249. Object.defineProperty(this, 'power', {
  29250. get: function get() {
  29251. // intensity = power per solid angle.
  29252. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29253. return this.intensity * 4 * Math.PI;
  29254. },
  29255. set: function set(power) {
  29256. // intensity = power per solid angle.
  29257. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29258. this.intensity = power / (4 * Math.PI);
  29259. }
  29260. });
  29261. this.distance = distance !== undefined ? distance : 0;
  29262. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29263. this.shadow = new PointLightShadow();
  29264. }
  29265. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  29266. constructor: PointLight,
  29267. isPointLight: true,
  29268. copy: function copy(source) {
  29269. Light.prototype.copy.call(this, source);
  29270. this.distance = source.distance;
  29271. this.decay = source.decay;
  29272. this.shadow = source.shadow.clone();
  29273. return this;
  29274. }
  29275. });
  29276. function OrthographicCamera(left, right, top, bottom, near, far) {
  29277. if (left === void 0) {
  29278. left = -1;
  29279. }
  29280. if (right === void 0) {
  29281. right = 1;
  29282. }
  29283. if (top === void 0) {
  29284. top = 1;
  29285. }
  29286. if (bottom === void 0) {
  29287. bottom = -1;
  29288. }
  29289. if (near === void 0) {
  29290. near = 0.1;
  29291. }
  29292. if (far === void 0) {
  29293. far = 2000;
  29294. }
  29295. Camera.call(this);
  29296. this.type = 'OrthographicCamera';
  29297. this.zoom = 1;
  29298. this.view = null;
  29299. this.left = left;
  29300. this.right = right;
  29301. this.top = top;
  29302. this.bottom = bottom;
  29303. this.near = near;
  29304. this.far = far;
  29305. this.updateProjectionMatrix();
  29306. }
  29307. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  29308. constructor: OrthographicCamera,
  29309. isOrthographicCamera: true,
  29310. copy: function copy(source, recursive) {
  29311. Camera.prototype.copy.call(this, source, recursive);
  29312. this.left = source.left;
  29313. this.right = source.right;
  29314. this.top = source.top;
  29315. this.bottom = source.bottom;
  29316. this.near = source.near;
  29317. this.far = source.far;
  29318. this.zoom = source.zoom;
  29319. this.view = source.view === null ? null : Object.assign({}, source.view);
  29320. return this;
  29321. },
  29322. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  29323. if (this.view === null) {
  29324. this.view = {
  29325. enabled: true,
  29326. fullWidth: 1,
  29327. fullHeight: 1,
  29328. offsetX: 0,
  29329. offsetY: 0,
  29330. width: 1,
  29331. height: 1
  29332. };
  29333. }
  29334. this.view.enabled = true;
  29335. this.view.fullWidth = fullWidth;
  29336. this.view.fullHeight = fullHeight;
  29337. this.view.offsetX = x;
  29338. this.view.offsetY = y;
  29339. this.view.width = width;
  29340. this.view.height = height;
  29341. this.updateProjectionMatrix();
  29342. },
  29343. clearViewOffset: function clearViewOffset() {
  29344. if (this.view !== null) {
  29345. this.view.enabled = false;
  29346. }
  29347. this.updateProjectionMatrix();
  29348. },
  29349. updateProjectionMatrix: function updateProjectionMatrix() {
  29350. var dx = (this.right - this.left) / (2 * this.zoom);
  29351. var dy = (this.top - this.bottom) / (2 * this.zoom);
  29352. var cx = (this.right + this.left) / 2;
  29353. var cy = (this.top + this.bottom) / 2;
  29354. var left = cx - dx;
  29355. var right = cx + dx;
  29356. var top = cy + dy;
  29357. var bottom = cy - dy;
  29358. if (this.view !== null && this.view.enabled) {
  29359. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  29360. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  29361. left += scaleW * this.view.offsetX;
  29362. right = left + scaleW * this.view.width;
  29363. top -= scaleH * this.view.offsetY;
  29364. bottom = top - scaleH * this.view.height;
  29365. }
  29366. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  29367. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  29368. },
  29369. toJSON: function toJSON(meta) {
  29370. var data = Object3D.prototype.toJSON.call(this, meta);
  29371. data.object.zoom = this.zoom;
  29372. data.object.left = this.left;
  29373. data.object.right = this.right;
  29374. data.object.top = this.top;
  29375. data.object.bottom = this.bottom;
  29376. data.object.near = this.near;
  29377. data.object.far = this.far;
  29378. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  29379. return data;
  29380. }
  29381. });
  29382. function DirectionalLightShadow() {
  29383. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  29384. }
  29385. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29386. constructor: DirectionalLightShadow,
  29387. isDirectionalLightShadow: true,
  29388. updateMatrices: function updateMatrices(light) {
  29389. LightShadow.prototype.updateMatrices.call(this, light);
  29390. }
  29391. });
  29392. function DirectionalLight(color, intensity) {
  29393. Light.call(this, color, intensity);
  29394. this.type = 'DirectionalLight';
  29395. this.position.copy(Object3D.DefaultUp);
  29396. this.updateMatrix();
  29397. this.target = new Object3D();
  29398. this.shadow = new DirectionalLightShadow();
  29399. }
  29400. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  29401. constructor: DirectionalLight,
  29402. isDirectionalLight: true,
  29403. copy: function copy(source) {
  29404. Light.prototype.copy.call(this, source);
  29405. this.target = source.target.clone();
  29406. this.shadow = source.shadow.clone();
  29407. return this;
  29408. }
  29409. });
  29410. function AmbientLight(color, intensity) {
  29411. Light.call(this, color, intensity);
  29412. this.type = 'AmbientLight';
  29413. }
  29414. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  29415. constructor: AmbientLight,
  29416. isAmbientLight: true
  29417. });
  29418. function RectAreaLight(color, intensity, width, height) {
  29419. Light.call(this, color, intensity);
  29420. this.type = 'RectAreaLight';
  29421. this.width = width !== undefined ? width : 10;
  29422. this.height = height !== undefined ? height : 10;
  29423. }
  29424. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  29425. constructor: RectAreaLight,
  29426. isRectAreaLight: true,
  29427. copy: function copy(source) {
  29428. Light.prototype.copy.call(this, source);
  29429. this.width = source.width;
  29430. this.height = source.height;
  29431. return this;
  29432. },
  29433. toJSON: function toJSON(meta) {
  29434. var data = Light.prototype.toJSON.call(this, meta);
  29435. data.object.width = this.width;
  29436. data.object.height = this.height;
  29437. return data;
  29438. }
  29439. });
  29440. /**
  29441. * Primary reference:
  29442. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29443. *
  29444. * Secondary reference:
  29445. * https://www.ppsloan.org/publications/StupidSH36.pdf
  29446. */
  29447. // 3-band SH defined by 9 coefficients
  29448. var SphericalHarmonics3 = /*#__PURE__*/function () {
  29449. function SphericalHarmonics3() {
  29450. Object.defineProperty(this, 'isSphericalHarmonics3', {
  29451. value: true
  29452. });
  29453. this.coefficients = [];
  29454. for (var i = 0; i < 9; i++) {
  29455. this.coefficients.push(new Vector3());
  29456. }
  29457. }
  29458. var _proto = SphericalHarmonics3.prototype;
  29459. _proto.set = function set(coefficients) {
  29460. for (var i = 0; i < 9; i++) {
  29461. this.coefficients[i].copy(coefficients[i]);
  29462. }
  29463. return this;
  29464. };
  29465. _proto.zero = function zero() {
  29466. for (var i = 0; i < 9; i++) {
  29467. this.coefficients[i].set(0, 0, 0);
  29468. }
  29469. return this;
  29470. } // get the radiance in the direction of the normal
  29471. // target is a Vector3
  29472. ;
  29473. _proto.getAt = function getAt(normal, target) {
  29474. // normal is assumed to be unit length
  29475. var x = normal.x,
  29476. y = normal.y,
  29477. z = normal.z;
  29478. var coeff = this.coefficients; // band 0
  29479. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  29480. target.addScaledVector(coeff[1], 0.488603 * y);
  29481. target.addScaledVector(coeff[2], 0.488603 * z);
  29482. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  29483. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  29484. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  29485. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  29486. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  29487. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  29488. return target;
  29489. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  29490. // target is a Vector3
  29491. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29492. ;
  29493. _proto.getIrradianceAt = function getIrradianceAt(normal, target) {
  29494. // normal is assumed to be unit length
  29495. var x = normal.x,
  29496. y = normal.y,
  29497. z = normal.z;
  29498. var coeff = this.coefficients; // band 0
  29499. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  29500. // band 1
  29501. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  29502. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  29503. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  29504. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  29505. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  29506. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  29507. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  29508. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  29509. return target;
  29510. };
  29511. _proto.add = function add(sh) {
  29512. for (var i = 0; i < 9; i++) {
  29513. this.coefficients[i].add(sh.coefficients[i]);
  29514. }
  29515. return this;
  29516. };
  29517. _proto.addScaledSH = function addScaledSH(sh, s) {
  29518. for (var i = 0; i < 9; i++) {
  29519. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  29520. }
  29521. return this;
  29522. };
  29523. _proto.scale = function scale(s) {
  29524. for (var i = 0; i < 9; i++) {
  29525. this.coefficients[i].multiplyScalar(s);
  29526. }
  29527. return this;
  29528. };
  29529. _proto.lerp = function lerp(sh, alpha) {
  29530. for (var i = 0; i < 9; i++) {
  29531. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  29532. }
  29533. return this;
  29534. };
  29535. _proto.equals = function equals(sh) {
  29536. for (var i = 0; i < 9; i++) {
  29537. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  29538. return false;
  29539. }
  29540. }
  29541. return true;
  29542. };
  29543. _proto.copy = function copy(sh) {
  29544. return this.set(sh.coefficients);
  29545. };
  29546. _proto.clone = function clone() {
  29547. return new this.constructor().copy(this);
  29548. };
  29549. _proto.fromArray = function fromArray(array, offset) {
  29550. if (offset === void 0) {
  29551. offset = 0;
  29552. }
  29553. var coefficients = this.coefficients;
  29554. for (var i = 0; i < 9; i++) {
  29555. coefficients[i].fromArray(array, offset + i * 3);
  29556. }
  29557. return this;
  29558. };
  29559. _proto.toArray = function toArray(array, offset) {
  29560. if (array === void 0) {
  29561. array = [];
  29562. }
  29563. if (offset === void 0) {
  29564. offset = 0;
  29565. }
  29566. var coefficients = this.coefficients;
  29567. for (var i = 0; i < 9; i++) {
  29568. coefficients[i].toArray(array, offset + i * 3);
  29569. }
  29570. return array;
  29571. } // evaluate the basis functions
  29572. // shBasis is an Array[ 9 ]
  29573. ;
  29574. SphericalHarmonics3.getBasisAt = function getBasisAt(normal, shBasis) {
  29575. // normal is assumed to be unit length
  29576. var x = normal.x,
  29577. y = normal.y,
  29578. z = normal.z; // band 0
  29579. shBasis[0] = 0.282095; // band 1
  29580. shBasis[1] = 0.488603 * y;
  29581. shBasis[2] = 0.488603 * z;
  29582. shBasis[3] = 0.488603 * x; // band 2
  29583. shBasis[4] = 1.092548 * x * y;
  29584. shBasis[5] = 1.092548 * y * z;
  29585. shBasis[6] = 0.315392 * (3 * z * z - 1);
  29586. shBasis[7] = 1.092548 * x * z;
  29587. shBasis[8] = 0.546274 * (x * x - y * y);
  29588. };
  29589. return SphericalHarmonics3;
  29590. }();
  29591. function LightProbe(sh, intensity) {
  29592. Light.call(this, undefined, intensity);
  29593. this.type = 'LightProbe';
  29594. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  29595. }
  29596. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  29597. constructor: LightProbe,
  29598. isLightProbe: true,
  29599. copy: function copy(source) {
  29600. Light.prototype.copy.call(this, source);
  29601. this.sh.copy(source.sh);
  29602. return this;
  29603. },
  29604. fromJSON: function fromJSON(json) {
  29605. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  29606. this.sh.fromArray(json.sh);
  29607. return this;
  29608. },
  29609. toJSON: function toJSON(meta) {
  29610. var data = Light.prototype.toJSON.call(this, meta);
  29611. data.object.sh = this.sh.toArray();
  29612. return data;
  29613. }
  29614. });
  29615. function MaterialLoader(manager) {
  29616. Loader.call(this, manager);
  29617. this.textures = {};
  29618. }
  29619. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  29620. constructor: MaterialLoader,
  29621. load: function load(url, onLoad, onProgress, onError) {
  29622. var scope = this;
  29623. var loader = new FileLoader(scope.manager);
  29624. loader.setPath(scope.path);
  29625. loader.setRequestHeader(scope.requestHeader);
  29626. loader.setWithCredentials(scope.withCredentials);
  29627. loader.load(url, function (text) {
  29628. try {
  29629. onLoad(scope.parse(JSON.parse(text)));
  29630. } catch (e) {
  29631. if (onError) {
  29632. onError(e);
  29633. } else {
  29634. console.error(e);
  29635. }
  29636. scope.manager.itemError(url);
  29637. }
  29638. }, onProgress, onError);
  29639. },
  29640. parse: function parse(json) {
  29641. var textures = this.textures;
  29642. function getTexture(name) {
  29643. if (textures[name] === undefined) {
  29644. console.warn('THREE.MaterialLoader: Undefined texture', name);
  29645. }
  29646. return textures[name];
  29647. }
  29648. var material = new Materials[json.type]();
  29649. if (json.uuid !== undefined) material.uuid = json.uuid;
  29650. if (json.name !== undefined) material.name = json.name;
  29651. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  29652. if (json.roughness !== undefined) material.roughness = json.roughness;
  29653. if (json.metalness !== undefined) material.metalness = json.metalness;
  29654. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  29655. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  29656. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  29657. if (json.shininess !== undefined) material.shininess = json.shininess;
  29658. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  29659. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  29660. if (json.fog !== undefined) material.fog = json.fog;
  29661. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  29662. if (json.blending !== undefined) material.blending = json.blending;
  29663. if (json.combine !== undefined) material.combine = json.combine;
  29664. if (json.side !== undefined) material.side = json.side;
  29665. if (json.opacity !== undefined) material.opacity = json.opacity;
  29666. if (json.transparent !== undefined) material.transparent = json.transparent;
  29667. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  29668. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  29669. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  29670. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  29671. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  29672. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  29673. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  29674. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  29675. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  29676. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  29677. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  29678. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  29679. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  29680. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  29681. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  29682. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  29683. if (json.rotation !== undefined) material.rotation = json.rotation;
  29684. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  29685. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  29686. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  29687. if (json.scale !== undefined) material.scale = json.scale;
  29688. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  29689. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  29690. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  29691. if (json.skinning !== undefined) material.skinning = json.skinning;
  29692. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  29693. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  29694. if (json.dithering !== undefined) material.dithering = json.dithering;
  29695. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  29696. if (json.visible !== undefined) material.visible = json.visible;
  29697. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  29698. if (json.userData !== undefined) material.userData = json.userData;
  29699. if (json.vertexColors !== undefined) {
  29700. if (typeof json.vertexColors === 'number') {
  29701. material.vertexColors = json.vertexColors > 0 ? true : false;
  29702. } else {
  29703. material.vertexColors = json.vertexColors;
  29704. }
  29705. } // Shader Material
  29706. if (json.uniforms !== undefined) {
  29707. for (var name in json.uniforms) {
  29708. var uniform = json.uniforms[name];
  29709. material.uniforms[name] = {};
  29710. switch (uniform.type) {
  29711. case 't':
  29712. material.uniforms[name].value = getTexture(uniform.value);
  29713. break;
  29714. case 'c':
  29715. material.uniforms[name].value = new Color().setHex(uniform.value);
  29716. break;
  29717. case 'v2':
  29718. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  29719. break;
  29720. case 'v3':
  29721. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  29722. break;
  29723. case 'v4':
  29724. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  29725. break;
  29726. case 'm3':
  29727. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  29728. break;
  29729. case 'm4':
  29730. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  29731. break;
  29732. default:
  29733. material.uniforms[name].value = uniform.value;
  29734. }
  29735. }
  29736. }
  29737. if (json.defines !== undefined) material.defines = json.defines;
  29738. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  29739. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  29740. if (json.extensions !== undefined) {
  29741. for (var key in json.extensions) {
  29742. material.extensions[key] = json.extensions[key];
  29743. }
  29744. } // Deprecated
  29745. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  29746. // for PointsMaterial
  29747. if (json.size !== undefined) material.size = json.size;
  29748. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  29749. if (json.map !== undefined) material.map = getTexture(json.map);
  29750. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  29751. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  29752. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  29753. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  29754. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  29755. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  29756. if (json.normalScale !== undefined) {
  29757. var normalScale = json.normalScale;
  29758. if (Array.isArray(normalScale) === false) {
  29759. // Blender exporter used to export a scalar. See #7459
  29760. normalScale = [normalScale, normalScale];
  29761. }
  29762. material.normalScale = new Vector2().fromArray(normalScale);
  29763. }
  29764. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  29765. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  29766. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  29767. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  29768. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  29769. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  29770. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  29771. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  29772. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  29773. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  29774. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  29775. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  29776. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  29777. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  29778. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  29779. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  29780. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  29781. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  29782. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  29783. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  29784. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  29785. if (json.transmission !== undefined) material.transmission = json.transmission;
  29786. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  29787. return material;
  29788. },
  29789. setTextures: function setTextures(value) {
  29790. this.textures = value;
  29791. return this;
  29792. }
  29793. });
  29794. var LoaderUtils = {
  29795. decodeText: function decodeText(array) {
  29796. if (typeof TextDecoder !== 'undefined') {
  29797. return new TextDecoder().decode(array);
  29798. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  29799. // throws a "maximum call stack size exceeded" error for large arrays.
  29800. var s = '';
  29801. for (var i = 0, il = array.length; i < il; i++) {
  29802. // Implicitly assumes little-endian.
  29803. s += String.fromCharCode(array[i]);
  29804. }
  29805. try {
  29806. // merges multi-byte utf-8 characters.
  29807. return decodeURIComponent(escape(s));
  29808. } catch (e) {
  29809. // see #16358
  29810. return s;
  29811. }
  29812. },
  29813. extractUrlBase: function extractUrlBase(url) {
  29814. var index = url.lastIndexOf('/');
  29815. if (index === -1) return './';
  29816. return url.substr(0, index + 1);
  29817. }
  29818. };
  29819. function InstancedBufferGeometry() {
  29820. BufferGeometry.call(this);
  29821. this.type = 'InstancedBufferGeometry';
  29822. this.instanceCount = Infinity;
  29823. }
  29824. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  29825. constructor: InstancedBufferGeometry,
  29826. isInstancedBufferGeometry: true,
  29827. copy: function copy(source) {
  29828. BufferGeometry.prototype.copy.call(this, source);
  29829. this.instanceCount = source.instanceCount;
  29830. return this;
  29831. },
  29832. clone: function clone() {
  29833. return new this.constructor().copy(this);
  29834. },
  29835. toJSON: function toJSON() {
  29836. var data = BufferGeometry.prototype.toJSON.call(this);
  29837. data.instanceCount = this.instanceCount;
  29838. data.isInstancedBufferGeometry = true;
  29839. return data;
  29840. }
  29841. });
  29842. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  29843. if (typeof normalized === 'number') {
  29844. meshPerAttribute = normalized;
  29845. normalized = false;
  29846. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  29847. }
  29848. BufferAttribute.call(this, array, itemSize, normalized);
  29849. this.meshPerAttribute = meshPerAttribute || 1;
  29850. }
  29851. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  29852. constructor: InstancedBufferAttribute,
  29853. isInstancedBufferAttribute: true,
  29854. copy: function copy(source) {
  29855. BufferAttribute.prototype.copy.call(this, source);
  29856. this.meshPerAttribute = source.meshPerAttribute;
  29857. return this;
  29858. },
  29859. toJSON: function toJSON() {
  29860. var data = BufferAttribute.prototype.toJSON.call(this);
  29861. data.meshPerAttribute = this.meshPerAttribute;
  29862. data.isInstancedBufferAttribute = true;
  29863. return data;
  29864. }
  29865. });
  29866. function BufferGeometryLoader(manager) {
  29867. Loader.call(this, manager);
  29868. }
  29869. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  29870. constructor: BufferGeometryLoader,
  29871. load: function load(url, onLoad, onProgress, onError) {
  29872. var scope = this;
  29873. var loader = new FileLoader(scope.manager);
  29874. loader.setPath(scope.path);
  29875. loader.setRequestHeader(scope.requestHeader);
  29876. loader.setWithCredentials(scope.withCredentials);
  29877. loader.load(url, function (text) {
  29878. try {
  29879. onLoad(scope.parse(JSON.parse(text)));
  29880. } catch (e) {
  29881. if (onError) {
  29882. onError(e);
  29883. } else {
  29884. console.error(e);
  29885. }
  29886. scope.manager.itemError(url);
  29887. }
  29888. }, onProgress, onError);
  29889. },
  29890. parse: function parse(json) {
  29891. var interleavedBufferMap = {};
  29892. var arrayBufferMap = {};
  29893. function getInterleavedBuffer(json, uuid) {
  29894. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  29895. var interleavedBuffers = json.interleavedBuffers;
  29896. var interleavedBuffer = interleavedBuffers[uuid];
  29897. var buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  29898. var array = getTypedArray(interleavedBuffer.type, buffer);
  29899. var ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  29900. ib.uuid = interleavedBuffer.uuid;
  29901. interleavedBufferMap[uuid] = ib;
  29902. return ib;
  29903. }
  29904. function getArrayBuffer(json, uuid) {
  29905. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  29906. var arrayBuffers = json.arrayBuffers;
  29907. var arrayBuffer = arrayBuffers[uuid];
  29908. var ab = new Uint32Array(arrayBuffer).buffer;
  29909. arrayBufferMap[uuid] = ab;
  29910. return ab;
  29911. }
  29912. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  29913. var index = json.data.index;
  29914. if (index !== undefined) {
  29915. var typedArray = getTypedArray(index.type, index.array);
  29916. geometry.setIndex(new BufferAttribute(typedArray, 1));
  29917. }
  29918. var attributes = json.data.attributes;
  29919. for (var key in attributes) {
  29920. var attribute = attributes[key];
  29921. var bufferAttribute = void 0;
  29922. if (attribute.isInterleavedBufferAttribute) {
  29923. var interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  29924. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  29925. } else {
  29926. var _typedArray = getTypedArray(attribute.type, attribute.array);
  29927. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  29928. bufferAttribute = new bufferAttributeConstr(_typedArray, attribute.itemSize, attribute.normalized);
  29929. }
  29930. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  29931. geometry.setAttribute(key, bufferAttribute);
  29932. }
  29933. var morphAttributes = json.data.morphAttributes;
  29934. if (morphAttributes) {
  29935. for (var _key in morphAttributes) {
  29936. var attributeArray = morphAttributes[_key];
  29937. var array = [];
  29938. for (var i = 0, il = attributeArray.length; i < il; i++) {
  29939. var _attribute = attributeArray[i];
  29940. var _bufferAttribute = void 0;
  29941. if (_attribute.isInterleavedBufferAttribute) {
  29942. var _interleavedBuffer = getInterleavedBuffer(json.data, _attribute.data);
  29943. _bufferAttribute = new InterleavedBufferAttribute(_interleavedBuffer, _attribute.itemSize, _attribute.offset, _attribute.normalized);
  29944. } else {
  29945. var _typedArray2 = getTypedArray(_attribute.type, _attribute.array);
  29946. _bufferAttribute = new BufferAttribute(_typedArray2, _attribute.itemSize, _attribute.normalized);
  29947. }
  29948. if (_attribute.name !== undefined) _bufferAttribute.name = _attribute.name;
  29949. array.push(_bufferAttribute);
  29950. }
  29951. geometry.morphAttributes[_key] = array;
  29952. }
  29953. }
  29954. var morphTargetsRelative = json.data.morphTargetsRelative;
  29955. if (morphTargetsRelative) {
  29956. geometry.morphTargetsRelative = true;
  29957. }
  29958. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  29959. if (groups !== undefined) {
  29960. for (var _i = 0, n = groups.length; _i !== n; ++_i) {
  29961. var group = groups[_i];
  29962. geometry.addGroup(group.start, group.count, group.materialIndex);
  29963. }
  29964. }
  29965. var boundingSphere = json.data.boundingSphere;
  29966. if (boundingSphere !== undefined) {
  29967. var center = new Vector3();
  29968. if (boundingSphere.center !== undefined) {
  29969. center.fromArray(boundingSphere.center);
  29970. }
  29971. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  29972. }
  29973. if (json.name) geometry.name = json.name;
  29974. if (json.userData) geometry.userData = json.userData;
  29975. return geometry;
  29976. }
  29977. });
  29978. var ObjectLoader = /*#__PURE__*/function (_Loader) {
  29979. _inheritsLoose(ObjectLoader, _Loader);
  29980. function ObjectLoader(manager) {
  29981. return _Loader.call(this, manager) || this;
  29982. }
  29983. var _proto = ObjectLoader.prototype;
  29984. _proto.load = function load(url, onLoad, onProgress, onError) {
  29985. var scope = this;
  29986. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  29987. this.resourcePath = this.resourcePath || path;
  29988. var loader = new FileLoader(this.manager);
  29989. loader.setPath(this.path);
  29990. loader.setRequestHeader(this.requestHeader);
  29991. loader.setWithCredentials(this.withCredentials);
  29992. loader.load(url, function (text) {
  29993. var json = null;
  29994. try {
  29995. json = JSON.parse(text);
  29996. } catch (error) {
  29997. if (onError !== undefined) onError(error);
  29998. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  29999. return;
  30000. }
  30001. var metadata = json.metadata;
  30002. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  30003. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  30004. return;
  30005. }
  30006. scope.parse(json, onLoad);
  30007. }, onProgress, onError);
  30008. };
  30009. _proto.parse = function parse(json, onLoad) {
  30010. var animations = this.parseAnimations(json.animations);
  30011. var shapes = this.parseShapes(json.shapes);
  30012. var geometries = this.parseGeometries(json.geometries, shapes);
  30013. var images = this.parseImages(json.images, function () {
  30014. if (onLoad !== undefined) onLoad(object);
  30015. });
  30016. var textures = this.parseTextures(json.textures, images);
  30017. var materials = this.parseMaterials(json.materials, textures);
  30018. var object = this.parseObject(json.object, geometries, materials, animations);
  30019. var skeletons = this.parseSkeletons(json.skeletons, object);
  30020. this.bindSkeletons(object, skeletons); //
  30021. if (onLoad !== undefined) {
  30022. var hasImages = false;
  30023. for (var uuid in images) {
  30024. if (images[uuid] instanceof HTMLImageElement) {
  30025. hasImages = true;
  30026. break;
  30027. }
  30028. }
  30029. if (hasImages === false) onLoad(object);
  30030. }
  30031. return object;
  30032. };
  30033. _proto.parseShapes = function parseShapes(json) {
  30034. var shapes = {};
  30035. if (json !== undefined) {
  30036. for (var i = 0, l = json.length; i < l; i++) {
  30037. var shape = new Shape().fromJSON(json[i]);
  30038. shapes[shape.uuid] = shape;
  30039. }
  30040. }
  30041. return shapes;
  30042. };
  30043. _proto.parseSkeletons = function parseSkeletons(json, object) {
  30044. var skeletons = {};
  30045. var bones = {}; // generate bone lookup table
  30046. object.traverse(function (child) {
  30047. if (child.isBone) bones[child.uuid] = child;
  30048. }); // create skeletons
  30049. if (json !== undefined) {
  30050. for (var i = 0, l = json.length; i < l; i++) {
  30051. var skeleton = new Skeleton().fromJSON(json[i], bones);
  30052. skeletons[skeleton.uuid] = skeleton;
  30053. }
  30054. }
  30055. return skeletons;
  30056. };
  30057. _proto.parseGeometries = function parseGeometries(json, shapes) {
  30058. var geometries = {};
  30059. var geometryShapes;
  30060. if (json !== undefined) {
  30061. var bufferGeometryLoader = new BufferGeometryLoader();
  30062. for (var i = 0, l = json.length; i < l; i++) {
  30063. var geometry = void 0;
  30064. var data = json[i];
  30065. switch (data.type) {
  30066. case 'PlaneGeometry':
  30067. case 'PlaneBufferGeometry':
  30068. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  30069. break;
  30070. case 'BoxGeometry':
  30071. case 'BoxBufferGeometry':
  30072. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  30073. break;
  30074. case 'CircleGeometry':
  30075. case 'CircleBufferGeometry':
  30076. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  30077. break;
  30078. case 'CylinderGeometry':
  30079. case 'CylinderBufferGeometry':
  30080. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30081. break;
  30082. case 'ConeGeometry':
  30083. case 'ConeBufferGeometry':
  30084. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30085. break;
  30086. case 'SphereGeometry':
  30087. case 'SphereBufferGeometry':
  30088. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  30089. break;
  30090. case 'DodecahedronGeometry':
  30091. case 'DodecahedronBufferGeometry':
  30092. case 'IcosahedronGeometry':
  30093. case 'IcosahedronBufferGeometry':
  30094. case 'OctahedronGeometry':
  30095. case 'OctahedronBufferGeometry':
  30096. case 'TetrahedronGeometry':
  30097. case 'TetrahedronBufferGeometry':
  30098. geometry = new Geometries[data.type](data.radius, data.detail);
  30099. break;
  30100. case 'RingGeometry':
  30101. case 'RingBufferGeometry':
  30102. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  30103. break;
  30104. case 'TorusGeometry':
  30105. case 'TorusBufferGeometry':
  30106. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  30107. break;
  30108. case 'TorusKnotGeometry':
  30109. case 'TorusKnotBufferGeometry':
  30110. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  30111. break;
  30112. case 'TubeGeometry':
  30113. case 'TubeBufferGeometry':
  30114. // This only works for built-in curves (e.g. CatmullRomCurve3).
  30115. // User defined curves or instances of CurvePath will not be deserialized.
  30116. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  30117. break;
  30118. case 'LatheGeometry':
  30119. case 'LatheBufferGeometry':
  30120. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  30121. break;
  30122. case 'PolyhedronGeometry':
  30123. case 'PolyhedronBufferGeometry':
  30124. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  30125. break;
  30126. case 'ShapeGeometry':
  30127. case 'ShapeBufferGeometry':
  30128. geometryShapes = [];
  30129. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  30130. var shape = shapes[data.shapes[j]];
  30131. geometryShapes.push(shape);
  30132. }
  30133. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  30134. break;
  30135. case 'ExtrudeGeometry':
  30136. case 'ExtrudeBufferGeometry':
  30137. geometryShapes = [];
  30138. for (var _j = 0, _jl = data.shapes.length; _j < _jl; _j++) {
  30139. var _shape = shapes[data.shapes[_j]];
  30140. geometryShapes.push(_shape);
  30141. }
  30142. var extrudePath = data.options.extrudePath;
  30143. if (extrudePath !== undefined) {
  30144. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  30145. }
  30146. geometry = new Geometries[data.type](geometryShapes, data.options);
  30147. break;
  30148. case 'BufferGeometry':
  30149. case 'InstancedBufferGeometry':
  30150. geometry = bufferGeometryLoader.parse(data);
  30151. break;
  30152. case 'Geometry':
  30153. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  30154. var geometryLoader = new THREE.LegacyJSONLoader();
  30155. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  30156. } else {
  30157. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  30158. }
  30159. break;
  30160. default:
  30161. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  30162. continue;
  30163. }
  30164. geometry.uuid = data.uuid;
  30165. if (data.name !== undefined) geometry.name = data.name;
  30166. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  30167. geometries[data.uuid] = geometry;
  30168. }
  30169. }
  30170. return geometries;
  30171. };
  30172. _proto.parseMaterials = function parseMaterials(json, textures) {
  30173. var cache = {}; // MultiMaterial
  30174. var materials = {};
  30175. if (json !== undefined) {
  30176. var loader = new MaterialLoader();
  30177. loader.setTextures(textures);
  30178. for (var i = 0, l = json.length; i < l; i++) {
  30179. var data = json[i];
  30180. if (data.type === 'MultiMaterial') {
  30181. // Deprecated
  30182. var array = [];
  30183. for (var j = 0; j < data.materials.length; j++) {
  30184. var material = data.materials[j];
  30185. if (cache[material.uuid] === undefined) {
  30186. cache[material.uuid] = loader.parse(material);
  30187. }
  30188. array.push(cache[material.uuid]);
  30189. }
  30190. materials[data.uuid] = array;
  30191. } else {
  30192. if (cache[data.uuid] === undefined) {
  30193. cache[data.uuid] = loader.parse(data);
  30194. }
  30195. materials[data.uuid] = cache[data.uuid];
  30196. }
  30197. }
  30198. }
  30199. return materials;
  30200. };
  30201. _proto.parseAnimations = function parseAnimations(json) {
  30202. var animations = {};
  30203. if (json !== undefined) {
  30204. for (var i = 0; i < json.length; i++) {
  30205. var data = json[i];
  30206. var clip = AnimationClip.parse(data);
  30207. animations[clip.uuid] = clip;
  30208. }
  30209. }
  30210. return animations;
  30211. };
  30212. _proto.parseImages = function parseImages(json, onLoad) {
  30213. var scope = this;
  30214. var images = {};
  30215. var loader;
  30216. function loadImage(url) {
  30217. scope.manager.itemStart(url);
  30218. return loader.load(url, function () {
  30219. scope.manager.itemEnd(url);
  30220. }, undefined, function () {
  30221. scope.manager.itemError(url);
  30222. scope.manager.itemEnd(url);
  30223. });
  30224. }
  30225. function deserializeImage(image) {
  30226. if (typeof image === 'string') {
  30227. var url = image;
  30228. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  30229. return loadImage(path);
  30230. } else {
  30231. if (image.data) {
  30232. return {
  30233. data: getTypedArray(image.type, image.data),
  30234. width: image.width,
  30235. height: image.height
  30236. };
  30237. } else {
  30238. return null;
  30239. }
  30240. }
  30241. }
  30242. if (json !== undefined && json.length > 0) {
  30243. var manager = new LoadingManager(onLoad);
  30244. loader = new ImageLoader(manager);
  30245. loader.setCrossOrigin(this.crossOrigin);
  30246. for (var i = 0, il = json.length; i < il; i++) {
  30247. var image = json[i];
  30248. var url = image.url;
  30249. if (Array.isArray(url)) {
  30250. // load array of images e.g CubeTexture
  30251. images[image.uuid] = [];
  30252. for (var j = 0, jl = url.length; j < jl; j++) {
  30253. var currentUrl = url[j];
  30254. var deserializedImage = deserializeImage(currentUrl);
  30255. if (deserializedImage !== null) {
  30256. if (deserializedImage instanceof HTMLImageElement) {
  30257. images[image.uuid].push(deserializedImage);
  30258. } else {
  30259. // special case: handle array of data textures for cube textures
  30260. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  30261. }
  30262. }
  30263. }
  30264. } else {
  30265. // load single image
  30266. var _deserializedImage = deserializeImage(image.url);
  30267. if (_deserializedImage !== null) {
  30268. images[image.uuid] = _deserializedImage;
  30269. }
  30270. }
  30271. }
  30272. }
  30273. return images;
  30274. };
  30275. _proto.parseTextures = function parseTextures(json, images) {
  30276. function parseConstant(value, type) {
  30277. if (typeof value === 'number') return value;
  30278. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  30279. return type[value];
  30280. }
  30281. var textures = {};
  30282. if (json !== undefined) {
  30283. for (var i = 0, l = json.length; i < l; i++) {
  30284. var data = json[i];
  30285. if (data.image === undefined) {
  30286. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  30287. }
  30288. if (images[data.image] === undefined) {
  30289. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  30290. }
  30291. var texture = void 0;
  30292. var image = images[data.image];
  30293. if (Array.isArray(image)) {
  30294. texture = new CubeTexture(image);
  30295. if (image.length === 6) texture.needsUpdate = true;
  30296. } else {
  30297. if (image && image.data) {
  30298. texture = new DataTexture(image.data, image.width, image.height);
  30299. } else {
  30300. texture = new Texture(image);
  30301. }
  30302. if (image) texture.needsUpdate = true; // textures can have undefined image data
  30303. }
  30304. texture.uuid = data.uuid;
  30305. if (data.name !== undefined) texture.name = data.name;
  30306. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  30307. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  30308. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  30309. if (data.center !== undefined) texture.center.fromArray(data.center);
  30310. if (data.rotation !== undefined) texture.rotation = data.rotation;
  30311. if (data.wrap !== undefined) {
  30312. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  30313. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  30314. }
  30315. if (data.format !== undefined) texture.format = data.format;
  30316. if (data.type !== undefined) texture.type = data.type;
  30317. if (data.encoding !== undefined) texture.encoding = data.encoding;
  30318. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  30319. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  30320. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  30321. if (data.flipY !== undefined) texture.flipY = data.flipY;
  30322. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  30323. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  30324. textures[data.uuid] = texture;
  30325. }
  30326. }
  30327. return textures;
  30328. };
  30329. _proto.parseObject = function parseObject(data, geometries, materials, animations) {
  30330. var object;
  30331. function getGeometry(name) {
  30332. if (geometries[name] === undefined) {
  30333. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  30334. }
  30335. return geometries[name];
  30336. }
  30337. function getMaterial(name) {
  30338. if (name === undefined) return undefined;
  30339. if (Array.isArray(name)) {
  30340. var array = [];
  30341. for (var i = 0, l = name.length; i < l; i++) {
  30342. var uuid = name[i];
  30343. if (materials[uuid] === undefined) {
  30344. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  30345. }
  30346. array.push(materials[uuid]);
  30347. }
  30348. return array;
  30349. }
  30350. if (materials[name] === undefined) {
  30351. console.warn('THREE.ObjectLoader: Undefined material', name);
  30352. }
  30353. return materials[name];
  30354. }
  30355. var geometry, material;
  30356. switch (data.type) {
  30357. case 'Scene':
  30358. object = new Scene();
  30359. if (data.background !== undefined) {
  30360. if (Number.isInteger(data.background)) {
  30361. object.background = new Color(data.background);
  30362. }
  30363. }
  30364. if (data.fog !== undefined) {
  30365. if (data.fog.type === 'Fog') {
  30366. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  30367. } else if (data.fog.type === 'FogExp2') {
  30368. object.fog = new FogExp2(data.fog.color, data.fog.density);
  30369. }
  30370. }
  30371. break;
  30372. case 'PerspectiveCamera':
  30373. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  30374. if (data.focus !== undefined) object.focus = data.focus;
  30375. if (data.zoom !== undefined) object.zoom = data.zoom;
  30376. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  30377. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  30378. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30379. break;
  30380. case 'OrthographicCamera':
  30381. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  30382. if (data.zoom !== undefined) object.zoom = data.zoom;
  30383. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30384. break;
  30385. case 'AmbientLight':
  30386. object = new AmbientLight(data.color, data.intensity);
  30387. break;
  30388. case 'DirectionalLight':
  30389. object = new DirectionalLight(data.color, data.intensity);
  30390. break;
  30391. case 'PointLight':
  30392. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  30393. break;
  30394. case 'RectAreaLight':
  30395. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  30396. break;
  30397. case 'SpotLight':
  30398. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  30399. break;
  30400. case 'HemisphereLight':
  30401. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  30402. break;
  30403. case 'LightProbe':
  30404. object = new LightProbe().fromJSON(data);
  30405. break;
  30406. case 'SkinnedMesh':
  30407. geometry = getGeometry(data.geometry);
  30408. material = getMaterial(data.material);
  30409. object = new SkinnedMesh(geometry, material);
  30410. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  30411. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  30412. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  30413. break;
  30414. case 'Mesh':
  30415. geometry = getGeometry(data.geometry);
  30416. material = getMaterial(data.material);
  30417. object = new Mesh(geometry, material);
  30418. break;
  30419. case 'InstancedMesh':
  30420. geometry = getGeometry(data.geometry);
  30421. material = getMaterial(data.material);
  30422. var count = data.count;
  30423. var instanceMatrix = data.instanceMatrix;
  30424. object = new InstancedMesh(geometry, material, count);
  30425. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  30426. break;
  30427. case 'LOD':
  30428. object = new LOD();
  30429. break;
  30430. case 'Line':
  30431. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  30432. break;
  30433. case 'LineLoop':
  30434. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  30435. break;
  30436. case 'LineSegments':
  30437. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  30438. break;
  30439. case 'PointCloud':
  30440. case 'Points':
  30441. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  30442. break;
  30443. case 'Sprite':
  30444. object = new Sprite(getMaterial(data.material));
  30445. break;
  30446. case 'Group':
  30447. object = new Group();
  30448. break;
  30449. case 'Bone':
  30450. object = new Bone();
  30451. break;
  30452. default:
  30453. object = new Object3D();
  30454. }
  30455. object.uuid = data.uuid;
  30456. if (data.name !== undefined) object.name = data.name;
  30457. if (data.matrix !== undefined) {
  30458. object.matrix.fromArray(data.matrix);
  30459. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  30460. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  30461. } else {
  30462. if (data.position !== undefined) object.position.fromArray(data.position);
  30463. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  30464. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  30465. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  30466. }
  30467. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  30468. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  30469. if (data.shadow) {
  30470. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  30471. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  30472. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  30473. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  30474. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  30475. }
  30476. if (data.visible !== undefined) object.visible = data.visible;
  30477. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  30478. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  30479. if (data.userData !== undefined) object.userData = data.userData;
  30480. if (data.layers !== undefined) object.layers.mask = data.layers;
  30481. if (data.children !== undefined) {
  30482. var children = data.children;
  30483. for (var i = 0; i < children.length; i++) {
  30484. object.add(this.parseObject(children[i], geometries, materials, animations));
  30485. }
  30486. }
  30487. if (data.animations !== undefined) {
  30488. var objectAnimations = data.animations;
  30489. for (var _i = 0; _i < objectAnimations.length; _i++) {
  30490. var uuid = objectAnimations[_i];
  30491. object.animations.push(animations[uuid]);
  30492. }
  30493. }
  30494. if (data.type === 'LOD') {
  30495. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  30496. var levels = data.levels;
  30497. for (var l = 0; l < levels.length; l++) {
  30498. var level = levels[l];
  30499. var child = object.getObjectByProperty('uuid', level.object);
  30500. if (child !== undefined) {
  30501. object.addLevel(child, level.distance);
  30502. }
  30503. }
  30504. }
  30505. return object;
  30506. };
  30507. _proto.bindSkeletons = function bindSkeletons(object, skeletons) {
  30508. if (Object.keys(skeletons).length === 0) return;
  30509. object.traverse(function (child) {
  30510. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  30511. var skeleton = skeletons[child.skeleton];
  30512. if (skeleton === undefined) {
  30513. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  30514. } else {
  30515. child.bind(skeleton, child.bindMatrix);
  30516. }
  30517. }
  30518. });
  30519. }
  30520. /* DEPRECATED */
  30521. ;
  30522. _proto.setTexturePath = function setTexturePath(value) {
  30523. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  30524. return this.setResourcePath(value);
  30525. };
  30526. return ObjectLoader;
  30527. }(Loader);
  30528. var TEXTURE_MAPPING = {
  30529. UVMapping: UVMapping,
  30530. CubeReflectionMapping: CubeReflectionMapping,
  30531. CubeRefractionMapping: CubeRefractionMapping,
  30532. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30533. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30534. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30535. CubeUVRefractionMapping: CubeUVRefractionMapping
  30536. };
  30537. var TEXTURE_WRAPPING = {
  30538. RepeatWrapping: RepeatWrapping,
  30539. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30540. MirroredRepeatWrapping: MirroredRepeatWrapping
  30541. };
  30542. var TEXTURE_FILTER = {
  30543. NearestFilter: NearestFilter,
  30544. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30545. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30546. LinearFilter: LinearFilter,
  30547. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30548. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  30549. };
  30550. function ImageBitmapLoader(manager) {
  30551. if (typeof createImageBitmap === 'undefined') {
  30552. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  30553. }
  30554. if (typeof fetch === 'undefined') {
  30555. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  30556. }
  30557. Loader.call(this, manager);
  30558. this.options = {
  30559. premultiplyAlpha: 'none'
  30560. };
  30561. }
  30562. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30563. constructor: ImageBitmapLoader,
  30564. isImageBitmapLoader: true,
  30565. setOptions: function setOptions(options) {
  30566. this.options = options;
  30567. return this;
  30568. },
  30569. load: function load(url, onLoad, onProgress, onError) {
  30570. if (url === undefined) url = '';
  30571. if (this.path !== undefined) url = this.path + url;
  30572. url = this.manager.resolveURL(url);
  30573. var scope = this;
  30574. var cached = Cache.get(url);
  30575. if (cached !== undefined) {
  30576. scope.manager.itemStart(url);
  30577. setTimeout(function () {
  30578. if (onLoad) onLoad(cached);
  30579. scope.manager.itemEnd(url);
  30580. }, 0);
  30581. return cached;
  30582. }
  30583. var fetchOptions = {};
  30584. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  30585. fetch(url, fetchOptions).then(function (res) {
  30586. return res.blob();
  30587. }).then(function (blob) {
  30588. return createImageBitmap(blob, scope.options);
  30589. }).then(function (imageBitmap) {
  30590. Cache.add(url, imageBitmap);
  30591. if (onLoad) onLoad(imageBitmap);
  30592. scope.manager.itemEnd(url);
  30593. }).catch(function (e) {
  30594. if (onError) onError(e);
  30595. scope.manager.itemError(url);
  30596. scope.manager.itemEnd(url);
  30597. });
  30598. scope.manager.itemStart(url);
  30599. }
  30600. });
  30601. function ShapePath() {
  30602. this.type = 'ShapePath';
  30603. this.color = new Color();
  30604. this.subPaths = [];
  30605. this.currentPath = null;
  30606. }
  30607. Object.assign(ShapePath.prototype, {
  30608. moveTo: function moveTo(x, y) {
  30609. this.currentPath = new Path();
  30610. this.subPaths.push(this.currentPath);
  30611. this.currentPath.moveTo(x, y);
  30612. return this;
  30613. },
  30614. lineTo: function lineTo(x, y) {
  30615. this.currentPath.lineTo(x, y);
  30616. return this;
  30617. },
  30618. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  30619. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  30620. return this;
  30621. },
  30622. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  30623. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  30624. return this;
  30625. },
  30626. splineThru: function splineThru(pts) {
  30627. this.currentPath.splineThru(pts);
  30628. return this;
  30629. },
  30630. toShapes: function toShapes(isCCW, noHoles) {
  30631. function toShapesNoHoles(inSubpaths) {
  30632. var shapes = [];
  30633. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  30634. var _tmpPath = inSubpaths[i];
  30635. var _tmpShape = new Shape();
  30636. _tmpShape.curves = _tmpPath.curves;
  30637. shapes.push(_tmpShape);
  30638. }
  30639. return shapes;
  30640. }
  30641. function isPointInsidePolygon(inPt, inPolygon) {
  30642. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  30643. // toggling of inside/outside at every single! intersection point of an edge
  30644. // with the horizontal line through inPt, left of inPt
  30645. // not counting lowerY endpoints of edges and whole edges on that line
  30646. var inside = false;
  30647. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  30648. var edgeLowPt = inPolygon[p];
  30649. var edgeHighPt = inPolygon[q];
  30650. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  30651. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  30652. if (Math.abs(edgeDy) > Number.EPSILON) {
  30653. // not parallel
  30654. if (edgeDy < 0) {
  30655. edgeLowPt = inPolygon[q];
  30656. edgeDx = -edgeDx;
  30657. edgeHighPt = inPolygon[p];
  30658. edgeDy = -edgeDy;
  30659. }
  30660. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  30661. if (inPt.y === edgeLowPt.y) {
  30662. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  30663. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30664. } else {
  30665. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  30666. if (perpEdge === 0) return true; // inPt is on contour ?
  30667. if (perpEdge < 0) continue;
  30668. inside = !inside; // true intersection left of inPt
  30669. }
  30670. } else {
  30671. // parallel or collinear
  30672. if (inPt.y !== edgeLowPt.y) continue; // parallel
  30673. // edge lies on the same horizontal line as inPt
  30674. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  30675. // continue;
  30676. }
  30677. }
  30678. return inside;
  30679. }
  30680. var isClockWise = ShapeUtils.isClockWise;
  30681. var subPaths = this.subPaths;
  30682. if (subPaths.length === 0) return [];
  30683. if (noHoles === true) return toShapesNoHoles(subPaths);
  30684. var solid, tmpPath, tmpShape;
  30685. var shapes = [];
  30686. if (subPaths.length === 1) {
  30687. tmpPath = subPaths[0];
  30688. tmpShape = new Shape();
  30689. tmpShape.curves = tmpPath.curves;
  30690. shapes.push(tmpShape);
  30691. return shapes;
  30692. }
  30693. var holesFirst = !isClockWise(subPaths[0].getPoints());
  30694. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  30695. var betterShapeHoles = [];
  30696. var newShapes = [];
  30697. var newShapeHoles = [];
  30698. var mainIdx = 0;
  30699. var tmpPoints;
  30700. newShapes[mainIdx] = undefined;
  30701. newShapeHoles[mainIdx] = [];
  30702. for (var i = 0, l = subPaths.length; i < l; i++) {
  30703. tmpPath = subPaths[i];
  30704. tmpPoints = tmpPath.getPoints();
  30705. solid = isClockWise(tmpPoints);
  30706. solid = isCCW ? !solid : solid;
  30707. if (solid) {
  30708. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  30709. newShapes[mainIdx] = {
  30710. s: new Shape(),
  30711. p: tmpPoints
  30712. };
  30713. newShapes[mainIdx].s.curves = tmpPath.curves;
  30714. if (holesFirst) mainIdx++;
  30715. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  30716. } else {
  30717. newShapeHoles[mainIdx].push({
  30718. h: tmpPath,
  30719. p: tmpPoints[0]
  30720. }); //console.log('ccw', i);
  30721. }
  30722. } // only Holes? -> probably all Shapes with wrong orientation
  30723. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  30724. if (newShapes.length > 1) {
  30725. var ambiguous = false;
  30726. var toChange = [];
  30727. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  30728. betterShapeHoles[sIdx] = [];
  30729. }
  30730. for (var _sIdx = 0, _sLen = newShapes.length; _sIdx < _sLen; _sIdx++) {
  30731. var sho = newShapeHoles[_sIdx];
  30732. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  30733. var ho = sho[hIdx];
  30734. var hole_unassigned = true;
  30735. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  30736. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  30737. if (_sIdx !== s2Idx) toChange.push({
  30738. froms: _sIdx,
  30739. tos: s2Idx,
  30740. hole: hIdx
  30741. });
  30742. if (hole_unassigned) {
  30743. hole_unassigned = false;
  30744. betterShapeHoles[s2Idx].push(ho);
  30745. } else {
  30746. ambiguous = true;
  30747. }
  30748. }
  30749. }
  30750. if (hole_unassigned) {
  30751. betterShapeHoles[_sIdx].push(ho);
  30752. }
  30753. }
  30754. } // console.log("ambiguous: ", ambiguous);
  30755. if (toChange.length > 0) {
  30756. // console.log("to change: ", toChange);
  30757. if (!ambiguous) newShapeHoles = betterShapeHoles;
  30758. }
  30759. }
  30760. var tmpHoles;
  30761. for (var _i = 0, il = newShapes.length; _i < il; _i++) {
  30762. tmpShape = newShapes[_i].s;
  30763. shapes.push(tmpShape);
  30764. tmpHoles = newShapeHoles[_i];
  30765. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  30766. tmpShape.holes.push(tmpHoles[j].h);
  30767. }
  30768. } //console.log("shape", shapes);
  30769. return shapes;
  30770. }
  30771. });
  30772. var Font = /*#__PURE__*/function () {
  30773. function Font(data) {
  30774. Object.defineProperty(this, 'isFont', {
  30775. value: true
  30776. });
  30777. this.type = 'Font';
  30778. this.data = data;
  30779. }
  30780. var _proto = Font.prototype;
  30781. _proto.generateShapes = function generateShapes(text, size) {
  30782. if (size === void 0) {
  30783. size = 100;
  30784. }
  30785. var shapes = [];
  30786. var paths = createPaths(text, size, this.data);
  30787. for (var p = 0, pl = paths.length; p < pl; p++) {
  30788. Array.prototype.push.apply(shapes, paths[p].toShapes());
  30789. }
  30790. return shapes;
  30791. };
  30792. return Font;
  30793. }();
  30794. function createPaths(text, size, data) {
  30795. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  30796. var scale = size / data.resolution;
  30797. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  30798. var paths = [];
  30799. var offsetX = 0,
  30800. offsetY = 0;
  30801. for (var i = 0; i < chars.length; i++) {
  30802. var char = chars[i];
  30803. if (char === '\n') {
  30804. offsetX = 0;
  30805. offsetY -= line_height;
  30806. } else {
  30807. var ret = createPath(char, scale, offsetX, offsetY, data);
  30808. offsetX += ret.offsetX;
  30809. paths.push(ret.path);
  30810. }
  30811. }
  30812. return paths;
  30813. }
  30814. function createPath(char, scale, offsetX, offsetY, data) {
  30815. var glyph = data.glyphs[char] || data.glyphs['?'];
  30816. if (!glyph) {
  30817. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  30818. return;
  30819. }
  30820. var path = new ShapePath();
  30821. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  30822. if (glyph.o) {
  30823. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  30824. for (var i = 0, l = outline.length; i < l;) {
  30825. var action = outline[i++];
  30826. switch (action) {
  30827. case 'm':
  30828. // moveTo
  30829. x = outline[i++] * scale + offsetX;
  30830. y = outline[i++] * scale + offsetY;
  30831. path.moveTo(x, y);
  30832. break;
  30833. case 'l':
  30834. // lineTo
  30835. x = outline[i++] * scale + offsetX;
  30836. y = outline[i++] * scale + offsetY;
  30837. path.lineTo(x, y);
  30838. break;
  30839. case 'q':
  30840. // quadraticCurveTo
  30841. cpx = outline[i++] * scale + offsetX;
  30842. cpy = outline[i++] * scale + offsetY;
  30843. cpx1 = outline[i++] * scale + offsetX;
  30844. cpy1 = outline[i++] * scale + offsetY;
  30845. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  30846. break;
  30847. case 'b':
  30848. // bezierCurveTo
  30849. cpx = outline[i++] * scale + offsetX;
  30850. cpy = outline[i++] * scale + offsetY;
  30851. cpx1 = outline[i++] * scale + offsetX;
  30852. cpy1 = outline[i++] * scale + offsetY;
  30853. cpx2 = outline[i++] * scale + offsetX;
  30854. cpy2 = outline[i++] * scale + offsetY;
  30855. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  30856. break;
  30857. }
  30858. }
  30859. }
  30860. return {
  30861. offsetX: glyph.ha * scale,
  30862. path: path
  30863. };
  30864. }
  30865. function FontLoader(manager) {
  30866. Loader.call(this, manager);
  30867. }
  30868. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30869. constructor: FontLoader,
  30870. load: function load(url, onLoad, onProgress, onError) {
  30871. var scope = this;
  30872. var loader = new FileLoader(this.manager);
  30873. loader.setPath(this.path);
  30874. loader.setRequestHeader(this.requestHeader);
  30875. loader.setWithCredentials(scope.withCredentials);
  30876. loader.load(url, function (text) {
  30877. var json;
  30878. try {
  30879. json = JSON.parse(text);
  30880. } catch (e) {
  30881. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  30882. json = JSON.parse(text.substring(65, text.length - 2));
  30883. }
  30884. var font = scope.parse(json);
  30885. if (onLoad) onLoad(font);
  30886. }, onProgress, onError);
  30887. },
  30888. parse: function parse(json) {
  30889. return new Font(json);
  30890. }
  30891. });
  30892. var _context;
  30893. var AudioContext = {
  30894. getContext: function getContext() {
  30895. if (_context === undefined) {
  30896. _context = new (window.AudioContext || window.webkitAudioContext)();
  30897. }
  30898. return _context;
  30899. },
  30900. setContext: function setContext(value) {
  30901. _context = value;
  30902. }
  30903. };
  30904. function AudioLoader(manager) {
  30905. Loader.call(this, manager);
  30906. }
  30907. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30908. constructor: AudioLoader,
  30909. load: function load(url, onLoad, onProgress, onError) {
  30910. var scope = this;
  30911. var loader = new FileLoader(scope.manager);
  30912. loader.setResponseType('arraybuffer');
  30913. loader.setPath(scope.path);
  30914. loader.setRequestHeader(scope.requestHeader);
  30915. loader.setWithCredentials(scope.withCredentials);
  30916. loader.load(url, function (buffer) {
  30917. try {
  30918. // Create a copy of the buffer. The `decodeAudioData` method
  30919. // detaches the buffer when complete, preventing reuse.
  30920. var bufferCopy = buffer.slice(0);
  30921. var context = AudioContext.getContext();
  30922. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  30923. onLoad(audioBuffer);
  30924. });
  30925. } catch (e) {
  30926. if (onError) {
  30927. onError(e);
  30928. } else {
  30929. console.error(e);
  30930. }
  30931. scope.manager.itemError(url);
  30932. }
  30933. }, onProgress, onError);
  30934. }
  30935. });
  30936. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  30937. LightProbe.call(this, undefined, intensity);
  30938. var color1 = new Color().set(skyColor);
  30939. var color2 = new Color().set(groundColor);
  30940. var sky = new Vector3(color1.r, color1.g, color1.b);
  30941. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30942. var c0 = Math.sqrt(Math.PI);
  30943. var c1 = c0 * Math.sqrt(0.75);
  30944. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  30945. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  30946. }
  30947. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  30948. constructor: HemisphereLightProbe,
  30949. isHemisphereLightProbe: true,
  30950. copy: function copy(source) {
  30951. // modifying colors not currently supported
  30952. LightProbe.prototype.copy.call(this, source);
  30953. return this;
  30954. },
  30955. toJSON: function toJSON(meta) {
  30956. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  30957. return data;
  30958. }
  30959. });
  30960. function AmbientLightProbe(color, intensity) {
  30961. LightProbe.call(this, undefined, intensity);
  30962. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30963. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  30964. }
  30965. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  30966. constructor: AmbientLightProbe,
  30967. isAmbientLightProbe: true,
  30968. copy: function copy(source) {
  30969. // modifying color not currently supported
  30970. LightProbe.prototype.copy.call(this, source);
  30971. return this;
  30972. },
  30973. toJSON: function toJSON(meta) {
  30974. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  30975. return data;
  30976. }
  30977. });
  30978. var _eyeRight = new Matrix4();
  30979. var _eyeLeft = new Matrix4();
  30980. function StereoCamera() {
  30981. this.type = 'StereoCamera';
  30982. this.aspect = 1;
  30983. this.eyeSep = 0.064;
  30984. this.cameraL = new PerspectiveCamera();
  30985. this.cameraL.layers.enable(1);
  30986. this.cameraL.matrixAutoUpdate = false;
  30987. this.cameraR = new PerspectiveCamera();
  30988. this.cameraR.layers.enable(2);
  30989. this.cameraR.matrixAutoUpdate = false;
  30990. this._cache = {
  30991. focus: null,
  30992. fov: null,
  30993. aspect: null,
  30994. near: null,
  30995. far: null,
  30996. zoom: null,
  30997. eyeSep: null
  30998. };
  30999. }
  31000. Object.assign(StereoCamera.prototype, {
  31001. update: function update(camera) {
  31002. var cache = this._cache;
  31003. 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;
  31004. if (needsUpdate) {
  31005. cache.focus = camera.focus;
  31006. cache.fov = camera.fov;
  31007. cache.aspect = camera.aspect * this.aspect;
  31008. cache.near = camera.near;
  31009. cache.far = camera.far;
  31010. cache.zoom = camera.zoom;
  31011. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  31012. // http://paulbourke.net/stereographics/stereorender/
  31013. var projectionMatrix = camera.projectionMatrix.clone();
  31014. var eyeSepHalf = cache.eyeSep / 2;
  31015. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  31016. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  31017. var xmin, xmax; // translate xOffset
  31018. _eyeLeft.elements[12] = -eyeSepHalf;
  31019. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  31020. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  31021. xmax = ymax * cache.aspect + eyeSepOnProjection;
  31022. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31023. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31024. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  31025. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  31026. xmax = ymax * cache.aspect - eyeSepOnProjection;
  31027. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31028. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31029. this.cameraR.projectionMatrix.copy(projectionMatrix);
  31030. }
  31031. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  31032. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  31033. }
  31034. });
  31035. var Clock = /*#__PURE__*/function () {
  31036. function Clock(autoStart) {
  31037. this.autoStart = autoStart !== undefined ? autoStart : true;
  31038. this.startTime = 0;
  31039. this.oldTime = 0;
  31040. this.elapsedTime = 0;
  31041. this.running = false;
  31042. }
  31043. var _proto = Clock.prototype;
  31044. _proto.start = function start() {
  31045. this.startTime = now();
  31046. this.oldTime = this.startTime;
  31047. this.elapsedTime = 0;
  31048. this.running = true;
  31049. };
  31050. _proto.stop = function stop() {
  31051. this.getElapsedTime();
  31052. this.running = false;
  31053. this.autoStart = false;
  31054. };
  31055. _proto.getElapsedTime = function getElapsedTime() {
  31056. this.getDelta();
  31057. return this.elapsedTime;
  31058. };
  31059. _proto.getDelta = function getDelta() {
  31060. var diff = 0;
  31061. if (this.autoStart && !this.running) {
  31062. this.start();
  31063. return 0;
  31064. }
  31065. if (this.running) {
  31066. var newTime = now();
  31067. diff = (newTime - this.oldTime) / 1000;
  31068. this.oldTime = newTime;
  31069. this.elapsedTime += diff;
  31070. }
  31071. return diff;
  31072. };
  31073. return Clock;
  31074. }();
  31075. function now() {
  31076. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  31077. }
  31078. var _position$2 = /*@__PURE__*/new Vector3();
  31079. var _quaternion$3 = /*@__PURE__*/new Quaternion();
  31080. var _scale$1 = /*@__PURE__*/new Vector3();
  31081. var _orientation = /*@__PURE__*/new Vector3();
  31082. var AudioListener = /*#__PURE__*/function (_Object3D) {
  31083. _inheritsLoose(AudioListener, _Object3D);
  31084. function AudioListener() {
  31085. var _this;
  31086. _this = _Object3D.call(this) || this;
  31087. _this.type = 'AudioListener';
  31088. _this.context = AudioContext.getContext();
  31089. _this.gain = _this.context.createGain();
  31090. _this.gain.connect(_this.context.destination);
  31091. _this.filter = null;
  31092. _this.timeDelta = 0; // private
  31093. _this._clock = new Clock();
  31094. return _this;
  31095. }
  31096. var _proto = AudioListener.prototype;
  31097. _proto.getInput = function getInput() {
  31098. return this.gain;
  31099. };
  31100. _proto.removeFilter = function removeFilter() {
  31101. if (this.filter !== null) {
  31102. this.gain.disconnect(this.filter);
  31103. this.filter.disconnect(this.context.destination);
  31104. this.gain.connect(this.context.destination);
  31105. this.filter = null;
  31106. }
  31107. return this;
  31108. };
  31109. _proto.getFilter = function getFilter() {
  31110. return this.filter;
  31111. };
  31112. _proto.setFilter = function setFilter(value) {
  31113. if (this.filter !== null) {
  31114. this.gain.disconnect(this.filter);
  31115. this.filter.disconnect(this.context.destination);
  31116. } else {
  31117. this.gain.disconnect(this.context.destination);
  31118. }
  31119. this.filter = value;
  31120. this.gain.connect(this.filter);
  31121. this.filter.connect(this.context.destination);
  31122. return this;
  31123. };
  31124. _proto.getMasterVolume = function getMasterVolume() {
  31125. return this.gain.gain.value;
  31126. };
  31127. _proto.setMasterVolume = function setMasterVolume(value) {
  31128. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  31129. return this;
  31130. };
  31131. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  31132. _Object3D.prototype.updateMatrixWorld.call(this, force);
  31133. var listener = this.context.listener;
  31134. var up = this.up;
  31135. this.timeDelta = this._clock.getDelta();
  31136. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  31137. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  31138. if (listener.positionX) {
  31139. // code path for Chrome (see #14393)
  31140. var endTime = this.context.currentTime + this.timeDelta;
  31141. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  31142. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  31143. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  31144. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  31145. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  31146. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  31147. listener.upX.linearRampToValueAtTime(up.x, endTime);
  31148. listener.upY.linearRampToValueAtTime(up.y, endTime);
  31149. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  31150. } else {
  31151. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  31152. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  31153. }
  31154. };
  31155. return AudioListener;
  31156. }(Object3D);
  31157. var Audio = /*#__PURE__*/function (_Object3D) {
  31158. _inheritsLoose(Audio, _Object3D);
  31159. function Audio(listener) {
  31160. var _this;
  31161. _this = _Object3D.call(this) || this;
  31162. _this.type = 'Audio';
  31163. _this.listener = listener;
  31164. _this.context = listener.context;
  31165. _this.gain = _this.context.createGain();
  31166. _this.gain.connect(listener.getInput());
  31167. _this.autoplay = false;
  31168. _this.buffer = null;
  31169. _this.detune = 0;
  31170. _this.loop = false;
  31171. _this.loopStart = 0;
  31172. _this.loopEnd = 0;
  31173. _this.offset = 0;
  31174. _this.duration = undefined;
  31175. _this.playbackRate = 1;
  31176. _this.isPlaying = false;
  31177. _this.hasPlaybackControl = true;
  31178. _this.source = null;
  31179. _this.sourceType = 'empty';
  31180. _this._startedAt = 0;
  31181. _this._progress = 0;
  31182. _this._connected = false;
  31183. _this.filters = [];
  31184. return _this;
  31185. }
  31186. var _proto = Audio.prototype;
  31187. _proto.getOutput = function getOutput() {
  31188. return this.gain;
  31189. };
  31190. _proto.setNodeSource = function setNodeSource(audioNode) {
  31191. this.hasPlaybackControl = false;
  31192. this.sourceType = 'audioNode';
  31193. this.source = audioNode;
  31194. this.connect();
  31195. return this;
  31196. };
  31197. _proto.setMediaElementSource = function setMediaElementSource(mediaElement) {
  31198. this.hasPlaybackControl = false;
  31199. this.sourceType = 'mediaNode';
  31200. this.source = this.context.createMediaElementSource(mediaElement);
  31201. this.connect();
  31202. return this;
  31203. };
  31204. _proto.setMediaStreamSource = function setMediaStreamSource(mediaStream) {
  31205. this.hasPlaybackControl = false;
  31206. this.sourceType = 'mediaStreamNode';
  31207. this.source = this.context.createMediaStreamSource(mediaStream);
  31208. this.connect();
  31209. return this;
  31210. };
  31211. _proto.setBuffer = function setBuffer(audioBuffer) {
  31212. this.buffer = audioBuffer;
  31213. this.sourceType = 'buffer';
  31214. if (this.autoplay) this.play();
  31215. return this;
  31216. };
  31217. _proto.play = function play(delay) {
  31218. if (delay === void 0) {
  31219. delay = 0;
  31220. }
  31221. if (this.isPlaying === true) {
  31222. console.warn('THREE.Audio: Audio is already playing.');
  31223. return;
  31224. }
  31225. if (this.hasPlaybackControl === false) {
  31226. console.warn('THREE.Audio: this Audio has no playback control.');
  31227. return;
  31228. }
  31229. this._startedAt = this.context.currentTime + delay;
  31230. var source = this.context.createBufferSource();
  31231. source.buffer = this.buffer;
  31232. source.loop = this.loop;
  31233. source.loopStart = this.loopStart;
  31234. source.loopEnd = this.loopEnd;
  31235. source.onended = this.onEnded.bind(this);
  31236. source.start(this._startedAt, this._progress + this.offset, this.duration);
  31237. this.isPlaying = true;
  31238. this.source = source;
  31239. this.setDetune(this.detune);
  31240. this.setPlaybackRate(this.playbackRate);
  31241. return this.connect();
  31242. };
  31243. _proto.pause = function pause() {
  31244. if (this.hasPlaybackControl === false) {
  31245. console.warn('THREE.Audio: this Audio has no playback control.');
  31246. return;
  31247. }
  31248. if (this.isPlaying === true) {
  31249. // update current progress
  31250. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  31251. if (this.loop === true) {
  31252. // ensure _progress does not exceed duration with looped audios
  31253. this._progress = this._progress % (this.duration || this.buffer.duration);
  31254. }
  31255. this.source.stop();
  31256. this.source.onended = null;
  31257. this.isPlaying = false;
  31258. }
  31259. return this;
  31260. };
  31261. _proto.stop = function stop() {
  31262. if (this.hasPlaybackControl === false) {
  31263. console.warn('THREE.Audio: this Audio has no playback control.');
  31264. return;
  31265. }
  31266. this._progress = 0;
  31267. this.source.stop();
  31268. this.source.onended = null;
  31269. this.isPlaying = false;
  31270. return this;
  31271. };
  31272. _proto.connect = function connect() {
  31273. if (this.filters.length > 0) {
  31274. this.source.connect(this.filters[0]);
  31275. for (var i = 1, l = this.filters.length; i < l; i++) {
  31276. this.filters[i - 1].connect(this.filters[i]);
  31277. }
  31278. this.filters[this.filters.length - 1].connect(this.getOutput());
  31279. } else {
  31280. this.source.connect(this.getOutput());
  31281. }
  31282. this._connected = true;
  31283. return this;
  31284. };
  31285. _proto.disconnect = function disconnect() {
  31286. if (this.filters.length > 0) {
  31287. this.source.disconnect(this.filters[0]);
  31288. for (var i = 1, l = this.filters.length; i < l; i++) {
  31289. this.filters[i - 1].disconnect(this.filters[i]);
  31290. }
  31291. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  31292. } else {
  31293. this.source.disconnect(this.getOutput());
  31294. }
  31295. this._connected = false;
  31296. return this;
  31297. };
  31298. _proto.getFilters = function getFilters() {
  31299. return this.filters;
  31300. };
  31301. _proto.setFilters = function setFilters(value) {
  31302. if (!value) value = [];
  31303. if (this._connected === true) {
  31304. this.disconnect();
  31305. this.filters = value.slice();
  31306. this.connect();
  31307. } else {
  31308. this.filters = value.slice();
  31309. }
  31310. return this;
  31311. };
  31312. _proto.setDetune = function setDetune(value) {
  31313. this.detune = value;
  31314. if (this.source.detune === undefined) return; // only set detune when available
  31315. if (this.isPlaying === true) {
  31316. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  31317. }
  31318. return this;
  31319. };
  31320. _proto.getDetune = function getDetune() {
  31321. return this.detune;
  31322. };
  31323. _proto.getFilter = function getFilter() {
  31324. return this.getFilters()[0];
  31325. };
  31326. _proto.setFilter = function setFilter(filter) {
  31327. return this.setFilters(filter ? [filter] : []);
  31328. };
  31329. _proto.setPlaybackRate = function setPlaybackRate(value) {
  31330. if (this.hasPlaybackControl === false) {
  31331. console.warn('THREE.Audio: this Audio has no playback control.');
  31332. return;
  31333. }
  31334. this.playbackRate = value;
  31335. if (this.isPlaying === true) {
  31336. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  31337. }
  31338. return this;
  31339. };
  31340. _proto.getPlaybackRate = function getPlaybackRate() {
  31341. return this.playbackRate;
  31342. };
  31343. _proto.onEnded = function onEnded() {
  31344. this.isPlaying = false;
  31345. };
  31346. _proto.getLoop = function getLoop() {
  31347. if (this.hasPlaybackControl === false) {
  31348. console.warn('THREE.Audio: this Audio has no playback control.');
  31349. return false;
  31350. }
  31351. return this.loop;
  31352. };
  31353. _proto.setLoop = function setLoop(value) {
  31354. if (this.hasPlaybackControl === false) {
  31355. console.warn('THREE.Audio: this Audio has no playback control.');
  31356. return;
  31357. }
  31358. this.loop = value;
  31359. if (this.isPlaying === true) {
  31360. this.source.loop = this.loop;
  31361. }
  31362. return this;
  31363. };
  31364. _proto.setLoopStart = function setLoopStart(value) {
  31365. this.loopStart = value;
  31366. return this;
  31367. };
  31368. _proto.setLoopEnd = function setLoopEnd(value) {
  31369. this.loopEnd = value;
  31370. return this;
  31371. };
  31372. _proto.getVolume = function getVolume() {
  31373. return this.gain.gain.value;
  31374. };
  31375. _proto.setVolume = function setVolume(value) {
  31376. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  31377. return this;
  31378. };
  31379. return Audio;
  31380. }(Object3D);
  31381. var _position$3 = /*@__PURE__*/new Vector3();
  31382. var _quaternion$4 = /*@__PURE__*/new Quaternion();
  31383. var _scale$2 = /*@__PURE__*/new Vector3();
  31384. var _orientation$1 = /*@__PURE__*/new Vector3();
  31385. var PositionalAudio = /*#__PURE__*/function (_Audio) {
  31386. _inheritsLoose(PositionalAudio, _Audio);
  31387. function PositionalAudio(listener) {
  31388. var _this;
  31389. _this = _Audio.call(this, listener) || this;
  31390. _this.panner = _this.context.createPanner();
  31391. _this.panner.panningModel = 'HRTF';
  31392. _this.panner.connect(_this.gain);
  31393. return _this;
  31394. }
  31395. var _proto = PositionalAudio.prototype;
  31396. _proto.getOutput = function getOutput() {
  31397. return this.panner;
  31398. };
  31399. _proto.getRefDistance = function getRefDistance() {
  31400. return this.panner.refDistance;
  31401. };
  31402. _proto.setRefDistance = function setRefDistance(value) {
  31403. this.panner.refDistance = value;
  31404. return this;
  31405. };
  31406. _proto.getRolloffFactor = function getRolloffFactor() {
  31407. return this.panner.rolloffFactor;
  31408. };
  31409. _proto.setRolloffFactor = function setRolloffFactor(value) {
  31410. this.panner.rolloffFactor = value;
  31411. return this;
  31412. };
  31413. _proto.getDistanceModel = function getDistanceModel() {
  31414. return this.panner.distanceModel;
  31415. };
  31416. _proto.setDistanceModel = function setDistanceModel(value) {
  31417. this.panner.distanceModel = value;
  31418. return this;
  31419. };
  31420. _proto.getMaxDistance = function getMaxDistance() {
  31421. return this.panner.maxDistance;
  31422. };
  31423. _proto.setMaxDistance = function setMaxDistance(value) {
  31424. this.panner.maxDistance = value;
  31425. return this;
  31426. };
  31427. _proto.setDirectionalCone = function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31428. this.panner.coneInnerAngle = coneInnerAngle;
  31429. this.panner.coneOuterAngle = coneOuterAngle;
  31430. this.panner.coneOuterGain = coneOuterGain;
  31431. return this;
  31432. };
  31433. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  31434. _Audio.prototype.updateMatrixWorld.call(this, force);
  31435. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  31436. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  31437. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  31438. var panner = this.panner;
  31439. if (panner.positionX) {
  31440. // code path for Chrome and Firefox (see #14393)
  31441. var endTime = this.context.currentTime + this.listener.timeDelta;
  31442. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  31443. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  31444. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  31445. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  31446. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  31447. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  31448. } else {
  31449. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  31450. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  31451. }
  31452. };
  31453. return PositionalAudio;
  31454. }(Audio);
  31455. var AudioAnalyser = /*#__PURE__*/function () {
  31456. function AudioAnalyser(audio, fftSize) {
  31457. if (fftSize === void 0) {
  31458. fftSize = 2048;
  31459. }
  31460. this.analyser = audio.context.createAnalyser();
  31461. this.analyser.fftSize = fftSize;
  31462. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  31463. audio.getOutput().connect(this.analyser);
  31464. }
  31465. var _proto = AudioAnalyser.prototype;
  31466. _proto.getFrequencyData = function getFrequencyData() {
  31467. this.analyser.getByteFrequencyData(this.data);
  31468. return this.data;
  31469. };
  31470. _proto.getAverageFrequency = function getAverageFrequency() {
  31471. var value = 0;
  31472. var data = this.getFrequencyData();
  31473. for (var i = 0; i < data.length; i++) {
  31474. value += data[i];
  31475. }
  31476. return value / data.length;
  31477. };
  31478. return AudioAnalyser;
  31479. }();
  31480. function PropertyMixer(binding, typeName, valueSize) {
  31481. this.binding = binding;
  31482. this.valueSize = valueSize;
  31483. var mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  31484. //
  31485. // interpolators can use .buffer as their .result
  31486. // the data then goes to 'incoming'
  31487. //
  31488. // 'accu0' and 'accu1' are used frame-interleaved for
  31489. // the cumulative result and are compared to detect
  31490. // changes
  31491. //
  31492. // 'orig' stores the original state of the property
  31493. //
  31494. // 'add' is used for additive cumulative results
  31495. //
  31496. // 'work' is optional and is only present for quaternion types. It is used
  31497. // to store intermediate quaternion multiplication results
  31498. switch (typeName) {
  31499. case 'quaternion':
  31500. mixFunction = this._slerp;
  31501. mixFunctionAdditive = this._slerpAdditive;
  31502. setIdentity = this._setAdditiveIdentityQuaternion;
  31503. this.buffer = new Float64Array(valueSize * 6);
  31504. this._workIndex = 5;
  31505. break;
  31506. case 'string':
  31507. case 'bool':
  31508. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  31509. // additive is not relevant for non-numeric types
  31510. mixFunctionAdditive = this._select;
  31511. setIdentity = this._setAdditiveIdentityOther;
  31512. this.buffer = new Array(valueSize * 5);
  31513. break;
  31514. default:
  31515. mixFunction = this._lerp;
  31516. mixFunctionAdditive = this._lerpAdditive;
  31517. setIdentity = this._setAdditiveIdentityNumeric;
  31518. this.buffer = new Float64Array(valueSize * 5);
  31519. }
  31520. this._mixBufferRegion = mixFunction;
  31521. this._mixBufferRegionAdditive = mixFunctionAdditive;
  31522. this._setIdentity = setIdentity;
  31523. this._origIndex = 3;
  31524. this._addIndex = 4;
  31525. this.cumulativeWeight = 0;
  31526. this.cumulativeWeightAdditive = 0;
  31527. this.useCount = 0;
  31528. this.referenceCount = 0;
  31529. }
  31530. Object.assign(PropertyMixer.prototype, {
  31531. // accumulate data in the 'incoming' region into 'accu<i>'
  31532. accumulate: function accumulate(accuIndex, weight) {
  31533. // note: happily accumulating nothing when weight = 0, the caller knows
  31534. // the weight and shouldn't have made the call in the first place
  31535. var buffer = this.buffer,
  31536. stride = this.valueSize,
  31537. offset = accuIndex * stride + stride;
  31538. var currentWeight = this.cumulativeWeight;
  31539. if (currentWeight === 0) {
  31540. // accuN := incoming * weight
  31541. for (var i = 0; i !== stride; ++i) {
  31542. buffer[offset + i] = buffer[i];
  31543. }
  31544. currentWeight = weight;
  31545. } else {
  31546. // accuN := accuN + incoming * weight
  31547. currentWeight += weight;
  31548. var mix = weight / currentWeight;
  31549. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  31550. }
  31551. this.cumulativeWeight = currentWeight;
  31552. },
  31553. // accumulate data in the 'incoming' region into 'add'
  31554. accumulateAdditive: function accumulateAdditive(weight) {
  31555. var buffer = this.buffer,
  31556. stride = this.valueSize,
  31557. offset = stride * this._addIndex;
  31558. if (this.cumulativeWeightAdditive === 0) {
  31559. // add = identity
  31560. this._setIdentity();
  31561. } // add := add + incoming * weight
  31562. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  31563. this.cumulativeWeightAdditive += weight;
  31564. },
  31565. // apply the state of 'accu<i>' to the binding when accus differ
  31566. apply: function apply(accuIndex) {
  31567. var stride = this.valueSize,
  31568. buffer = this.buffer,
  31569. offset = accuIndex * stride + stride,
  31570. weight = this.cumulativeWeight,
  31571. weightAdditive = this.cumulativeWeightAdditive,
  31572. binding = this.binding;
  31573. this.cumulativeWeight = 0;
  31574. this.cumulativeWeightAdditive = 0;
  31575. if (weight < 1) {
  31576. // accuN := accuN + original * ( 1 - cumulativeWeight )
  31577. var originalValueOffset = stride * this._origIndex;
  31578. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  31579. }
  31580. if (weightAdditive > 0) {
  31581. // accuN := accuN + additive accuN
  31582. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  31583. }
  31584. for (var i = stride, e = stride + stride; i !== e; ++i) {
  31585. if (buffer[i] !== buffer[i + stride]) {
  31586. // value has changed -> update scene graph
  31587. binding.setValue(buffer, offset);
  31588. break;
  31589. }
  31590. }
  31591. },
  31592. // remember the state of the bound property and copy it to both accus
  31593. saveOriginalState: function saveOriginalState() {
  31594. var binding = this.binding;
  31595. var buffer = this.buffer,
  31596. stride = this.valueSize,
  31597. originalValueOffset = stride * this._origIndex;
  31598. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  31599. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  31600. buffer[i] = buffer[originalValueOffset + i % stride];
  31601. } // Add to identity for additive
  31602. this._setIdentity();
  31603. this.cumulativeWeight = 0;
  31604. this.cumulativeWeightAdditive = 0;
  31605. },
  31606. // apply the state previously taken via 'saveOriginalState' to the binding
  31607. restoreOriginalState: function restoreOriginalState() {
  31608. var originalValueOffset = this.valueSize * 3;
  31609. this.binding.setValue(this.buffer, originalValueOffset);
  31610. },
  31611. _setAdditiveIdentityNumeric: function _setAdditiveIdentityNumeric() {
  31612. var startIndex = this._addIndex * this.valueSize;
  31613. var endIndex = startIndex + this.valueSize;
  31614. for (var i = startIndex; i < endIndex; i++) {
  31615. this.buffer[i] = 0;
  31616. }
  31617. },
  31618. _setAdditiveIdentityQuaternion: function _setAdditiveIdentityQuaternion() {
  31619. this._setAdditiveIdentityNumeric();
  31620. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  31621. },
  31622. _setAdditiveIdentityOther: function _setAdditiveIdentityOther() {
  31623. var startIndex = this._origIndex * this.valueSize;
  31624. var targetIndex = this._addIndex * this.valueSize;
  31625. for (var i = 0; i < this.valueSize; i++) {
  31626. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  31627. }
  31628. },
  31629. // mix functions
  31630. _select: function _select(buffer, dstOffset, srcOffset, t, stride) {
  31631. if (t >= 0.5) {
  31632. for (var i = 0; i !== stride; ++i) {
  31633. buffer[dstOffset + i] = buffer[srcOffset + i];
  31634. }
  31635. }
  31636. },
  31637. _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {
  31638. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  31639. },
  31640. _slerpAdditive: function _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31641. var workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  31642. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  31643. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  31644. },
  31645. _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {
  31646. var s = 1 - t;
  31647. for (var i = 0; i !== stride; ++i) {
  31648. var j = dstOffset + i;
  31649. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  31650. }
  31651. },
  31652. _lerpAdditive: function _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31653. for (var i = 0; i !== stride; ++i) {
  31654. var j = dstOffset + i;
  31655. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  31656. }
  31657. }
  31658. });
  31659. // Characters [].:/ are reserved for track binding syntax.
  31660. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  31661. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  31662. // only latin characters, and the unicode \p{L} is not yet supported. So
  31663. // instead, we exclude reserved characters and match everything else.
  31664. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  31665. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  31666. // be matched to parse the rest of the track name.
  31667. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  31668. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  31669. // characters. Accessor may contain any character except closing bracket.
  31670. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  31671. // contain any non-bracket characters.
  31672. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  31673. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  31674. var _supportedObjectNames = ['material', 'materials', 'bones'];
  31675. function Composite(targetGroup, path, optionalParsedPath) {
  31676. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  31677. this._targetGroup = targetGroup;
  31678. this._bindings = targetGroup.subscribe_(path, parsedPath);
  31679. }
  31680. Object.assign(Composite.prototype, {
  31681. getValue: function getValue(array, offset) {
  31682. this.bind(); // bind all binding
  31683. var firstValidIndex = this._targetGroup.nCachedObjects_,
  31684. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  31685. if (binding !== undefined) binding.getValue(array, offset);
  31686. },
  31687. setValue: function setValue(array, offset) {
  31688. var bindings = this._bindings;
  31689. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31690. bindings[i].setValue(array, offset);
  31691. }
  31692. },
  31693. bind: function bind() {
  31694. var bindings = this._bindings;
  31695. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31696. bindings[i].bind();
  31697. }
  31698. },
  31699. unbind: function unbind() {
  31700. var bindings = this._bindings;
  31701. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31702. bindings[i].unbind();
  31703. }
  31704. }
  31705. });
  31706. function PropertyBinding(rootNode, path, parsedPath) {
  31707. this.path = path;
  31708. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  31709. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  31710. this.rootNode = rootNode;
  31711. }
  31712. Object.assign(PropertyBinding, {
  31713. Composite: Composite,
  31714. create: function create(root, path, parsedPath) {
  31715. if (!(root && root.isAnimationObjectGroup)) {
  31716. return new PropertyBinding(root, path, parsedPath);
  31717. } else {
  31718. return new PropertyBinding.Composite(root, path, parsedPath);
  31719. }
  31720. },
  31721. /**
  31722. * Replaces spaces with underscores and removes unsupported characters from
  31723. * node names, to ensure compatibility with parseTrackName().
  31724. *
  31725. * @param {string} name Node name to be sanitized.
  31726. * @return {string}
  31727. */
  31728. sanitizeNodeName: function sanitizeNodeName(name) {
  31729. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  31730. },
  31731. parseTrackName: function parseTrackName(trackName) {
  31732. var matches = _trackRe.exec(trackName);
  31733. if (!matches) {
  31734. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  31735. }
  31736. var results = {
  31737. // directoryName: matches[ 1 ], // (tschw) currently unused
  31738. nodeName: matches[2],
  31739. objectName: matches[3],
  31740. objectIndex: matches[4],
  31741. propertyName: matches[5],
  31742. // required
  31743. propertyIndex: matches[6]
  31744. };
  31745. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  31746. if (lastDot !== undefined && lastDot !== -1) {
  31747. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  31748. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  31749. // 'bar' could be the objectName, or part of a nodeName (which can
  31750. // include '.' characters).
  31751. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  31752. results.nodeName = results.nodeName.substring(0, lastDot);
  31753. results.objectName = objectName;
  31754. }
  31755. }
  31756. if (results.propertyName === null || results.propertyName.length === 0) {
  31757. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  31758. }
  31759. return results;
  31760. },
  31761. findNode: function findNode(root, nodeName) {
  31762. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  31763. return root;
  31764. } // search into skeleton bones.
  31765. if (root.skeleton) {
  31766. var bone = root.skeleton.getBoneByName(nodeName);
  31767. if (bone !== undefined) {
  31768. return bone;
  31769. }
  31770. } // search into node subtree.
  31771. if (root.children) {
  31772. var searchNodeSubtree = function searchNodeSubtree(children) {
  31773. for (var i = 0; i < children.length; i++) {
  31774. var childNode = children[i];
  31775. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  31776. return childNode;
  31777. }
  31778. var result = searchNodeSubtree(childNode.children);
  31779. if (result) return result;
  31780. }
  31781. return null;
  31782. };
  31783. var subTreeNode = searchNodeSubtree(root.children);
  31784. if (subTreeNode) {
  31785. return subTreeNode;
  31786. }
  31787. }
  31788. return null;
  31789. }
  31790. });
  31791. Object.assign(PropertyBinding.prototype, {
  31792. // prototype, continued
  31793. // these are used to "bind" a nonexistent property
  31794. _getValue_unavailable: function _getValue_unavailable() {},
  31795. _setValue_unavailable: function _setValue_unavailable() {},
  31796. BindingType: {
  31797. Direct: 0,
  31798. EntireArray: 1,
  31799. ArrayElement: 2,
  31800. HasFromToArray: 3
  31801. },
  31802. Versioning: {
  31803. None: 0,
  31804. NeedsUpdate: 1,
  31805. MatrixWorldNeedsUpdate: 2
  31806. },
  31807. GetterByBindingType: [function getValue_direct(buffer, offset) {
  31808. buffer[offset] = this.node[this.propertyName];
  31809. }, function getValue_array(buffer, offset) {
  31810. var source = this.resolvedProperty;
  31811. for (var i = 0, n = source.length; i !== n; ++i) {
  31812. buffer[offset++] = source[i];
  31813. }
  31814. }, function getValue_arrayElement(buffer, offset) {
  31815. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  31816. }, function getValue_toArray(buffer, offset) {
  31817. this.resolvedProperty.toArray(buffer, offset);
  31818. }],
  31819. SetterByBindingTypeAndVersioning: [[// Direct
  31820. function setValue_direct(buffer, offset) {
  31821. this.targetObject[this.propertyName] = buffer[offset];
  31822. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  31823. this.targetObject[this.propertyName] = buffer[offset];
  31824. this.targetObject.needsUpdate = true;
  31825. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  31826. this.targetObject[this.propertyName] = buffer[offset];
  31827. this.targetObject.matrixWorldNeedsUpdate = true;
  31828. }], [// EntireArray
  31829. function setValue_array(buffer, offset) {
  31830. var dest = this.resolvedProperty;
  31831. for (var i = 0, n = dest.length; i !== n; ++i) {
  31832. dest[i] = buffer[offset++];
  31833. }
  31834. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  31835. var dest = this.resolvedProperty;
  31836. for (var i = 0, n = dest.length; i !== n; ++i) {
  31837. dest[i] = buffer[offset++];
  31838. }
  31839. this.targetObject.needsUpdate = true;
  31840. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  31841. var dest = this.resolvedProperty;
  31842. for (var i = 0, n = dest.length; i !== n; ++i) {
  31843. dest[i] = buffer[offset++];
  31844. }
  31845. this.targetObject.matrixWorldNeedsUpdate = true;
  31846. }], [// ArrayElement
  31847. function setValue_arrayElement(buffer, offset) {
  31848. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31849. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  31850. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31851. this.targetObject.needsUpdate = true;
  31852. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  31853. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31854. this.targetObject.matrixWorldNeedsUpdate = true;
  31855. }], [// HasToFromArray
  31856. function setValue_fromArray(buffer, offset) {
  31857. this.resolvedProperty.fromArray(buffer, offset);
  31858. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  31859. this.resolvedProperty.fromArray(buffer, offset);
  31860. this.targetObject.needsUpdate = true;
  31861. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  31862. this.resolvedProperty.fromArray(buffer, offset);
  31863. this.targetObject.matrixWorldNeedsUpdate = true;
  31864. }]],
  31865. getValue: function getValue_unbound(targetArray, offset) {
  31866. this.bind();
  31867. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  31868. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31869. // prototype version of these methods with one that represents
  31870. // the bound state. When the property is not found, the methods
  31871. // become no-ops.
  31872. },
  31873. setValue: function getValue_unbound(sourceArray, offset) {
  31874. this.bind();
  31875. this.setValue(sourceArray, offset);
  31876. },
  31877. // create getter / setter pair for a property in the scene graph
  31878. bind: function bind() {
  31879. var targetObject = this.node;
  31880. var parsedPath = this.parsedPath;
  31881. var objectName = parsedPath.objectName;
  31882. var propertyName = parsedPath.propertyName;
  31883. var propertyIndex = parsedPath.propertyIndex;
  31884. if (!targetObject) {
  31885. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  31886. this.node = targetObject;
  31887. } // set fail state so we can just 'return' on error
  31888. this.getValue = this._getValue_unavailable;
  31889. this.setValue = this._setValue_unavailable; // ensure there is a value node
  31890. if (!targetObject) {
  31891. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  31892. return;
  31893. }
  31894. if (objectName) {
  31895. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31896. switch (objectName) {
  31897. case 'materials':
  31898. if (!targetObject.material) {
  31899. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  31900. return;
  31901. }
  31902. if (!targetObject.material.materials) {
  31903. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  31904. return;
  31905. }
  31906. targetObject = targetObject.material.materials;
  31907. break;
  31908. case 'bones':
  31909. if (!targetObject.skeleton) {
  31910. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  31911. return;
  31912. } // potential future optimization: skip this if propertyIndex is already an integer
  31913. // and convert the integer string to a true integer.
  31914. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  31915. for (var i = 0; i < targetObject.length; i++) {
  31916. if (targetObject[i].name === objectIndex) {
  31917. objectIndex = i;
  31918. break;
  31919. }
  31920. }
  31921. break;
  31922. default:
  31923. if (targetObject[objectName] === undefined) {
  31924. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  31925. return;
  31926. }
  31927. targetObject = targetObject[objectName];
  31928. }
  31929. if (objectIndex !== undefined) {
  31930. if (targetObject[objectIndex] === undefined) {
  31931. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  31932. return;
  31933. }
  31934. targetObject = targetObject[objectIndex];
  31935. }
  31936. } // resolve property
  31937. var nodeProperty = targetObject[propertyName];
  31938. if (nodeProperty === undefined) {
  31939. var nodeName = parsedPath.nodeName;
  31940. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  31941. return;
  31942. } // determine versioning scheme
  31943. var versioning = this.Versioning.None;
  31944. this.targetObject = targetObject;
  31945. if (targetObject.needsUpdate !== undefined) {
  31946. // material
  31947. versioning = this.Versioning.NeedsUpdate;
  31948. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  31949. // node transform
  31950. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31951. } // determine how the property gets bound
  31952. var bindingType = this.BindingType.Direct;
  31953. if (propertyIndex !== undefined) {
  31954. // access a sub element of the property array (only primitives are supported right now)
  31955. if (propertyName === 'morphTargetInfluences') {
  31956. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31957. // support resolving morphTarget names into indices.
  31958. if (!targetObject.geometry) {
  31959. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  31960. return;
  31961. }
  31962. if (targetObject.geometry.isBufferGeometry) {
  31963. if (!targetObject.geometry.morphAttributes) {
  31964. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  31965. return;
  31966. }
  31967. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  31968. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  31969. }
  31970. } else {
  31971. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  31972. return;
  31973. }
  31974. }
  31975. bindingType = this.BindingType.ArrayElement;
  31976. this.resolvedProperty = nodeProperty;
  31977. this.propertyIndex = propertyIndex;
  31978. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  31979. // must use copy for Object3D.Euler/Quaternion
  31980. bindingType = this.BindingType.HasFromToArray;
  31981. this.resolvedProperty = nodeProperty;
  31982. } else if (Array.isArray(nodeProperty)) {
  31983. bindingType = this.BindingType.EntireArray;
  31984. this.resolvedProperty = nodeProperty;
  31985. } else {
  31986. this.propertyName = propertyName;
  31987. } // select getter / setter
  31988. this.getValue = this.GetterByBindingType[bindingType];
  31989. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  31990. },
  31991. unbind: function unbind() {
  31992. this.node = null; // back to the prototype version of getValue / setValue
  31993. // note: avoiding to mutate the shape of 'this' via 'delete'
  31994. this.getValue = this._getValue_unbound;
  31995. this.setValue = this._setValue_unbound;
  31996. }
  31997. }); // DECLARE ALIAS AFTER assign prototype
  31998. Object.assign(PropertyBinding.prototype, {
  31999. // initial state of these methods that calls 'bind'
  32000. _getValue_unbound: PropertyBinding.prototype.getValue,
  32001. _setValue_unbound: PropertyBinding.prototype.setValue
  32002. });
  32003. /**
  32004. *
  32005. * A group of objects that receives a shared animation state.
  32006. *
  32007. * Usage:
  32008. *
  32009. * - Add objects you would otherwise pass as 'root' to the
  32010. * constructor or the .clipAction method of AnimationMixer.
  32011. *
  32012. * - Instead pass this object as 'root'.
  32013. *
  32014. * - You can also add and remove objects later when the mixer
  32015. * is running.
  32016. *
  32017. * Note:
  32018. *
  32019. * Objects of this class appear as one object to the mixer,
  32020. * so cache control of the individual objects must be done
  32021. * on the group.
  32022. *
  32023. * Limitation:
  32024. *
  32025. * - The animated properties must be compatible among the
  32026. * all objects in the group.
  32027. *
  32028. * - A single property can either be controlled through a
  32029. * target group or directly, but not both.
  32030. */
  32031. function AnimationObjectGroup() {
  32032. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  32033. this._objects = Array.prototype.slice.call(arguments);
  32034. this.nCachedObjects_ = 0; // threshold
  32035. // note: read by PropertyBinding.Composite
  32036. var indices = {};
  32037. this._indicesByUUID = indices; // for bookkeeping
  32038. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32039. indices[arguments[i].uuid] = i;
  32040. }
  32041. this._paths = []; // inside: string
  32042. this._parsedPaths = []; // inside: { we don't care, here }
  32043. this._bindings = []; // inside: Array< PropertyBinding >
  32044. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  32045. var scope = this;
  32046. this.stats = {
  32047. objects: {
  32048. get total() {
  32049. return scope._objects.length;
  32050. },
  32051. get inUse() {
  32052. return this.total - scope.nCachedObjects_;
  32053. }
  32054. },
  32055. get bindingsPerObject() {
  32056. return scope._bindings.length;
  32057. }
  32058. };
  32059. }
  32060. Object.assign(AnimationObjectGroup.prototype, {
  32061. isAnimationObjectGroup: true,
  32062. add: function add() {
  32063. var objects = this._objects,
  32064. indicesByUUID = this._indicesByUUID,
  32065. paths = this._paths,
  32066. parsedPaths = this._parsedPaths,
  32067. bindings = this._bindings,
  32068. nBindings = bindings.length;
  32069. var knownObject = undefined,
  32070. nObjects = objects.length,
  32071. nCachedObjects = this.nCachedObjects_;
  32072. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32073. var object = arguments[i],
  32074. uuid = object.uuid;
  32075. var index = indicesByUUID[uuid];
  32076. if (index === undefined) {
  32077. // unknown object -> add it to the ACTIVE region
  32078. index = nObjects++;
  32079. indicesByUUID[uuid] = index;
  32080. objects.push(object); // accounting is done, now do the same for all bindings
  32081. for (var j = 0, m = nBindings; j !== m; ++j) {
  32082. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  32083. }
  32084. } else if (index < nCachedObjects) {
  32085. knownObject = objects[index]; // move existing object to the ACTIVE region
  32086. var firstActiveIndex = --nCachedObjects,
  32087. lastCachedObject = objects[firstActiveIndex];
  32088. indicesByUUID[lastCachedObject.uuid] = index;
  32089. objects[index] = lastCachedObject;
  32090. indicesByUUID[uuid] = firstActiveIndex;
  32091. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  32092. for (var _j = 0, _m = nBindings; _j !== _m; ++_j) {
  32093. var bindingsForPath = bindings[_j],
  32094. lastCached = bindingsForPath[firstActiveIndex];
  32095. var binding = bindingsForPath[index];
  32096. bindingsForPath[index] = lastCached;
  32097. if (binding === undefined) {
  32098. // since we do not bother to create new bindings
  32099. // for objects that are cached, the binding may
  32100. // or may not exist
  32101. binding = new PropertyBinding(object, paths[_j], parsedPaths[_j]);
  32102. }
  32103. bindingsForPath[firstActiveIndex] = binding;
  32104. }
  32105. } else if (objects[index] !== knownObject) {
  32106. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  32107. } // else the object is already where we want it to be
  32108. } // for arguments
  32109. this.nCachedObjects_ = nCachedObjects;
  32110. },
  32111. remove: function remove() {
  32112. var objects = this._objects,
  32113. indicesByUUID = this._indicesByUUID,
  32114. bindings = this._bindings,
  32115. nBindings = bindings.length;
  32116. var nCachedObjects = this.nCachedObjects_;
  32117. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32118. var object = arguments[i],
  32119. uuid = object.uuid,
  32120. index = indicesByUUID[uuid];
  32121. if (index !== undefined && index >= nCachedObjects) {
  32122. // move existing object into the CACHED region
  32123. var lastCachedIndex = nCachedObjects++,
  32124. firstActiveObject = objects[lastCachedIndex];
  32125. indicesByUUID[firstActiveObject.uuid] = index;
  32126. objects[index] = firstActiveObject;
  32127. indicesByUUID[uuid] = lastCachedIndex;
  32128. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  32129. for (var j = 0, m = nBindings; j !== m; ++j) {
  32130. var bindingsForPath = bindings[j],
  32131. firstActive = bindingsForPath[lastCachedIndex],
  32132. binding = bindingsForPath[index];
  32133. bindingsForPath[index] = firstActive;
  32134. bindingsForPath[lastCachedIndex] = binding;
  32135. }
  32136. }
  32137. } // for arguments
  32138. this.nCachedObjects_ = nCachedObjects;
  32139. },
  32140. // remove & forget
  32141. uncache: function uncache() {
  32142. var objects = this._objects,
  32143. indicesByUUID = this._indicesByUUID,
  32144. bindings = this._bindings,
  32145. nBindings = bindings.length;
  32146. var nCachedObjects = this.nCachedObjects_,
  32147. nObjects = objects.length;
  32148. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32149. var object = arguments[i],
  32150. uuid = object.uuid,
  32151. index = indicesByUUID[uuid];
  32152. if (index !== undefined) {
  32153. delete indicesByUUID[uuid];
  32154. if (index < nCachedObjects) {
  32155. // object is cached, shrink the CACHED region
  32156. var firstActiveIndex = --nCachedObjects,
  32157. lastCachedObject = objects[firstActiveIndex],
  32158. lastIndex = --nObjects,
  32159. lastObject = objects[lastIndex]; // last cached object takes this object's place
  32160. indicesByUUID[lastCachedObject.uuid] = index;
  32161. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  32162. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  32163. objects[firstActiveIndex] = lastObject;
  32164. objects.pop(); // accounting is done, now do the same for all bindings
  32165. for (var j = 0, m = nBindings; j !== m; ++j) {
  32166. var bindingsForPath = bindings[j],
  32167. lastCached = bindingsForPath[firstActiveIndex],
  32168. last = bindingsForPath[lastIndex];
  32169. bindingsForPath[index] = lastCached;
  32170. bindingsForPath[firstActiveIndex] = last;
  32171. bindingsForPath.pop();
  32172. }
  32173. } else {
  32174. // object is active, just swap with the last and pop
  32175. var _lastIndex = --nObjects,
  32176. _lastObject = objects[_lastIndex];
  32177. if (_lastIndex > 0) {
  32178. indicesByUUID[_lastObject.uuid] = index;
  32179. }
  32180. objects[index] = _lastObject;
  32181. objects.pop(); // accounting is done, now do the same for all bindings
  32182. for (var _j2 = 0, _m2 = nBindings; _j2 !== _m2; ++_j2) {
  32183. var _bindingsForPath = bindings[_j2];
  32184. _bindingsForPath[index] = _bindingsForPath[_lastIndex];
  32185. _bindingsForPath.pop();
  32186. }
  32187. } // cached or active
  32188. } // if object is known
  32189. } // for arguments
  32190. this.nCachedObjects_ = nCachedObjects;
  32191. },
  32192. // Internal interface used by befriended PropertyBinding.Composite:
  32193. subscribe_: function subscribe_(path, parsedPath) {
  32194. // returns an array of bindings for the given path that is changed
  32195. // according to the contained objects in the group
  32196. var indicesByPath = this._bindingsIndicesByPath;
  32197. var index = indicesByPath[path];
  32198. var bindings = this._bindings;
  32199. if (index !== undefined) return bindings[index];
  32200. var paths = this._paths,
  32201. parsedPaths = this._parsedPaths,
  32202. objects = this._objects,
  32203. nObjects = objects.length,
  32204. nCachedObjects = this.nCachedObjects_,
  32205. bindingsForPath = new Array(nObjects);
  32206. index = bindings.length;
  32207. indicesByPath[path] = index;
  32208. paths.push(path);
  32209. parsedPaths.push(parsedPath);
  32210. bindings.push(bindingsForPath);
  32211. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  32212. var object = objects[i];
  32213. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  32214. }
  32215. return bindingsForPath;
  32216. },
  32217. unsubscribe_: function unsubscribe_(path) {
  32218. // tells the group to forget about a property path and no longer
  32219. // update the array previously obtained with 'subscribe_'
  32220. var indicesByPath = this._bindingsIndicesByPath,
  32221. index = indicesByPath[path];
  32222. if (index !== undefined) {
  32223. var paths = this._paths,
  32224. parsedPaths = this._parsedPaths,
  32225. bindings = this._bindings,
  32226. lastBindingsIndex = bindings.length - 1,
  32227. lastBindings = bindings[lastBindingsIndex],
  32228. lastBindingsPath = path[lastBindingsIndex];
  32229. indicesByPath[lastBindingsPath] = index;
  32230. bindings[index] = lastBindings;
  32231. bindings.pop();
  32232. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  32233. parsedPaths.pop();
  32234. paths[index] = paths[lastBindingsIndex];
  32235. paths.pop();
  32236. }
  32237. }
  32238. });
  32239. var AnimationAction = /*#__PURE__*/function () {
  32240. function AnimationAction(mixer, clip, localRoot, blendMode) {
  32241. if (localRoot === void 0) {
  32242. localRoot = null;
  32243. }
  32244. if (blendMode === void 0) {
  32245. blendMode = clip.blendMode;
  32246. }
  32247. this._mixer = mixer;
  32248. this._clip = clip;
  32249. this._localRoot = localRoot;
  32250. this.blendMode = blendMode;
  32251. var tracks = clip.tracks,
  32252. nTracks = tracks.length,
  32253. interpolants = new Array(nTracks);
  32254. var interpolantSettings = {
  32255. endingStart: ZeroCurvatureEnding,
  32256. endingEnd: ZeroCurvatureEnding
  32257. };
  32258. for (var i = 0; i !== nTracks; ++i) {
  32259. var interpolant = tracks[i].createInterpolant(null);
  32260. interpolants[i] = interpolant;
  32261. interpolant.settings = interpolantSettings;
  32262. }
  32263. this._interpolantSettings = interpolantSettings;
  32264. this._interpolants = interpolants; // bound by the mixer
  32265. // inside: PropertyMixer (managed by the mixer)
  32266. this._propertyBindings = new Array(nTracks);
  32267. this._cacheIndex = null; // for the memory manager
  32268. this._byClipCacheIndex = null; // for the memory manager
  32269. this._timeScaleInterpolant = null;
  32270. this._weightInterpolant = null;
  32271. this.loop = LoopRepeat;
  32272. this._loopCount = -1; // global mixer time when the action is to be started
  32273. // it's set back to 'null' upon start of the action
  32274. this._startTime = null; // scaled local time of the action
  32275. // gets clamped or wrapped to 0..clip.duration according to loop
  32276. this.time = 0;
  32277. this.timeScale = 1;
  32278. this._effectiveTimeScale = 1;
  32279. this.weight = 1;
  32280. this._effectiveWeight = 1;
  32281. this.repetitions = Infinity; // no. of repetitions when looping
  32282. this.paused = false; // true -> zero effective time scale
  32283. this.enabled = true; // false -> zero effective weight
  32284. this.clampWhenFinished = false; // keep feeding the last frame?
  32285. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  32286. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  32287. } // State & Scheduling
  32288. var _proto = AnimationAction.prototype;
  32289. _proto.play = function play() {
  32290. this._mixer._activateAction(this);
  32291. return this;
  32292. };
  32293. _proto.stop = function stop() {
  32294. this._mixer._deactivateAction(this);
  32295. return this.reset();
  32296. };
  32297. _proto.reset = function reset() {
  32298. this.paused = false;
  32299. this.enabled = true;
  32300. this.time = 0; // restart clip
  32301. this._loopCount = -1; // forget previous loops
  32302. this._startTime = null; // forget scheduling
  32303. return this.stopFading().stopWarping();
  32304. };
  32305. _proto.isRunning = function isRunning() {
  32306. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  32307. } // return true when play has been called
  32308. ;
  32309. _proto.isScheduled = function isScheduled() {
  32310. return this._mixer._isActiveAction(this);
  32311. };
  32312. _proto.startAt = function startAt(time) {
  32313. this._startTime = time;
  32314. return this;
  32315. };
  32316. _proto.setLoop = function setLoop(mode, repetitions) {
  32317. this.loop = mode;
  32318. this.repetitions = repetitions;
  32319. return this;
  32320. } // Weight
  32321. // set the weight stopping any scheduled fading
  32322. // although .enabled = false yields an effective weight of zero, this
  32323. // method does *not* change .enabled, because it would be confusing
  32324. ;
  32325. _proto.setEffectiveWeight = function setEffectiveWeight(weight) {
  32326. this.weight = weight; // note: same logic as when updated at runtime
  32327. this._effectiveWeight = this.enabled ? weight : 0;
  32328. return this.stopFading();
  32329. } // return the weight considering fading and .enabled
  32330. ;
  32331. _proto.getEffectiveWeight = function getEffectiveWeight() {
  32332. return this._effectiveWeight;
  32333. };
  32334. _proto.fadeIn = function fadeIn(duration) {
  32335. return this._scheduleFading(duration, 0, 1);
  32336. };
  32337. _proto.fadeOut = function fadeOut(duration) {
  32338. return this._scheduleFading(duration, 1, 0);
  32339. };
  32340. _proto.crossFadeFrom = function crossFadeFrom(fadeOutAction, duration, warp) {
  32341. fadeOutAction.fadeOut(duration);
  32342. this.fadeIn(duration);
  32343. if (warp) {
  32344. var fadeInDuration = this._clip.duration,
  32345. fadeOutDuration = fadeOutAction._clip.duration,
  32346. startEndRatio = fadeOutDuration / fadeInDuration,
  32347. endStartRatio = fadeInDuration / fadeOutDuration;
  32348. fadeOutAction.warp(1.0, startEndRatio, duration);
  32349. this.warp(endStartRatio, 1.0, duration);
  32350. }
  32351. return this;
  32352. };
  32353. _proto.crossFadeTo = function crossFadeTo(fadeInAction, duration, warp) {
  32354. return fadeInAction.crossFadeFrom(this, duration, warp);
  32355. };
  32356. _proto.stopFading = function stopFading() {
  32357. var weightInterpolant = this._weightInterpolant;
  32358. if (weightInterpolant !== null) {
  32359. this._weightInterpolant = null;
  32360. this._mixer._takeBackControlInterpolant(weightInterpolant);
  32361. }
  32362. return this;
  32363. } // Time Scale Control
  32364. // set the time scale stopping any scheduled warping
  32365. // although .paused = true yields an effective time scale of zero, this
  32366. // method does *not* change .paused, because it would be confusing
  32367. ;
  32368. _proto.setEffectiveTimeScale = function setEffectiveTimeScale(timeScale) {
  32369. this.timeScale = timeScale;
  32370. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  32371. return this.stopWarping();
  32372. } // return the time scale considering warping and .paused
  32373. ;
  32374. _proto.getEffectiveTimeScale = function getEffectiveTimeScale() {
  32375. return this._effectiveTimeScale;
  32376. };
  32377. _proto.setDuration = function setDuration(duration) {
  32378. this.timeScale = this._clip.duration / duration;
  32379. return this.stopWarping();
  32380. };
  32381. _proto.syncWith = function syncWith(action) {
  32382. this.time = action.time;
  32383. this.timeScale = action.timeScale;
  32384. return this.stopWarping();
  32385. };
  32386. _proto.halt = function halt(duration) {
  32387. return this.warp(this._effectiveTimeScale, 0, duration);
  32388. };
  32389. _proto.warp = function warp(startTimeScale, endTimeScale, duration) {
  32390. var mixer = this._mixer,
  32391. now = mixer.time,
  32392. timeScale = this.timeScale;
  32393. var interpolant = this._timeScaleInterpolant;
  32394. if (interpolant === null) {
  32395. interpolant = mixer._lendControlInterpolant();
  32396. this._timeScaleInterpolant = interpolant;
  32397. }
  32398. var times = interpolant.parameterPositions,
  32399. values = interpolant.sampleValues;
  32400. times[0] = now;
  32401. times[1] = now + duration;
  32402. values[0] = startTimeScale / timeScale;
  32403. values[1] = endTimeScale / timeScale;
  32404. return this;
  32405. };
  32406. _proto.stopWarping = function stopWarping() {
  32407. var timeScaleInterpolant = this._timeScaleInterpolant;
  32408. if (timeScaleInterpolant !== null) {
  32409. this._timeScaleInterpolant = null;
  32410. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  32411. }
  32412. return this;
  32413. } // Object Accessors
  32414. ;
  32415. _proto.getMixer = function getMixer() {
  32416. return this._mixer;
  32417. };
  32418. _proto.getClip = function getClip() {
  32419. return this._clip;
  32420. };
  32421. _proto.getRoot = function getRoot() {
  32422. return this._localRoot || this._mixer._root;
  32423. } // Interna
  32424. ;
  32425. _proto._update = function _update(time, deltaTime, timeDirection, accuIndex) {
  32426. // called by the mixer
  32427. if (!this.enabled) {
  32428. // call ._updateWeight() to update ._effectiveWeight
  32429. this._updateWeight(time);
  32430. return;
  32431. }
  32432. var startTime = this._startTime;
  32433. if (startTime !== null) {
  32434. // check for scheduled start of action
  32435. var timeRunning = (time - startTime) * timeDirection;
  32436. if (timeRunning < 0 || timeDirection === 0) {
  32437. return; // yet to come / don't decide when delta = 0
  32438. } // start
  32439. this._startTime = null; // unschedule
  32440. deltaTime = timeDirection * timeRunning;
  32441. } // apply time scale and advance time
  32442. deltaTime *= this._updateTimeScale(time);
  32443. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  32444. // an effective weight of 0
  32445. var weight = this._updateWeight(time);
  32446. if (weight > 0) {
  32447. var _interpolants = this._interpolants;
  32448. var propertyMixers = this._propertyBindings;
  32449. switch (this.blendMode) {
  32450. case AdditiveAnimationBlendMode:
  32451. for (var j = 0, m = _interpolants.length; j !== m; ++j) {
  32452. _interpolants[j].evaluate(clipTime);
  32453. propertyMixers[j].accumulateAdditive(weight);
  32454. }
  32455. break;
  32456. case NormalAnimationBlendMode:
  32457. default:
  32458. for (var _j = 0, _m = _interpolants.length; _j !== _m; ++_j) {
  32459. _interpolants[_j].evaluate(clipTime);
  32460. propertyMixers[_j].accumulate(accuIndex, weight);
  32461. }
  32462. }
  32463. }
  32464. };
  32465. _proto._updateWeight = function _updateWeight(time) {
  32466. var weight = 0;
  32467. if (this.enabled) {
  32468. weight = this.weight;
  32469. var interpolant = this._weightInterpolant;
  32470. if (interpolant !== null) {
  32471. var interpolantValue = interpolant.evaluate(time)[0];
  32472. weight *= interpolantValue;
  32473. if (time > interpolant.parameterPositions[1]) {
  32474. this.stopFading();
  32475. if (interpolantValue === 0) {
  32476. // faded out, disable
  32477. this.enabled = false;
  32478. }
  32479. }
  32480. }
  32481. }
  32482. this._effectiveWeight = weight;
  32483. return weight;
  32484. };
  32485. _proto._updateTimeScale = function _updateTimeScale(time) {
  32486. var timeScale = 0;
  32487. if (!this.paused) {
  32488. timeScale = this.timeScale;
  32489. var interpolant = this._timeScaleInterpolant;
  32490. if (interpolant !== null) {
  32491. var interpolantValue = interpolant.evaluate(time)[0];
  32492. timeScale *= interpolantValue;
  32493. if (time > interpolant.parameterPositions[1]) {
  32494. this.stopWarping();
  32495. if (timeScale === 0) {
  32496. // motion has halted, pause
  32497. this.paused = true;
  32498. } else {
  32499. // warp done - apply final time scale
  32500. this.timeScale = timeScale;
  32501. }
  32502. }
  32503. }
  32504. }
  32505. this._effectiveTimeScale = timeScale;
  32506. return timeScale;
  32507. };
  32508. _proto._updateTime = function _updateTime(deltaTime) {
  32509. var duration = this._clip.duration;
  32510. var loop = this.loop;
  32511. var time = this.time + deltaTime;
  32512. var loopCount = this._loopCount;
  32513. var pingPong = loop === LoopPingPong;
  32514. if (deltaTime === 0) {
  32515. if (loopCount === -1) return time;
  32516. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  32517. }
  32518. if (loop === LoopOnce) {
  32519. if (loopCount === -1) {
  32520. // just started
  32521. this._loopCount = 0;
  32522. this._setEndings(true, true, false);
  32523. }
  32524. handle_stop: {
  32525. if (time >= duration) {
  32526. time = duration;
  32527. } else if (time < 0) {
  32528. time = 0;
  32529. } else {
  32530. this.time = time;
  32531. break handle_stop;
  32532. }
  32533. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32534. this.time = time;
  32535. this._mixer.dispatchEvent({
  32536. type: 'finished',
  32537. action: this,
  32538. direction: deltaTime < 0 ? -1 : 1
  32539. });
  32540. }
  32541. } else {
  32542. // repetitive Repeat or PingPong
  32543. if (loopCount === -1) {
  32544. // just started
  32545. if (deltaTime >= 0) {
  32546. loopCount = 0;
  32547. this._setEndings(true, this.repetitions === 0, pingPong);
  32548. } else {
  32549. // when looping in reverse direction, the initial
  32550. // transition through zero counts as a repetition,
  32551. // so leave loopCount at -1
  32552. this._setEndings(this.repetitions === 0, true, pingPong);
  32553. }
  32554. }
  32555. if (time >= duration || time < 0) {
  32556. // wrap around
  32557. var loopDelta = Math.floor(time / duration); // signed
  32558. time -= duration * loopDelta;
  32559. loopCount += Math.abs(loopDelta);
  32560. var pending = this.repetitions - loopCount;
  32561. if (pending <= 0) {
  32562. // have to stop (switch state, clamp time, fire event)
  32563. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32564. time = deltaTime > 0 ? duration : 0;
  32565. this.time = time;
  32566. this._mixer.dispatchEvent({
  32567. type: 'finished',
  32568. action: this,
  32569. direction: deltaTime > 0 ? 1 : -1
  32570. });
  32571. } else {
  32572. // keep running
  32573. if (pending === 1) {
  32574. // entering the last round
  32575. var atStart = deltaTime < 0;
  32576. this._setEndings(atStart, !atStart, pingPong);
  32577. } else {
  32578. this._setEndings(false, false, pingPong);
  32579. }
  32580. this._loopCount = loopCount;
  32581. this.time = time;
  32582. this._mixer.dispatchEvent({
  32583. type: 'loop',
  32584. action: this,
  32585. loopDelta: loopDelta
  32586. });
  32587. }
  32588. } else {
  32589. this.time = time;
  32590. }
  32591. if (pingPong && (loopCount & 1) === 1) {
  32592. // invert time for the "pong round"
  32593. return duration - time;
  32594. }
  32595. }
  32596. return time;
  32597. };
  32598. _proto._setEndings = function _setEndings(atStart, atEnd, pingPong) {
  32599. var settings = this._interpolantSettings;
  32600. if (pingPong) {
  32601. settings.endingStart = ZeroSlopeEnding;
  32602. settings.endingEnd = ZeroSlopeEnding;
  32603. } else {
  32604. // assuming for LoopOnce atStart == atEnd == true
  32605. if (atStart) {
  32606. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32607. } else {
  32608. settings.endingStart = WrapAroundEnding;
  32609. }
  32610. if (atEnd) {
  32611. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32612. } else {
  32613. settings.endingEnd = WrapAroundEnding;
  32614. }
  32615. }
  32616. };
  32617. _proto._scheduleFading = function _scheduleFading(duration, weightNow, weightThen) {
  32618. var mixer = this._mixer,
  32619. now = mixer.time;
  32620. var interpolant = this._weightInterpolant;
  32621. if (interpolant === null) {
  32622. interpolant = mixer._lendControlInterpolant();
  32623. this._weightInterpolant = interpolant;
  32624. }
  32625. var times = interpolant.parameterPositions,
  32626. values = interpolant.sampleValues;
  32627. times[0] = now;
  32628. values[0] = weightNow;
  32629. times[1] = now + duration;
  32630. values[1] = weightThen;
  32631. return this;
  32632. };
  32633. return AnimationAction;
  32634. }();
  32635. function AnimationMixer(root) {
  32636. this._root = root;
  32637. this._initMemoryManager();
  32638. this._accuIndex = 0;
  32639. this.time = 0;
  32640. this.timeScale = 1.0;
  32641. }
  32642. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  32643. constructor: AnimationMixer,
  32644. _bindAction: function _bindAction(action, prototypeAction) {
  32645. var root = action._localRoot || this._root,
  32646. tracks = action._clip.tracks,
  32647. nTracks = tracks.length,
  32648. bindings = action._propertyBindings,
  32649. interpolants = action._interpolants,
  32650. rootUuid = root.uuid,
  32651. bindingsByRoot = this._bindingsByRootAndName;
  32652. var bindingsByName = bindingsByRoot[rootUuid];
  32653. if (bindingsByName === undefined) {
  32654. bindingsByName = {};
  32655. bindingsByRoot[rootUuid] = bindingsByName;
  32656. }
  32657. for (var i = 0; i !== nTracks; ++i) {
  32658. var track = tracks[i],
  32659. trackName = track.name;
  32660. var binding = bindingsByName[trackName];
  32661. if (binding !== undefined) {
  32662. bindings[i] = binding;
  32663. } else {
  32664. binding = bindings[i];
  32665. if (binding !== undefined) {
  32666. // existing binding, make sure the cache knows
  32667. if (binding._cacheIndex === null) {
  32668. ++binding.referenceCount;
  32669. this._addInactiveBinding(binding, rootUuid, trackName);
  32670. }
  32671. continue;
  32672. }
  32673. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  32674. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  32675. ++binding.referenceCount;
  32676. this._addInactiveBinding(binding, rootUuid, trackName);
  32677. bindings[i] = binding;
  32678. }
  32679. interpolants[i].resultBuffer = binding.buffer;
  32680. }
  32681. },
  32682. _activateAction: function _activateAction(action) {
  32683. if (!this._isActiveAction(action)) {
  32684. if (action._cacheIndex === null) {
  32685. // this action has been forgotten by the cache, but the user
  32686. // appears to be still using it -> rebind
  32687. var rootUuid = (action._localRoot || this._root).uuid,
  32688. clipUuid = action._clip.uuid,
  32689. actionsForClip = this._actionsByClip[clipUuid];
  32690. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  32691. this._addInactiveAction(action, clipUuid, rootUuid);
  32692. }
  32693. var bindings = action._propertyBindings; // increment reference counts / sort out state
  32694. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32695. var binding = bindings[i];
  32696. if (binding.useCount++ === 0) {
  32697. this._lendBinding(binding);
  32698. binding.saveOriginalState();
  32699. }
  32700. }
  32701. this._lendAction(action);
  32702. }
  32703. },
  32704. _deactivateAction: function _deactivateAction(action) {
  32705. if (this._isActiveAction(action)) {
  32706. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  32707. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32708. var binding = bindings[i];
  32709. if (--binding.useCount === 0) {
  32710. binding.restoreOriginalState();
  32711. this._takeBackBinding(binding);
  32712. }
  32713. }
  32714. this._takeBackAction(action);
  32715. }
  32716. },
  32717. // Memory manager
  32718. _initMemoryManager: function _initMemoryManager() {
  32719. this._actions = []; // 'nActiveActions' followed by inactive ones
  32720. this._nActiveActions = 0;
  32721. this._actionsByClip = {}; // inside:
  32722. // {
  32723. // knownActions: Array< AnimationAction > - used as prototypes
  32724. // actionByRoot: AnimationAction - lookup
  32725. // }
  32726. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  32727. this._nActiveBindings = 0;
  32728. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  32729. this._controlInterpolants = []; // same game as above
  32730. this._nActiveControlInterpolants = 0;
  32731. var scope = this;
  32732. this.stats = {
  32733. actions: {
  32734. get total() {
  32735. return scope._actions.length;
  32736. },
  32737. get inUse() {
  32738. return scope._nActiveActions;
  32739. }
  32740. },
  32741. bindings: {
  32742. get total() {
  32743. return scope._bindings.length;
  32744. },
  32745. get inUse() {
  32746. return scope._nActiveBindings;
  32747. }
  32748. },
  32749. controlInterpolants: {
  32750. get total() {
  32751. return scope._controlInterpolants.length;
  32752. },
  32753. get inUse() {
  32754. return scope._nActiveControlInterpolants;
  32755. }
  32756. }
  32757. };
  32758. },
  32759. // Memory management for AnimationAction objects
  32760. _isActiveAction: function _isActiveAction(action) {
  32761. var index = action._cacheIndex;
  32762. return index !== null && index < this._nActiveActions;
  32763. },
  32764. _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {
  32765. var actions = this._actions,
  32766. actionsByClip = this._actionsByClip;
  32767. var actionsForClip = actionsByClip[clipUuid];
  32768. if (actionsForClip === undefined) {
  32769. actionsForClip = {
  32770. knownActions: [action],
  32771. actionByRoot: {}
  32772. };
  32773. action._byClipCacheIndex = 0;
  32774. actionsByClip[clipUuid] = actionsForClip;
  32775. } else {
  32776. var knownActions = actionsForClip.knownActions;
  32777. action._byClipCacheIndex = knownActions.length;
  32778. knownActions.push(action);
  32779. }
  32780. action._cacheIndex = actions.length;
  32781. actions.push(action);
  32782. actionsForClip.actionByRoot[rootUuid] = action;
  32783. },
  32784. _removeInactiveAction: function _removeInactiveAction(action) {
  32785. var actions = this._actions,
  32786. lastInactiveAction = actions[actions.length - 1],
  32787. cacheIndex = action._cacheIndex;
  32788. lastInactiveAction._cacheIndex = cacheIndex;
  32789. actions[cacheIndex] = lastInactiveAction;
  32790. actions.pop();
  32791. action._cacheIndex = null;
  32792. var clipUuid = action._clip.uuid,
  32793. actionsByClip = this._actionsByClip,
  32794. actionsForClip = actionsByClip[clipUuid],
  32795. knownActionsForClip = actionsForClip.knownActions,
  32796. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  32797. byClipCacheIndex = action._byClipCacheIndex;
  32798. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  32799. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  32800. knownActionsForClip.pop();
  32801. action._byClipCacheIndex = null;
  32802. var actionByRoot = actionsForClip.actionByRoot,
  32803. rootUuid = (action._localRoot || this._root).uuid;
  32804. delete actionByRoot[rootUuid];
  32805. if (knownActionsForClip.length === 0) {
  32806. delete actionsByClip[clipUuid];
  32807. }
  32808. this._removeInactiveBindingsForAction(action);
  32809. },
  32810. _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {
  32811. var bindings = action._propertyBindings;
  32812. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32813. var binding = bindings[i];
  32814. if (--binding.referenceCount === 0) {
  32815. this._removeInactiveBinding(binding);
  32816. }
  32817. }
  32818. },
  32819. _lendAction: function _lendAction(action) {
  32820. // [ active actions | inactive actions ]
  32821. // [ active actions >| inactive actions ]
  32822. // s a
  32823. // <-swap->
  32824. // a s
  32825. var actions = this._actions,
  32826. prevIndex = action._cacheIndex,
  32827. lastActiveIndex = this._nActiveActions++,
  32828. firstInactiveAction = actions[lastActiveIndex];
  32829. action._cacheIndex = lastActiveIndex;
  32830. actions[lastActiveIndex] = action;
  32831. firstInactiveAction._cacheIndex = prevIndex;
  32832. actions[prevIndex] = firstInactiveAction;
  32833. },
  32834. _takeBackAction: function _takeBackAction(action) {
  32835. // [ active actions | inactive actions ]
  32836. // [ active actions |< inactive actions ]
  32837. // a s
  32838. // <-swap->
  32839. // s a
  32840. var actions = this._actions,
  32841. prevIndex = action._cacheIndex,
  32842. firstInactiveIndex = --this._nActiveActions,
  32843. lastActiveAction = actions[firstInactiveIndex];
  32844. action._cacheIndex = firstInactiveIndex;
  32845. actions[firstInactiveIndex] = action;
  32846. lastActiveAction._cacheIndex = prevIndex;
  32847. actions[prevIndex] = lastActiveAction;
  32848. },
  32849. // Memory management for PropertyMixer objects
  32850. _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {
  32851. var bindingsByRoot = this._bindingsByRootAndName,
  32852. bindings = this._bindings;
  32853. var bindingByName = bindingsByRoot[rootUuid];
  32854. if (bindingByName === undefined) {
  32855. bindingByName = {};
  32856. bindingsByRoot[rootUuid] = bindingByName;
  32857. }
  32858. bindingByName[trackName] = binding;
  32859. binding._cacheIndex = bindings.length;
  32860. bindings.push(binding);
  32861. },
  32862. _removeInactiveBinding: function _removeInactiveBinding(binding) {
  32863. var bindings = this._bindings,
  32864. propBinding = binding.binding,
  32865. rootUuid = propBinding.rootNode.uuid,
  32866. trackName = propBinding.path,
  32867. bindingsByRoot = this._bindingsByRootAndName,
  32868. bindingByName = bindingsByRoot[rootUuid],
  32869. lastInactiveBinding = bindings[bindings.length - 1],
  32870. cacheIndex = binding._cacheIndex;
  32871. lastInactiveBinding._cacheIndex = cacheIndex;
  32872. bindings[cacheIndex] = lastInactiveBinding;
  32873. bindings.pop();
  32874. delete bindingByName[trackName];
  32875. if (Object.keys(bindingByName).length === 0) {
  32876. delete bindingsByRoot[rootUuid];
  32877. }
  32878. },
  32879. _lendBinding: function _lendBinding(binding) {
  32880. var bindings = this._bindings,
  32881. prevIndex = binding._cacheIndex,
  32882. lastActiveIndex = this._nActiveBindings++,
  32883. firstInactiveBinding = bindings[lastActiveIndex];
  32884. binding._cacheIndex = lastActiveIndex;
  32885. bindings[lastActiveIndex] = binding;
  32886. firstInactiveBinding._cacheIndex = prevIndex;
  32887. bindings[prevIndex] = firstInactiveBinding;
  32888. },
  32889. _takeBackBinding: function _takeBackBinding(binding) {
  32890. var bindings = this._bindings,
  32891. prevIndex = binding._cacheIndex,
  32892. firstInactiveIndex = --this._nActiveBindings,
  32893. lastActiveBinding = bindings[firstInactiveIndex];
  32894. binding._cacheIndex = firstInactiveIndex;
  32895. bindings[firstInactiveIndex] = binding;
  32896. lastActiveBinding._cacheIndex = prevIndex;
  32897. bindings[prevIndex] = lastActiveBinding;
  32898. },
  32899. // Memory management of Interpolants for weight and time scale
  32900. _lendControlInterpolant: function _lendControlInterpolant() {
  32901. var interpolants = this._controlInterpolants,
  32902. lastActiveIndex = this._nActiveControlInterpolants++;
  32903. var interpolant = interpolants[lastActiveIndex];
  32904. if (interpolant === undefined) {
  32905. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  32906. interpolant.__cacheIndex = lastActiveIndex;
  32907. interpolants[lastActiveIndex] = interpolant;
  32908. }
  32909. return interpolant;
  32910. },
  32911. _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {
  32912. var interpolants = this._controlInterpolants,
  32913. prevIndex = interpolant.__cacheIndex,
  32914. firstInactiveIndex = --this._nActiveControlInterpolants,
  32915. lastActiveInterpolant = interpolants[firstInactiveIndex];
  32916. interpolant.__cacheIndex = firstInactiveIndex;
  32917. interpolants[firstInactiveIndex] = interpolant;
  32918. lastActiveInterpolant.__cacheIndex = prevIndex;
  32919. interpolants[prevIndex] = lastActiveInterpolant;
  32920. },
  32921. _controlInterpolantsResultBuffer: new Float32Array(1),
  32922. // return an action for a clip optionally using a custom root target
  32923. // object (this method allocates a lot of dynamic memory in case a
  32924. // previously unknown clip/root combination is specified)
  32925. clipAction: function clipAction(clip, optionalRoot, blendMode) {
  32926. var root = optionalRoot || this._root,
  32927. rootUuid = root.uuid;
  32928. var clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  32929. var clipUuid = clipObject !== null ? clipObject.uuid : clip;
  32930. var actionsForClip = this._actionsByClip[clipUuid];
  32931. var prototypeAction = null;
  32932. if (blendMode === undefined) {
  32933. if (clipObject !== null) {
  32934. blendMode = clipObject.blendMode;
  32935. } else {
  32936. blendMode = NormalAnimationBlendMode;
  32937. }
  32938. }
  32939. if (actionsForClip !== undefined) {
  32940. var existingAction = actionsForClip.actionByRoot[rootUuid];
  32941. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  32942. return existingAction;
  32943. } // we know the clip, so we don't have to parse all
  32944. // the bindings again but can just copy
  32945. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  32946. if (clipObject === null) clipObject = prototypeAction._clip;
  32947. } // clip must be known when specified via string
  32948. if (clipObject === null) return null; // allocate all resources required to run it
  32949. var newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  32950. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  32951. this._addInactiveAction(newAction, clipUuid, rootUuid);
  32952. return newAction;
  32953. },
  32954. // get an existing action
  32955. existingAction: function existingAction(clip, optionalRoot) {
  32956. var root = optionalRoot || this._root,
  32957. rootUuid = root.uuid,
  32958. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  32959. clipUuid = clipObject ? clipObject.uuid : clip,
  32960. actionsForClip = this._actionsByClip[clipUuid];
  32961. if (actionsForClip !== undefined) {
  32962. return actionsForClip.actionByRoot[rootUuid] || null;
  32963. }
  32964. return null;
  32965. },
  32966. // deactivates all previously scheduled actions
  32967. stopAllAction: function stopAllAction() {
  32968. var actions = this._actions,
  32969. nActions = this._nActiveActions;
  32970. for (var i = nActions - 1; i >= 0; --i) {
  32971. actions[i].stop();
  32972. }
  32973. return this;
  32974. },
  32975. // advance the time and update apply the animation
  32976. update: function update(deltaTime) {
  32977. deltaTime *= this.timeScale;
  32978. var actions = this._actions,
  32979. nActions = this._nActiveActions,
  32980. time = this.time += deltaTime,
  32981. timeDirection = Math.sign(deltaTime),
  32982. accuIndex = this._accuIndex ^= 1; // run active actions
  32983. for (var i = 0; i !== nActions; ++i) {
  32984. var action = actions[i];
  32985. action._update(time, deltaTime, timeDirection, accuIndex);
  32986. } // update scene graph
  32987. var bindings = this._bindings,
  32988. nBindings = this._nActiveBindings;
  32989. for (var _i = 0; _i !== nBindings; ++_i) {
  32990. bindings[_i].apply(accuIndex);
  32991. }
  32992. return this;
  32993. },
  32994. // Allows you to seek to a specific time in an animation.
  32995. setTime: function setTime(timeInSeconds) {
  32996. this.time = 0; // Zero out time attribute for AnimationMixer object;
  32997. for (var i = 0; i < this._actions.length; i++) {
  32998. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  32999. }
  33000. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  33001. },
  33002. // return this mixer's root target object
  33003. getRoot: function getRoot() {
  33004. return this._root;
  33005. },
  33006. // free all resources specific to a particular clip
  33007. uncacheClip: function uncacheClip(clip) {
  33008. var actions = this._actions,
  33009. clipUuid = clip.uuid,
  33010. actionsByClip = this._actionsByClip,
  33011. actionsForClip = actionsByClip[clipUuid];
  33012. if (actionsForClip !== undefined) {
  33013. // note: just calling _removeInactiveAction would mess up the
  33014. // iteration state and also require updating the state we can
  33015. // just throw away
  33016. var actionsToRemove = actionsForClip.knownActions;
  33017. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  33018. var action = actionsToRemove[i];
  33019. this._deactivateAction(action);
  33020. var cacheIndex = action._cacheIndex,
  33021. lastInactiveAction = actions[actions.length - 1];
  33022. action._cacheIndex = null;
  33023. action._byClipCacheIndex = null;
  33024. lastInactiveAction._cacheIndex = cacheIndex;
  33025. actions[cacheIndex] = lastInactiveAction;
  33026. actions.pop();
  33027. this._removeInactiveBindingsForAction(action);
  33028. }
  33029. delete actionsByClip[clipUuid];
  33030. }
  33031. },
  33032. // free all resources specific to a particular root target object
  33033. uncacheRoot: function uncacheRoot(root) {
  33034. var rootUuid = root.uuid,
  33035. actionsByClip = this._actionsByClip;
  33036. for (var clipUuid in actionsByClip) {
  33037. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  33038. action = actionByRoot[rootUuid];
  33039. if (action !== undefined) {
  33040. this._deactivateAction(action);
  33041. this._removeInactiveAction(action);
  33042. }
  33043. }
  33044. var bindingsByRoot = this._bindingsByRootAndName,
  33045. bindingByName = bindingsByRoot[rootUuid];
  33046. if (bindingByName !== undefined) {
  33047. for (var trackName in bindingByName) {
  33048. var binding = bindingByName[trackName];
  33049. binding.restoreOriginalState();
  33050. this._removeInactiveBinding(binding);
  33051. }
  33052. }
  33053. },
  33054. // remove a targeted clip from the cache
  33055. uncacheAction: function uncacheAction(clip, optionalRoot) {
  33056. var action = this.existingAction(clip, optionalRoot);
  33057. if (action !== null) {
  33058. this._deactivateAction(action);
  33059. this._removeInactiveAction(action);
  33060. }
  33061. }
  33062. });
  33063. var Uniform = /*#__PURE__*/function () {
  33064. function Uniform(value) {
  33065. if (typeof value === 'string') {
  33066. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  33067. value = arguments[1];
  33068. }
  33069. this.value = value;
  33070. }
  33071. var _proto = Uniform.prototype;
  33072. _proto.clone = function clone() {
  33073. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  33074. };
  33075. return Uniform;
  33076. }();
  33077. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  33078. InterleavedBuffer.call(this, array, stride);
  33079. this.meshPerAttribute = meshPerAttribute || 1;
  33080. }
  33081. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  33082. constructor: InstancedInterleavedBuffer,
  33083. isInstancedInterleavedBuffer: true,
  33084. copy: function copy(source) {
  33085. InterleavedBuffer.prototype.copy.call(this, source);
  33086. this.meshPerAttribute = source.meshPerAttribute;
  33087. return this;
  33088. },
  33089. clone: function clone(data) {
  33090. var ib = InterleavedBuffer.prototype.clone.call(this, data);
  33091. ib.meshPerAttribute = this.meshPerAttribute;
  33092. return ib;
  33093. },
  33094. toJSON: function toJSON(data) {
  33095. var json = InterleavedBuffer.prototype.toJSON.call(this, data);
  33096. json.isInstancedInterleavedBuffer = true;
  33097. json.meshPerAttribute = this.meshPerAttribute;
  33098. return json;
  33099. }
  33100. });
  33101. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  33102. this.buffer = buffer;
  33103. this.type = type;
  33104. this.itemSize = itemSize;
  33105. this.elementSize = elementSize;
  33106. this.count = count;
  33107. this.version = 0;
  33108. }
  33109. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  33110. set: function set(value) {
  33111. if (value === true) this.version++;
  33112. }
  33113. });
  33114. Object.assign(GLBufferAttribute.prototype, {
  33115. isGLBufferAttribute: true,
  33116. setBuffer: function setBuffer(buffer) {
  33117. this.buffer = buffer;
  33118. return this;
  33119. },
  33120. setType: function setType(type, elementSize) {
  33121. this.type = type;
  33122. this.elementSize = elementSize;
  33123. return this;
  33124. },
  33125. setItemSize: function setItemSize(itemSize) {
  33126. this.itemSize = itemSize;
  33127. return this;
  33128. },
  33129. setCount: function setCount(count) {
  33130. this.count = count;
  33131. return this;
  33132. }
  33133. });
  33134. function Raycaster(origin, direction, near, far) {
  33135. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  33136. this.near = near || 0;
  33137. this.far = far || Infinity;
  33138. this.camera = null;
  33139. this.layers = new Layers();
  33140. this.params = {
  33141. Mesh: {},
  33142. Line: {
  33143. threshold: 1
  33144. },
  33145. LOD: {},
  33146. Points: {
  33147. threshold: 1
  33148. },
  33149. Sprite: {}
  33150. };
  33151. Object.defineProperties(this.params, {
  33152. PointCloud: {
  33153. get: function get() {
  33154. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  33155. return this.Points;
  33156. }
  33157. }
  33158. });
  33159. }
  33160. function ascSort(a, b) {
  33161. return a.distance - b.distance;
  33162. }
  33163. function _intersectObject(object, raycaster, intersects, recursive) {
  33164. if (object.layers.test(raycaster.layers)) {
  33165. object.raycast(raycaster, intersects);
  33166. }
  33167. if (recursive === true) {
  33168. var children = object.children;
  33169. for (var i = 0, l = children.length; i < l; i++) {
  33170. _intersectObject(children[i], raycaster, intersects, true);
  33171. }
  33172. }
  33173. }
  33174. Object.assign(Raycaster.prototype, {
  33175. set: function set(origin, direction) {
  33176. // direction is assumed to be normalized (for accurate distance calculations)
  33177. this.ray.set(origin, direction);
  33178. },
  33179. setFromCamera: function setFromCamera(coords, camera) {
  33180. if (camera && camera.isPerspectiveCamera) {
  33181. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  33182. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  33183. this.camera = camera;
  33184. } else if (camera && camera.isOrthographicCamera) {
  33185. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  33186. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  33187. this.camera = camera;
  33188. } else {
  33189. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  33190. }
  33191. },
  33192. intersectObject: function intersectObject(object, recursive, optionalTarget) {
  33193. var intersects = optionalTarget || [];
  33194. _intersectObject(object, this, intersects, recursive);
  33195. intersects.sort(ascSort);
  33196. return intersects;
  33197. },
  33198. intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {
  33199. var intersects = optionalTarget || [];
  33200. if (Array.isArray(objects) === false) {
  33201. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  33202. return intersects;
  33203. }
  33204. for (var i = 0, l = objects.length; i < l; i++) {
  33205. _intersectObject(objects[i], this, intersects, recursive);
  33206. }
  33207. intersects.sort(ascSort);
  33208. return intersects;
  33209. }
  33210. });
  33211. /**
  33212. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  33213. *
  33214. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  33215. * The azimuthal angle (theta) is measured from the positive z-axis.
  33216. */
  33217. var Spherical = /*#__PURE__*/function () {
  33218. function Spherical(radius, phi, theta) {
  33219. if (radius === void 0) {
  33220. radius = 1;
  33221. }
  33222. if (phi === void 0) {
  33223. phi = 0;
  33224. }
  33225. if (theta === void 0) {
  33226. theta = 0;
  33227. }
  33228. this.radius = radius;
  33229. this.phi = phi; // polar angle
  33230. this.theta = theta; // azimuthal angle
  33231. return this;
  33232. }
  33233. var _proto = Spherical.prototype;
  33234. _proto.set = function set(radius, phi, theta) {
  33235. this.radius = radius;
  33236. this.phi = phi;
  33237. this.theta = theta;
  33238. return this;
  33239. };
  33240. _proto.clone = function clone() {
  33241. return new this.constructor().copy(this);
  33242. };
  33243. _proto.copy = function copy(other) {
  33244. this.radius = other.radius;
  33245. this.phi = other.phi;
  33246. this.theta = other.theta;
  33247. return this;
  33248. } // restrict phi to be betwee EPS and PI-EPS
  33249. ;
  33250. _proto.makeSafe = function makeSafe() {
  33251. var EPS = 0.000001;
  33252. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  33253. return this;
  33254. };
  33255. _proto.setFromVector3 = function setFromVector3(v) {
  33256. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33257. };
  33258. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33259. this.radius = Math.sqrt(x * x + y * y + z * z);
  33260. if (this.radius === 0) {
  33261. this.theta = 0;
  33262. this.phi = 0;
  33263. } else {
  33264. this.theta = Math.atan2(x, z);
  33265. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  33266. }
  33267. return this;
  33268. };
  33269. return Spherical;
  33270. }();
  33271. /**
  33272. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  33273. */
  33274. var Cylindrical = /*#__PURE__*/function () {
  33275. function Cylindrical(radius, theta, y) {
  33276. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  33277. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  33278. this.y = y !== undefined ? y : 0; // height above the x-z plane
  33279. return this;
  33280. }
  33281. var _proto = Cylindrical.prototype;
  33282. _proto.set = function set(radius, theta, y) {
  33283. this.radius = radius;
  33284. this.theta = theta;
  33285. this.y = y;
  33286. return this;
  33287. };
  33288. _proto.clone = function clone() {
  33289. return new this.constructor().copy(this);
  33290. };
  33291. _proto.copy = function copy(other) {
  33292. this.radius = other.radius;
  33293. this.theta = other.theta;
  33294. this.y = other.y;
  33295. return this;
  33296. };
  33297. _proto.setFromVector3 = function setFromVector3(v) {
  33298. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33299. };
  33300. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33301. this.radius = Math.sqrt(x * x + z * z);
  33302. this.theta = Math.atan2(x, z);
  33303. this.y = y;
  33304. return this;
  33305. };
  33306. return Cylindrical;
  33307. }();
  33308. var _vector$8 = /*@__PURE__*/new Vector2();
  33309. var Box2 = /*#__PURE__*/function () {
  33310. function Box2(min, max) {
  33311. Object.defineProperty(this, 'isBox2', {
  33312. value: true
  33313. });
  33314. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  33315. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  33316. }
  33317. var _proto = Box2.prototype;
  33318. _proto.set = function set(min, max) {
  33319. this.min.copy(min);
  33320. this.max.copy(max);
  33321. return this;
  33322. };
  33323. _proto.setFromPoints = function setFromPoints(points) {
  33324. this.makeEmpty();
  33325. for (var i = 0, il = points.length; i < il; i++) {
  33326. this.expandByPoint(points[i]);
  33327. }
  33328. return this;
  33329. };
  33330. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  33331. var halfSize = _vector$8.copy(size).multiplyScalar(0.5);
  33332. this.min.copy(center).sub(halfSize);
  33333. this.max.copy(center).add(halfSize);
  33334. return this;
  33335. };
  33336. _proto.clone = function clone() {
  33337. return new this.constructor().copy(this);
  33338. };
  33339. _proto.copy = function copy(box) {
  33340. this.min.copy(box.min);
  33341. this.max.copy(box.max);
  33342. return this;
  33343. };
  33344. _proto.makeEmpty = function makeEmpty() {
  33345. this.min.x = this.min.y = +Infinity;
  33346. this.max.x = this.max.y = -Infinity;
  33347. return this;
  33348. };
  33349. _proto.isEmpty = function isEmpty() {
  33350. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  33351. return this.max.x < this.min.x || this.max.y < this.min.y;
  33352. };
  33353. _proto.getCenter = function getCenter(target) {
  33354. if (target === undefined) {
  33355. console.warn('THREE.Box2: .getCenter() target is now required');
  33356. target = new Vector2();
  33357. }
  33358. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  33359. };
  33360. _proto.getSize = function getSize(target) {
  33361. if (target === undefined) {
  33362. console.warn('THREE.Box2: .getSize() target is now required');
  33363. target = new Vector2();
  33364. }
  33365. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  33366. };
  33367. _proto.expandByPoint = function expandByPoint(point) {
  33368. this.min.min(point);
  33369. this.max.max(point);
  33370. return this;
  33371. };
  33372. _proto.expandByVector = function expandByVector(vector) {
  33373. this.min.sub(vector);
  33374. this.max.add(vector);
  33375. return this;
  33376. };
  33377. _proto.expandByScalar = function expandByScalar(scalar) {
  33378. this.min.addScalar(-scalar);
  33379. this.max.addScalar(scalar);
  33380. return this;
  33381. };
  33382. _proto.containsPoint = function containsPoint(point) {
  33383. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  33384. };
  33385. _proto.containsBox = function containsBox(box) {
  33386. 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;
  33387. };
  33388. _proto.getParameter = function getParameter(point, target) {
  33389. // This can potentially have a divide by zero if the box
  33390. // has a size dimension of 0.
  33391. if (target === undefined) {
  33392. console.warn('THREE.Box2: .getParameter() target is now required');
  33393. target = new Vector2();
  33394. }
  33395. 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));
  33396. };
  33397. _proto.intersectsBox = function intersectsBox(box) {
  33398. // using 4 splitting planes to rule out intersections
  33399. 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;
  33400. };
  33401. _proto.clampPoint = function clampPoint(point, target) {
  33402. if (target === undefined) {
  33403. console.warn('THREE.Box2: .clampPoint() target is now required');
  33404. target = new Vector2();
  33405. }
  33406. return target.copy(point).clamp(this.min, this.max);
  33407. };
  33408. _proto.distanceToPoint = function distanceToPoint(point) {
  33409. var clampedPoint = _vector$8.copy(point).clamp(this.min, this.max);
  33410. return clampedPoint.sub(point).length();
  33411. };
  33412. _proto.intersect = function intersect(box) {
  33413. this.min.max(box.min);
  33414. this.max.min(box.max);
  33415. return this;
  33416. };
  33417. _proto.union = function union(box) {
  33418. this.min.min(box.min);
  33419. this.max.max(box.max);
  33420. return this;
  33421. };
  33422. _proto.translate = function translate(offset) {
  33423. this.min.add(offset);
  33424. this.max.add(offset);
  33425. return this;
  33426. };
  33427. _proto.equals = function equals(box) {
  33428. return box.min.equals(this.min) && box.max.equals(this.max);
  33429. };
  33430. return Box2;
  33431. }();
  33432. var _startP = /*@__PURE__*/new Vector3();
  33433. var _startEnd = /*@__PURE__*/new Vector3();
  33434. var Line3 = /*#__PURE__*/function () {
  33435. function Line3(start, end) {
  33436. this.start = start !== undefined ? start : new Vector3();
  33437. this.end = end !== undefined ? end : new Vector3();
  33438. }
  33439. var _proto = Line3.prototype;
  33440. _proto.set = function set(start, end) {
  33441. this.start.copy(start);
  33442. this.end.copy(end);
  33443. return this;
  33444. };
  33445. _proto.clone = function clone() {
  33446. return new this.constructor().copy(this);
  33447. };
  33448. _proto.copy = function copy(line) {
  33449. this.start.copy(line.start);
  33450. this.end.copy(line.end);
  33451. return this;
  33452. };
  33453. _proto.getCenter = function getCenter(target) {
  33454. if (target === undefined) {
  33455. console.warn('THREE.Line3: .getCenter() target is now required');
  33456. target = new Vector3();
  33457. }
  33458. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  33459. };
  33460. _proto.delta = function delta(target) {
  33461. if (target === undefined) {
  33462. console.warn('THREE.Line3: .delta() target is now required');
  33463. target = new Vector3();
  33464. }
  33465. return target.subVectors(this.end, this.start);
  33466. };
  33467. _proto.distanceSq = function distanceSq() {
  33468. return this.start.distanceToSquared(this.end);
  33469. };
  33470. _proto.distance = function distance() {
  33471. return this.start.distanceTo(this.end);
  33472. };
  33473. _proto.at = function at(t, target) {
  33474. if (target === undefined) {
  33475. console.warn('THREE.Line3: .at() target is now required');
  33476. target = new Vector3();
  33477. }
  33478. return this.delta(target).multiplyScalar(t).add(this.start);
  33479. };
  33480. _proto.closestPointToPointParameter = function closestPointToPointParameter(point, clampToLine) {
  33481. _startP.subVectors(point, this.start);
  33482. _startEnd.subVectors(this.end, this.start);
  33483. var startEnd2 = _startEnd.dot(_startEnd);
  33484. var startEnd_startP = _startEnd.dot(_startP);
  33485. var t = startEnd_startP / startEnd2;
  33486. if (clampToLine) {
  33487. t = MathUtils.clamp(t, 0, 1);
  33488. }
  33489. return t;
  33490. };
  33491. _proto.closestPointToPoint = function closestPointToPoint(point, clampToLine, target) {
  33492. var t = this.closestPointToPointParameter(point, clampToLine);
  33493. if (target === undefined) {
  33494. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  33495. target = new Vector3();
  33496. }
  33497. return this.delta(target).multiplyScalar(t).add(this.start);
  33498. };
  33499. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  33500. this.start.applyMatrix4(matrix);
  33501. this.end.applyMatrix4(matrix);
  33502. return this;
  33503. };
  33504. _proto.equals = function equals(line) {
  33505. return line.start.equals(this.start) && line.end.equals(this.end);
  33506. };
  33507. return Line3;
  33508. }();
  33509. function ImmediateRenderObject(material) {
  33510. Object3D.call(this);
  33511. this.material = material;
  33512. this.render = function ()
  33513. /* renderCallback */
  33514. {};
  33515. this.hasPositions = false;
  33516. this.hasNormals = false;
  33517. this.hasColors = false;
  33518. this.hasUvs = false;
  33519. this.positionArray = null;
  33520. this.normalArray = null;
  33521. this.colorArray = null;
  33522. this.uvArray = null;
  33523. this.count = 0;
  33524. }
  33525. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  33526. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  33527. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  33528. var _vector$9 = /*@__PURE__*/new Vector3();
  33529. var SpotLightHelper = /*#__PURE__*/function (_Object3D) {
  33530. _inheritsLoose(SpotLightHelper, _Object3D);
  33531. function SpotLightHelper(light, color) {
  33532. var _this;
  33533. _this = _Object3D.call(this) || this;
  33534. _this.light = light;
  33535. _this.light.updateMatrixWorld();
  33536. _this.matrix = light.matrixWorld;
  33537. _this.matrixAutoUpdate = false;
  33538. _this.color = color;
  33539. var geometry = new BufferGeometry();
  33540. 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];
  33541. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  33542. var p1 = i / l * Math.PI * 2;
  33543. var p2 = j / l * Math.PI * 2;
  33544. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  33545. }
  33546. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  33547. var material = new LineBasicMaterial({
  33548. fog: false,
  33549. toneMapped: false
  33550. });
  33551. _this.cone = new LineSegments(geometry, material);
  33552. _this.add(_this.cone);
  33553. _this.update();
  33554. return _this;
  33555. }
  33556. var _proto = SpotLightHelper.prototype;
  33557. _proto.dispose = function dispose() {
  33558. this.cone.geometry.dispose();
  33559. this.cone.material.dispose();
  33560. };
  33561. _proto.update = function update() {
  33562. this.light.updateMatrixWorld();
  33563. var coneLength = this.light.distance ? this.light.distance : 1000;
  33564. var coneWidth = coneLength * Math.tan(this.light.angle);
  33565. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  33566. _vector$9.setFromMatrixPosition(this.light.target.matrixWorld);
  33567. this.cone.lookAt(_vector$9);
  33568. if (this.color !== undefined) {
  33569. this.cone.material.color.set(this.color);
  33570. } else {
  33571. this.cone.material.color.copy(this.light.color);
  33572. }
  33573. };
  33574. return SpotLightHelper;
  33575. }(Object3D);
  33576. var _vector$a = /*@__PURE__*/new Vector3();
  33577. var _boneMatrix = /*@__PURE__*/new Matrix4();
  33578. var _matrixWorldInv = /*@__PURE__*/new Matrix4();
  33579. var SkeletonHelper = /*#__PURE__*/function (_LineSegments) {
  33580. _inheritsLoose(SkeletonHelper, _LineSegments);
  33581. function SkeletonHelper(object) {
  33582. var _this;
  33583. var bones = getBoneList(object);
  33584. var geometry = new BufferGeometry();
  33585. var vertices = [];
  33586. var colors = [];
  33587. var color1 = new Color(0, 0, 1);
  33588. var color2 = new Color(0, 1, 0);
  33589. for (var i = 0; i < bones.length; i++) {
  33590. var bone = bones[i];
  33591. if (bone.parent && bone.parent.isBone) {
  33592. vertices.push(0, 0, 0);
  33593. vertices.push(0, 0, 0);
  33594. colors.push(color1.r, color1.g, color1.b);
  33595. colors.push(color2.r, color2.g, color2.b);
  33596. }
  33597. }
  33598. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33599. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33600. var material = new LineBasicMaterial({
  33601. vertexColors: true,
  33602. depthTest: false,
  33603. depthWrite: false,
  33604. toneMapped: false,
  33605. transparent: true
  33606. });
  33607. _this = _LineSegments.call(this, geometry, material) || this;
  33608. _this.type = 'SkeletonHelper';
  33609. _this.isSkeletonHelper = true;
  33610. _this.root = object;
  33611. _this.bones = bones;
  33612. _this.matrix = object.matrixWorld;
  33613. _this.matrixAutoUpdate = false;
  33614. return _this;
  33615. }
  33616. var _proto = SkeletonHelper.prototype;
  33617. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  33618. var bones = this.bones;
  33619. var geometry = this.geometry;
  33620. var position = geometry.getAttribute('position');
  33621. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  33622. for (var i = 0, j = 0; i < bones.length; i++) {
  33623. var bone = bones[i];
  33624. if (bone.parent && bone.parent.isBone) {
  33625. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  33626. _vector$a.setFromMatrixPosition(_boneMatrix);
  33627. position.setXYZ(j, _vector$a.x, _vector$a.y, _vector$a.z);
  33628. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  33629. _vector$a.setFromMatrixPosition(_boneMatrix);
  33630. position.setXYZ(j + 1, _vector$a.x, _vector$a.y, _vector$a.z);
  33631. j += 2;
  33632. }
  33633. }
  33634. geometry.getAttribute('position').needsUpdate = true;
  33635. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  33636. };
  33637. return SkeletonHelper;
  33638. }(LineSegments);
  33639. function getBoneList(object) {
  33640. var boneList = [];
  33641. if (object && object.isBone) {
  33642. boneList.push(object);
  33643. }
  33644. for (var i = 0; i < object.children.length; i++) {
  33645. boneList.push.apply(boneList, getBoneList(object.children[i]));
  33646. }
  33647. return boneList;
  33648. }
  33649. var PointLightHelper = /*#__PURE__*/function (_Mesh) {
  33650. _inheritsLoose(PointLightHelper, _Mesh);
  33651. function PointLightHelper(light, sphereSize, color) {
  33652. var _this;
  33653. var geometry = new SphereGeometry(sphereSize, 4, 2);
  33654. var material = new MeshBasicMaterial({
  33655. wireframe: true,
  33656. fog: false,
  33657. toneMapped: false
  33658. });
  33659. _this = _Mesh.call(this, geometry, material) || this;
  33660. _this.light = light;
  33661. _this.light.updateMatrixWorld();
  33662. _this.color = color;
  33663. _this.type = 'PointLightHelper';
  33664. _this.matrix = _this.light.matrixWorld;
  33665. _this.matrixAutoUpdate = false;
  33666. _this.update();
  33667. /*
  33668. // TODO: delete this comment?
  33669. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  33670. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  33671. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  33672. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  33673. const d = light.distance;
  33674. if ( d === 0.0 ) {
  33675. this.lightDistance.visible = false;
  33676. } else {
  33677. this.lightDistance.scale.set( d, d, d );
  33678. }
  33679. this.add( this.lightDistance );
  33680. */
  33681. return _this;
  33682. }
  33683. var _proto = PointLightHelper.prototype;
  33684. _proto.dispose = function dispose() {
  33685. this.geometry.dispose();
  33686. this.material.dispose();
  33687. };
  33688. _proto.update = function update() {
  33689. if (this.color !== undefined) {
  33690. this.material.color.set(this.color);
  33691. } else {
  33692. this.material.color.copy(this.light.color);
  33693. }
  33694. /*
  33695. const d = this.light.distance;
  33696. if ( d === 0.0 ) {
  33697. this.lightDistance.visible = false;
  33698. } else {
  33699. this.lightDistance.visible = true;
  33700. this.lightDistance.scale.set( d, d, d );
  33701. }
  33702. */
  33703. };
  33704. return PointLightHelper;
  33705. }(Mesh);
  33706. var _vector$b = /*@__PURE__*/new Vector3();
  33707. var _color1 = /*@__PURE__*/new Color();
  33708. var _color2 = /*@__PURE__*/new Color();
  33709. var HemisphereLightHelper = /*#__PURE__*/function (_Object3D) {
  33710. _inheritsLoose(HemisphereLightHelper, _Object3D);
  33711. function HemisphereLightHelper(light, size, color) {
  33712. var _this;
  33713. _this = _Object3D.call(this) || this;
  33714. _this.light = light;
  33715. _this.light.updateMatrixWorld();
  33716. _this.matrix = light.matrixWorld;
  33717. _this.matrixAutoUpdate = false;
  33718. _this.color = color;
  33719. var geometry = new OctahedronGeometry(size);
  33720. geometry.rotateY(Math.PI * 0.5);
  33721. _this.material = new MeshBasicMaterial({
  33722. wireframe: true,
  33723. fog: false,
  33724. toneMapped: false
  33725. });
  33726. if (_this.color === undefined) _this.material.vertexColors = true;
  33727. var position = geometry.getAttribute('position');
  33728. var colors = new Float32Array(position.count * 3);
  33729. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  33730. _this.add(new Mesh(geometry, _this.material));
  33731. _this.update();
  33732. return _this;
  33733. }
  33734. var _proto = HemisphereLightHelper.prototype;
  33735. _proto.dispose = function dispose() {
  33736. this.children[0].geometry.dispose();
  33737. this.children[0].material.dispose();
  33738. };
  33739. _proto.update = function update() {
  33740. var mesh = this.children[0];
  33741. if (this.color !== undefined) {
  33742. this.material.color.set(this.color);
  33743. } else {
  33744. var colors = mesh.geometry.getAttribute('color');
  33745. _color1.copy(this.light.color);
  33746. _color2.copy(this.light.groundColor);
  33747. for (var i = 0, l = colors.count; i < l; i++) {
  33748. var color = i < l / 2 ? _color1 : _color2;
  33749. colors.setXYZ(i, color.r, color.g, color.b);
  33750. }
  33751. colors.needsUpdate = true;
  33752. }
  33753. mesh.lookAt(_vector$b.setFromMatrixPosition(this.light.matrixWorld).negate());
  33754. };
  33755. return HemisphereLightHelper;
  33756. }(Object3D);
  33757. var GridHelper = /*#__PURE__*/function (_LineSegments) {
  33758. _inheritsLoose(GridHelper, _LineSegments);
  33759. function GridHelper(size, divisions, color1, color2) {
  33760. var _this;
  33761. if (size === void 0) {
  33762. size = 10;
  33763. }
  33764. if (divisions === void 0) {
  33765. divisions = 10;
  33766. }
  33767. if (color1 === void 0) {
  33768. color1 = 0x444444;
  33769. }
  33770. if (color2 === void 0) {
  33771. color2 = 0x888888;
  33772. }
  33773. color1 = new Color(color1);
  33774. color2 = new Color(color2);
  33775. var center = divisions / 2;
  33776. var step = size / divisions;
  33777. var halfSize = size / 2;
  33778. var vertices = [],
  33779. colors = [];
  33780. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  33781. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  33782. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  33783. var color = i === center ? color1 : color2;
  33784. color.toArray(colors, j);
  33785. j += 3;
  33786. color.toArray(colors, j);
  33787. j += 3;
  33788. color.toArray(colors, j);
  33789. j += 3;
  33790. color.toArray(colors, j);
  33791. j += 3;
  33792. }
  33793. var geometry = new BufferGeometry();
  33794. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33795. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33796. var material = new LineBasicMaterial({
  33797. vertexColors: true,
  33798. toneMapped: false
  33799. });
  33800. _this = _LineSegments.call(this, geometry, material) || this;
  33801. _this.type = 'GridHelper';
  33802. return _this;
  33803. }
  33804. return GridHelper;
  33805. }(LineSegments);
  33806. var PolarGridHelper = /*#__PURE__*/function (_LineSegments) {
  33807. _inheritsLoose(PolarGridHelper, _LineSegments);
  33808. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  33809. var _this;
  33810. if (radius === void 0) {
  33811. radius = 10;
  33812. }
  33813. if (radials === void 0) {
  33814. radials = 16;
  33815. }
  33816. if (circles === void 0) {
  33817. circles = 8;
  33818. }
  33819. if (divisions === void 0) {
  33820. divisions = 64;
  33821. }
  33822. if (color1 === void 0) {
  33823. color1 = 0x444444;
  33824. }
  33825. if (color2 === void 0) {
  33826. color2 = 0x888888;
  33827. }
  33828. color1 = new Color(color1);
  33829. color2 = new Color(color2);
  33830. var vertices = [];
  33831. var colors = []; // create the radials
  33832. for (var i = 0; i <= radials; i++) {
  33833. var v = i / radials * (Math.PI * 2);
  33834. var x = Math.sin(v) * radius;
  33835. var z = Math.cos(v) * radius;
  33836. vertices.push(0, 0, 0);
  33837. vertices.push(x, 0, z);
  33838. var color = i & 1 ? color1 : color2;
  33839. colors.push(color.r, color.g, color.b);
  33840. colors.push(color.r, color.g, color.b);
  33841. } // create the circles
  33842. for (var _i = 0; _i <= circles; _i++) {
  33843. var _color = _i & 1 ? color1 : color2;
  33844. var r = radius - radius / circles * _i;
  33845. for (var j = 0; j < divisions; j++) {
  33846. // first vertex
  33847. var _v = j / divisions * (Math.PI * 2);
  33848. var _x = Math.sin(_v) * r;
  33849. var _z = Math.cos(_v) * r;
  33850. vertices.push(_x, 0, _z);
  33851. colors.push(_color.r, _color.g, _color.b); // second vertex
  33852. _v = (j + 1) / divisions * (Math.PI * 2);
  33853. _x = Math.sin(_v) * r;
  33854. _z = Math.cos(_v) * r;
  33855. vertices.push(_x, 0, _z);
  33856. colors.push(_color.r, _color.g, _color.b);
  33857. }
  33858. }
  33859. var geometry = new BufferGeometry();
  33860. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33861. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33862. var material = new LineBasicMaterial({
  33863. vertexColors: true,
  33864. toneMapped: false
  33865. });
  33866. _this = _LineSegments.call(this, geometry, material) || this;
  33867. _this.type = 'PolarGridHelper';
  33868. return _this;
  33869. }
  33870. return PolarGridHelper;
  33871. }(LineSegments);
  33872. var _v1$6 = /*@__PURE__*/new Vector3();
  33873. var _v2$3 = /*@__PURE__*/new Vector3();
  33874. var _v3$1 = /*@__PURE__*/new Vector3();
  33875. var DirectionalLightHelper = /*#__PURE__*/function (_Object3D) {
  33876. _inheritsLoose(DirectionalLightHelper, _Object3D);
  33877. function DirectionalLightHelper(light, size, color) {
  33878. var _this;
  33879. _this = _Object3D.call(this) || this;
  33880. _this.light = light;
  33881. _this.light.updateMatrixWorld();
  33882. _this.matrix = light.matrixWorld;
  33883. _this.matrixAutoUpdate = false;
  33884. _this.color = color;
  33885. if (size === undefined) size = 1;
  33886. var geometry = new BufferGeometry();
  33887. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  33888. var material = new LineBasicMaterial({
  33889. fog: false,
  33890. toneMapped: false
  33891. });
  33892. _this.lightPlane = new Line(geometry, material);
  33893. _this.add(_this.lightPlane);
  33894. geometry = new BufferGeometry();
  33895. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  33896. _this.targetLine = new Line(geometry, material);
  33897. _this.add(_this.targetLine);
  33898. _this.update();
  33899. return _this;
  33900. }
  33901. var _proto = DirectionalLightHelper.prototype;
  33902. _proto.dispose = function dispose() {
  33903. this.lightPlane.geometry.dispose();
  33904. this.lightPlane.material.dispose();
  33905. this.targetLine.geometry.dispose();
  33906. this.targetLine.material.dispose();
  33907. };
  33908. _proto.update = function update() {
  33909. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  33910. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  33911. _v3$1.subVectors(_v2$3, _v1$6);
  33912. this.lightPlane.lookAt(_v2$3);
  33913. if (this.color !== undefined) {
  33914. this.lightPlane.material.color.set(this.color);
  33915. this.targetLine.material.color.set(this.color);
  33916. } else {
  33917. this.lightPlane.material.color.copy(this.light.color);
  33918. this.targetLine.material.color.copy(this.light.color);
  33919. }
  33920. this.targetLine.lookAt(_v2$3);
  33921. this.targetLine.scale.z = _v3$1.length();
  33922. };
  33923. return DirectionalLightHelper;
  33924. }(Object3D);
  33925. var _vector$c = /*@__PURE__*/new Vector3();
  33926. var _camera = /*@__PURE__*/new Camera();
  33927. /**
  33928. * - shows frustum, line of sight and up of the camera
  33929. * - suitable for fast updates
  33930. * - based on frustum visualization in lightgl.js shadowmap example
  33931. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33932. */
  33933. var CameraHelper = /*#__PURE__*/function (_LineSegments) {
  33934. _inheritsLoose(CameraHelper, _LineSegments);
  33935. function CameraHelper(camera) {
  33936. var _this;
  33937. var geometry = new BufferGeometry();
  33938. var material = new LineBasicMaterial({
  33939. color: 0xffffff,
  33940. vertexColors: true,
  33941. toneMapped: false
  33942. });
  33943. var vertices = [];
  33944. var colors = [];
  33945. var pointMap = {}; // colors
  33946. var colorFrustum = new Color(0xffaa00);
  33947. var colorCone = new Color(0xff0000);
  33948. var colorUp = new Color(0x00aaff);
  33949. var colorTarget = new Color(0xffffff);
  33950. var colorCross = new Color(0x333333); // near
  33951. addLine('n1', 'n2', colorFrustum);
  33952. addLine('n2', 'n4', colorFrustum);
  33953. addLine('n4', 'n3', colorFrustum);
  33954. addLine('n3', 'n1', colorFrustum); // far
  33955. addLine('f1', 'f2', colorFrustum);
  33956. addLine('f2', 'f4', colorFrustum);
  33957. addLine('f4', 'f3', colorFrustum);
  33958. addLine('f3', 'f1', colorFrustum); // sides
  33959. addLine('n1', 'f1', colorFrustum);
  33960. addLine('n2', 'f2', colorFrustum);
  33961. addLine('n3', 'f3', colorFrustum);
  33962. addLine('n4', 'f4', colorFrustum); // cone
  33963. addLine('p', 'n1', colorCone);
  33964. addLine('p', 'n2', colorCone);
  33965. addLine('p', 'n3', colorCone);
  33966. addLine('p', 'n4', colorCone); // up
  33967. addLine('u1', 'u2', colorUp);
  33968. addLine('u2', 'u3', colorUp);
  33969. addLine('u3', 'u1', colorUp); // target
  33970. addLine('c', 't', colorTarget);
  33971. addLine('p', 'c', colorCross); // cross
  33972. addLine('cn1', 'cn2', colorCross);
  33973. addLine('cn3', 'cn4', colorCross);
  33974. addLine('cf1', 'cf2', colorCross);
  33975. addLine('cf3', 'cf4', colorCross);
  33976. function addLine(a, b, color) {
  33977. addPoint(a, color);
  33978. addPoint(b, color);
  33979. }
  33980. function addPoint(id, color) {
  33981. vertices.push(0, 0, 0);
  33982. colors.push(color.r, color.g, color.b);
  33983. if (pointMap[id] === undefined) {
  33984. pointMap[id] = [];
  33985. }
  33986. pointMap[id].push(vertices.length / 3 - 1);
  33987. }
  33988. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33989. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33990. _this = _LineSegments.call(this, geometry, material) || this;
  33991. _this.type = 'CameraHelper';
  33992. _this.camera = camera;
  33993. if (_this.camera.updateProjectionMatrix) _this.camera.updateProjectionMatrix();
  33994. _this.matrix = camera.matrixWorld;
  33995. _this.matrixAutoUpdate = false;
  33996. _this.pointMap = pointMap;
  33997. _this.update();
  33998. return _this;
  33999. }
  34000. var _proto = CameraHelper.prototype;
  34001. _proto.update = function update() {
  34002. var geometry = this.geometry;
  34003. var pointMap = this.pointMap;
  34004. var w = 1,
  34005. h = 1; // we need just camera projection matrix inverse
  34006. // world matrix must be identity
  34007. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  34008. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  34009. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  34010. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  34011. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  34012. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  34013. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  34014. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  34015. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  34016. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  34017. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  34018. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  34019. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  34020. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  34021. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  34022. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  34023. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  34024. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  34025. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  34026. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  34027. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  34028. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  34029. geometry.getAttribute('position').needsUpdate = true;
  34030. };
  34031. return CameraHelper;
  34032. }(LineSegments);
  34033. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  34034. _vector$c.set(x, y, z).unproject(camera);
  34035. var points = pointMap[point];
  34036. if (points !== undefined) {
  34037. var position = geometry.getAttribute('position');
  34038. for (var i = 0, l = points.length; i < l; i++) {
  34039. position.setXYZ(points[i], _vector$c.x, _vector$c.y, _vector$c.z);
  34040. }
  34041. }
  34042. }
  34043. var _box$3 = /*@__PURE__*/new Box3();
  34044. var BoxHelper = /*#__PURE__*/function (_LineSegments) {
  34045. _inheritsLoose(BoxHelper, _LineSegments);
  34046. function BoxHelper(object, color) {
  34047. var _this;
  34048. if (color === void 0) {
  34049. color = 0xffff00;
  34050. }
  34051. 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]);
  34052. var positions = new Float32Array(8 * 3);
  34053. var geometry = new BufferGeometry();
  34054. geometry.setIndex(new BufferAttribute(indices, 1));
  34055. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  34056. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34057. color: color,
  34058. toneMapped: false
  34059. })) || this;
  34060. _this.object = object;
  34061. _this.type = 'BoxHelper';
  34062. _this.matrixAutoUpdate = false;
  34063. _this.update();
  34064. return _this;
  34065. }
  34066. var _proto = BoxHelper.prototype;
  34067. _proto.update = function update(object) {
  34068. if (object !== undefined) {
  34069. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  34070. }
  34071. if (this.object !== undefined) {
  34072. _box$3.setFromObject(this.object);
  34073. }
  34074. if (_box$3.isEmpty()) return;
  34075. var min = _box$3.min;
  34076. var max = _box$3.max;
  34077. /*
  34078. 5____4
  34079. 1/___0/|
  34080. | 6__|_7
  34081. 2/___3/
  34082. 0: max.x, max.y, max.z
  34083. 1: min.x, max.y, max.z
  34084. 2: min.x, min.y, max.z
  34085. 3: max.x, min.y, max.z
  34086. 4: max.x, max.y, min.z
  34087. 5: min.x, max.y, min.z
  34088. 6: min.x, min.y, min.z
  34089. 7: max.x, min.y, min.z
  34090. */
  34091. var position = this.geometry.attributes.position;
  34092. var array = position.array;
  34093. array[0] = max.x;
  34094. array[1] = max.y;
  34095. array[2] = max.z;
  34096. array[3] = min.x;
  34097. array[4] = max.y;
  34098. array[5] = max.z;
  34099. array[6] = min.x;
  34100. array[7] = min.y;
  34101. array[8] = max.z;
  34102. array[9] = max.x;
  34103. array[10] = min.y;
  34104. array[11] = max.z;
  34105. array[12] = max.x;
  34106. array[13] = max.y;
  34107. array[14] = min.z;
  34108. array[15] = min.x;
  34109. array[16] = max.y;
  34110. array[17] = min.z;
  34111. array[18] = min.x;
  34112. array[19] = min.y;
  34113. array[20] = min.z;
  34114. array[21] = max.x;
  34115. array[22] = min.y;
  34116. array[23] = min.z;
  34117. position.needsUpdate = true;
  34118. this.geometry.computeBoundingSphere();
  34119. };
  34120. _proto.setFromObject = function setFromObject(object) {
  34121. this.object = object;
  34122. this.update();
  34123. return this;
  34124. };
  34125. _proto.copy = function copy(source) {
  34126. LineSegments.prototype.copy.call(this, source);
  34127. this.object = source.object;
  34128. return this;
  34129. };
  34130. return BoxHelper;
  34131. }(LineSegments);
  34132. var Box3Helper = /*#__PURE__*/function (_LineSegments) {
  34133. _inheritsLoose(Box3Helper, _LineSegments);
  34134. function Box3Helper(box, color) {
  34135. var _this;
  34136. if (color === void 0) {
  34137. color = 0xffff00;
  34138. }
  34139. 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]);
  34140. 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];
  34141. var geometry = new BufferGeometry();
  34142. geometry.setIndex(new BufferAttribute(indices, 1));
  34143. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34144. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34145. color: color,
  34146. toneMapped: false
  34147. })) || this;
  34148. _this.box = box;
  34149. _this.type = 'Box3Helper';
  34150. _this.geometry.computeBoundingSphere();
  34151. return _this;
  34152. }
  34153. var _proto = Box3Helper.prototype;
  34154. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34155. var box = this.box;
  34156. if (box.isEmpty()) return;
  34157. box.getCenter(this.position);
  34158. box.getSize(this.scale);
  34159. this.scale.multiplyScalar(0.5);
  34160. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  34161. };
  34162. return Box3Helper;
  34163. }(LineSegments);
  34164. var PlaneHelper = /*#__PURE__*/function (_Line) {
  34165. _inheritsLoose(PlaneHelper, _Line);
  34166. function PlaneHelper(plane, size, hex) {
  34167. var _this;
  34168. if (size === void 0) {
  34169. size = 1;
  34170. }
  34171. if (hex === void 0) {
  34172. hex = 0xffff00;
  34173. }
  34174. var color = hex;
  34175. 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];
  34176. var geometry = new BufferGeometry();
  34177. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34178. geometry.computeBoundingSphere();
  34179. _this = _Line.call(this, geometry, new LineBasicMaterial({
  34180. color: color,
  34181. toneMapped: false
  34182. })) || this;
  34183. _this.type = 'PlaneHelper';
  34184. _this.plane = plane;
  34185. _this.size = size;
  34186. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  34187. var geometry2 = new BufferGeometry();
  34188. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  34189. geometry2.computeBoundingSphere();
  34190. _this.add(new Mesh(geometry2, new MeshBasicMaterial({
  34191. color: color,
  34192. opacity: 0.2,
  34193. transparent: true,
  34194. depthWrite: false,
  34195. toneMapped: false
  34196. })));
  34197. return _this;
  34198. }
  34199. var _proto = PlaneHelper.prototype;
  34200. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34201. var scale = -this.plane.constant;
  34202. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  34203. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  34204. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  34205. this.lookAt(this.plane.normal);
  34206. _Line.prototype.updateMatrixWorld.call(this, force);
  34207. };
  34208. return PlaneHelper;
  34209. }(Line);
  34210. var _axis = /*@__PURE__*/new Vector3();
  34211. var _lineGeometry, _coneGeometry;
  34212. var ArrowHelper = /*#__PURE__*/function (_Object3D) {
  34213. _inheritsLoose(ArrowHelper, _Object3D);
  34214. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  34215. var _this;
  34216. _this = _Object3D.call(this) || this; // dir is assumed to be normalized
  34217. _this.type = 'ArrowHelper';
  34218. if (dir === undefined) dir = new Vector3(0, 0, 1);
  34219. if (origin === undefined) origin = new Vector3(0, 0, 0);
  34220. if (length === undefined) length = 1;
  34221. if (color === undefined) color = 0xffff00;
  34222. if (headLength === undefined) headLength = 0.2 * length;
  34223. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34224. if (_lineGeometry === undefined) {
  34225. _lineGeometry = new BufferGeometry();
  34226. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  34227. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  34228. _coneGeometry.translate(0, -0.5, 0);
  34229. }
  34230. _this.position.copy(origin);
  34231. _this.line = new Line(_lineGeometry, new LineBasicMaterial({
  34232. color: color,
  34233. toneMapped: false
  34234. }));
  34235. _this.line.matrixAutoUpdate = false;
  34236. _this.add(_this.line);
  34237. _this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  34238. color: color,
  34239. toneMapped: false
  34240. }));
  34241. _this.cone.matrixAutoUpdate = false;
  34242. _this.add(_this.cone);
  34243. _this.setDirection(dir);
  34244. _this.setLength(length, headLength, headWidth);
  34245. return _this;
  34246. }
  34247. var _proto = ArrowHelper.prototype;
  34248. _proto.setDirection = function setDirection(dir) {
  34249. // dir is assumed to be normalized
  34250. if (dir.y > 0.99999) {
  34251. this.quaternion.set(0, 0, 0, 1);
  34252. } else if (dir.y < -0.99999) {
  34253. this.quaternion.set(1, 0, 0, 0);
  34254. } else {
  34255. _axis.set(dir.z, 0, -dir.x).normalize();
  34256. var radians = Math.acos(dir.y);
  34257. this.quaternion.setFromAxisAngle(_axis, radians);
  34258. }
  34259. };
  34260. _proto.setLength = function setLength(length, headLength, headWidth) {
  34261. if (headLength === undefined) headLength = 0.2 * length;
  34262. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34263. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  34264. this.line.updateMatrix();
  34265. this.cone.scale.set(headWidth, headLength, headWidth);
  34266. this.cone.position.y = length;
  34267. this.cone.updateMatrix();
  34268. };
  34269. _proto.setColor = function setColor(color) {
  34270. this.line.material.color.set(color);
  34271. this.cone.material.color.set(color);
  34272. };
  34273. _proto.copy = function copy(source) {
  34274. _Object3D.prototype.copy.call(this, source, false);
  34275. this.line.copy(source.line);
  34276. this.cone.copy(source.cone);
  34277. return this;
  34278. };
  34279. return ArrowHelper;
  34280. }(Object3D);
  34281. var AxesHelper = /*#__PURE__*/function (_LineSegments) {
  34282. _inheritsLoose(AxesHelper, _LineSegments);
  34283. function AxesHelper(size) {
  34284. var _this;
  34285. if (size === void 0) {
  34286. size = 1;
  34287. }
  34288. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  34289. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  34290. var geometry = new BufferGeometry();
  34291. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34292. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34293. var material = new LineBasicMaterial({
  34294. vertexColors: true,
  34295. toneMapped: false
  34296. });
  34297. _this = _LineSegments.call(this, geometry, material) || this;
  34298. _this.type = 'AxesHelper';
  34299. return _this;
  34300. }
  34301. return AxesHelper;
  34302. }(LineSegments);
  34303. var _floatView = new Float32Array(1);
  34304. var _int32View = new Int32Array(_floatView.buffer);
  34305. var DataUtils = {
  34306. // Converts float32 to float16 (stored as uint16 value).
  34307. toHalfFloat: function toHalfFloat(val) {
  34308. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  34309. /* This method is faster than the OpenEXR implementation (very often
  34310. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  34311. * by James Tursa?s half-precision code. */
  34312. _floatView[0] = val;
  34313. var x = _int32View[0];
  34314. var bits = x >> 16 & 0x8000;
  34315. /* Get the sign */
  34316. var m = x >> 12 & 0x07ff;
  34317. /* Keep one extra bit for rounding */
  34318. var e = x >> 23 & 0xff;
  34319. /* Using int is faster here */
  34320. /* If zero, or denormal, or exponent underflows too much for a denormal
  34321. * half, return signed zero. */
  34322. if (e < 103) return bits;
  34323. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34324. if (e > 142) {
  34325. bits |= 0x7c00;
  34326. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34327. * not Inf, so make sure we set one mantissa bit too. */
  34328. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  34329. return bits;
  34330. }
  34331. /* If exponent underflows but not too much, return a denormal */
  34332. if (e < 113) {
  34333. m |= 0x0800;
  34334. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34335. * to 1, which is OK. */
  34336. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  34337. return bits;
  34338. }
  34339. bits |= e - 112 << 10 | m >> 1;
  34340. /* Extra rounding. An overflow will set mantissa to 0 and increment
  34341. * the exponent, which is OK. */
  34342. bits += m & 1;
  34343. return bits;
  34344. }
  34345. };
  34346. var _ENCODINGS;
  34347. var LOD_MIN = 4;
  34348. var LOD_MAX = 8;
  34349. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  34350. // chosen to approximate a Trowbridge-Reitz distribution function times the
  34351. // geometric shadowing function. These sigma values squared must match the
  34352. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  34353. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  34354. 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
  34355. // samples and exit early, but not recompile the shader.
  34356. var MAX_SAMPLES = 20;
  34357. 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);
  34358. var backgroundMaterial = new MeshBasicMaterial({
  34359. side: BackSide,
  34360. depthWrite: false,
  34361. depthTest: false
  34362. });
  34363. var backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  34364. var _flatCamera = /*@__PURE__*/new OrthographicCamera();
  34365. var _createPlanes2 = /*@__PURE__*/_createPlanes(),
  34366. _lodPlanes = _createPlanes2._lodPlanes,
  34367. _sizeLods = _createPlanes2._sizeLods,
  34368. _sigmas = _createPlanes2._sigmas;
  34369. var _clearColor = /*@__PURE__*/new Color();
  34370. var _oldTarget = null; // Golden Ratio
  34371. var PHI = (1 + Math.sqrt(5)) / 2;
  34372. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  34373. // same axis), used as axis directions evenly spread on a sphere.
  34374. 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)];
  34375. /**
  34376. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  34377. * (PMREM) from a cubeMap environment texture. This allows different levels of
  34378. * blur to be quickly accessed based on material roughness. It is packed into a
  34379. * special CubeUV format that allows us to perform custom interpolation so that
  34380. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  34381. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  34382. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  34383. * higher roughness levels. In this way we maintain resolution to smoothly
  34384. * interpolate diffuse lighting while limiting sampling computation.
  34385. */
  34386. function convertLinearToRGBE(color) {
  34387. var maxComponent = Math.max(color.r, color.g, color.b);
  34388. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  34389. color.multiplyScalar(Math.pow(2.0, -fExp));
  34390. var alpha = (fExp + 128.0) / 255.0;
  34391. return alpha;
  34392. }
  34393. var PMREMGenerator = /*#__PURE__*/function () {
  34394. function PMREMGenerator(renderer) {
  34395. this._renderer = renderer;
  34396. this._pingPongRenderTarget = null;
  34397. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  34398. this._equirectShader = null;
  34399. this._cubemapShader = null;
  34400. this._compileMaterial(this._blurMaterial);
  34401. }
  34402. /**
  34403. * Generates a PMREM from a supplied Scene, which can be faster than using an
  34404. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  34405. * in radians to be applied to the scene before PMREM generation. Optional near
  34406. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  34407. * is placed at the origin).
  34408. */
  34409. var _proto = PMREMGenerator.prototype;
  34410. _proto.fromScene = function fromScene(scene, sigma, near, far) {
  34411. if (sigma === void 0) {
  34412. sigma = 0;
  34413. }
  34414. if (near === void 0) {
  34415. near = 0.1;
  34416. }
  34417. if (far === void 0) {
  34418. far = 100;
  34419. }
  34420. _oldTarget = this._renderer.getRenderTarget();
  34421. var cubeUVRenderTarget = this._allocateTargets();
  34422. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  34423. if (sigma > 0) {
  34424. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  34425. }
  34426. this._applyPMREM(cubeUVRenderTarget);
  34427. this._cleanup(cubeUVRenderTarget);
  34428. return cubeUVRenderTarget;
  34429. }
  34430. /**
  34431. * Generates a PMREM from an equirectangular texture, which can be either LDR
  34432. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  34433. * as this matches best with the 256 x 256 cubemap output.
  34434. */
  34435. ;
  34436. _proto.fromEquirectangular = function fromEquirectangular(equirectangular) {
  34437. return this._fromTexture(equirectangular);
  34438. }
  34439. /**
  34440. * Generates a PMREM from an cubemap texture, which can be either LDR
  34441. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  34442. * as this matches best with the 256 x 256 cubemap output.
  34443. */
  34444. ;
  34445. _proto.fromCubemap = function fromCubemap(cubemap) {
  34446. return this._fromTexture(cubemap);
  34447. }
  34448. /**
  34449. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  34450. * your texture's network fetch for increased concurrency.
  34451. */
  34452. ;
  34453. _proto.compileCubemapShader = function compileCubemapShader() {
  34454. if (this._cubemapShader === null) {
  34455. this._cubemapShader = _getCubemapShader();
  34456. this._compileMaterial(this._cubemapShader);
  34457. }
  34458. }
  34459. /**
  34460. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  34461. * your texture's network fetch for increased concurrency.
  34462. */
  34463. ;
  34464. _proto.compileEquirectangularShader = function compileEquirectangularShader() {
  34465. if (this._equirectShader === null) {
  34466. this._equirectShader = _getEquirectShader();
  34467. this._compileMaterial(this._equirectShader);
  34468. }
  34469. }
  34470. /**
  34471. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  34472. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  34473. * one of them will cause any others to also become unusable.
  34474. */
  34475. ;
  34476. _proto.dispose = function dispose() {
  34477. this._blurMaterial.dispose();
  34478. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  34479. if (this._equirectShader !== null) this._equirectShader.dispose();
  34480. for (var i = 0; i < _lodPlanes.length; i++) {
  34481. _lodPlanes[i].dispose();
  34482. }
  34483. } // private interface
  34484. ;
  34485. _proto._cleanup = function _cleanup(outputTarget) {
  34486. this._pingPongRenderTarget.dispose();
  34487. this._renderer.setRenderTarget(_oldTarget);
  34488. outputTarget.scissorTest = false;
  34489. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  34490. };
  34491. _proto._fromTexture = function _fromTexture(texture) {
  34492. _oldTarget = this._renderer.getRenderTarget();
  34493. var cubeUVRenderTarget = this._allocateTargets(texture);
  34494. this._textureToCubeUV(texture, cubeUVRenderTarget);
  34495. this._applyPMREM(cubeUVRenderTarget);
  34496. this._cleanup(cubeUVRenderTarget);
  34497. return cubeUVRenderTarget;
  34498. };
  34499. _proto._allocateTargets = function _allocateTargets(texture) {
  34500. // warning: null texture is valid
  34501. var params = {
  34502. magFilter: NearestFilter,
  34503. minFilter: NearestFilter,
  34504. generateMipmaps: false,
  34505. type: UnsignedByteType,
  34506. format: RGBEFormat,
  34507. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  34508. depthBuffer: false
  34509. };
  34510. var cubeUVRenderTarget = _createRenderTarget(params);
  34511. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  34512. this._pingPongRenderTarget = _createRenderTarget(params);
  34513. return cubeUVRenderTarget;
  34514. };
  34515. _proto._compileMaterial = function _compileMaterial(material) {
  34516. var tmpMesh = new Mesh(_lodPlanes[0], material);
  34517. this._renderer.compile(tmpMesh, _flatCamera);
  34518. };
  34519. _proto._sceneToCubeUV = function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  34520. var fov = 90;
  34521. var aspect = 1;
  34522. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  34523. var upSign = [1, -1, 1, 1, 1, 1];
  34524. var forwardSign = [1, 1, 1, -1, -1, -1];
  34525. var renderer = this._renderer;
  34526. var originalAutoClear = renderer.autoClear;
  34527. var outputEncoding = renderer.outputEncoding;
  34528. var toneMapping = renderer.toneMapping;
  34529. renderer.getClearColor(_clearColor);
  34530. renderer.toneMapping = NoToneMapping;
  34531. renderer.outputEncoding = LinearEncoding;
  34532. renderer.autoClear = false;
  34533. var useSolidColor = false;
  34534. var background = scene.background;
  34535. if (background) {
  34536. if (background.isColor) {
  34537. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  34538. scene.background = null;
  34539. var alpha = convertLinearToRGBE(backgroundMaterial.color);
  34540. backgroundMaterial.opacity = alpha;
  34541. useSolidColor = true;
  34542. }
  34543. } else {
  34544. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  34545. var _alpha = convertLinearToRGBE(backgroundMaterial.color);
  34546. backgroundMaterial.opacity = _alpha;
  34547. useSolidColor = true;
  34548. }
  34549. for (var i = 0; i < 6; i++) {
  34550. var col = i % 3;
  34551. if (col == 0) {
  34552. cubeCamera.up.set(0, upSign[i], 0);
  34553. cubeCamera.lookAt(forwardSign[i], 0, 0);
  34554. } else if (col == 1) {
  34555. cubeCamera.up.set(0, 0, upSign[i]);
  34556. cubeCamera.lookAt(0, forwardSign[i], 0);
  34557. } else {
  34558. cubeCamera.up.set(0, upSign[i], 0);
  34559. cubeCamera.lookAt(0, 0, forwardSign[i]);
  34560. }
  34561. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  34562. renderer.setRenderTarget(cubeUVRenderTarget);
  34563. if (useSolidColor) {
  34564. renderer.render(backgroundBox, cubeCamera);
  34565. }
  34566. renderer.render(scene, cubeCamera);
  34567. }
  34568. renderer.toneMapping = toneMapping;
  34569. renderer.outputEncoding = outputEncoding;
  34570. renderer.autoClear = originalAutoClear;
  34571. };
  34572. _proto._textureToCubeUV = function _textureToCubeUV(texture, cubeUVRenderTarget) {
  34573. var renderer = this._renderer;
  34574. if (texture.isCubeTexture) {
  34575. if (this._cubemapShader == null) {
  34576. this._cubemapShader = _getCubemapShader();
  34577. }
  34578. } else {
  34579. if (this._equirectShader == null) {
  34580. this._equirectShader = _getEquirectShader();
  34581. }
  34582. }
  34583. var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  34584. var mesh = new Mesh(_lodPlanes[0], material);
  34585. var uniforms = material.uniforms;
  34586. uniforms['envMap'].value = texture;
  34587. if (!texture.isCubeTexture) {
  34588. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  34589. }
  34590. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  34591. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  34592. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  34593. renderer.setRenderTarget(cubeUVRenderTarget);
  34594. renderer.render(mesh, _flatCamera);
  34595. };
  34596. _proto._applyPMREM = function _applyPMREM(cubeUVRenderTarget) {
  34597. var renderer = this._renderer;
  34598. var autoClear = renderer.autoClear;
  34599. renderer.autoClear = false;
  34600. for (var i = 1; i < TOTAL_LODS; i++) {
  34601. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  34602. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  34603. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  34604. }
  34605. renderer.autoClear = autoClear;
  34606. }
  34607. /**
  34608. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  34609. * vertically and horizontally, but this breaks down on a cube. Here we apply
  34610. * the blur latitudinally (around the poles), and then longitudinally (towards
  34611. * the poles) to approximate the orthogonally-separable blur. It is least
  34612. * accurate at the poles, but still does a decent job.
  34613. */
  34614. ;
  34615. _proto._blur = function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  34616. var pingPongRenderTarget = this._pingPongRenderTarget;
  34617. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  34618. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  34619. };
  34620. _proto._halfBlur = function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  34621. var renderer = this._renderer;
  34622. var blurMaterial = this._blurMaterial;
  34623. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  34624. console.error('blur direction must be either latitudinal or longitudinal!');
  34625. } // Number of standard deviations at which to cut off the discrete approximation.
  34626. var STANDARD_DEVIATIONS = 3;
  34627. var blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  34628. var blurUniforms = blurMaterial.uniforms;
  34629. var pixels = _sizeLods[lodIn] - 1;
  34630. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  34631. var sigmaPixels = sigmaRadians / radiansPerPixel;
  34632. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  34633. if (samples > MAX_SAMPLES) {
  34634. console.warn("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES);
  34635. }
  34636. var weights = [];
  34637. var sum = 0;
  34638. for (var i = 0; i < MAX_SAMPLES; ++i) {
  34639. var _x = i / sigmaPixels;
  34640. var weight = Math.exp(-_x * _x / 2);
  34641. weights.push(weight);
  34642. if (i == 0) {
  34643. sum += weight;
  34644. } else if (i < samples) {
  34645. sum += 2 * weight;
  34646. }
  34647. }
  34648. for (var _i = 0; _i < weights.length; _i++) {
  34649. weights[_i] = weights[_i] / sum;
  34650. }
  34651. blurUniforms['envMap'].value = targetIn.texture;
  34652. blurUniforms['samples'].value = samples;
  34653. blurUniforms['weights'].value = weights;
  34654. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  34655. if (poleAxis) {
  34656. blurUniforms['poleAxis'].value = poleAxis;
  34657. }
  34658. blurUniforms['dTheta'].value = radiansPerPixel;
  34659. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  34660. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  34661. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  34662. var outputSize = _sizeLods[lodOut];
  34663. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  34664. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  34665. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  34666. renderer.setRenderTarget(targetOut);
  34667. renderer.render(blurMesh, _flatCamera);
  34668. };
  34669. return PMREMGenerator;
  34670. }();
  34671. function _isLDR(texture) {
  34672. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  34673. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  34674. }
  34675. function _createPlanes() {
  34676. var _lodPlanes = [];
  34677. var _sizeLods = [];
  34678. var _sigmas = [];
  34679. var lod = LOD_MAX;
  34680. for (var i = 0; i < TOTAL_LODS; i++) {
  34681. var sizeLod = Math.pow(2, lod);
  34682. _sizeLods.push(sizeLod);
  34683. var sigma = 1.0 / sizeLod;
  34684. if (i > LOD_MAX - LOD_MIN) {
  34685. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  34686. } else if (i == 0) {
  34687. sigma = 0;
  34688. }
  34689. _sigmas.push(sigma);
  34690. var texelSize = 1.0 / (sizeLod - 1);
  34691. var min = -texelSize / 2;
  34692. var max = 1 + texelSize / 2;
  34693. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  34694. var cubeFaces = 6;
  34695. var vertices = 6;
  34696. var positionSize = 3;
  34697. var uvSize = 2;
  34698. var faceIndexSize = 1;
  34699. var position = new Float32Array(positionSize * vertices * cubeFaces);
  34700. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  34701. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  34702. for (var face = 0; face < cubeFaces; face++) {
  34703. var x = face % 3 * 2 / 3 - 1;
  34704. var y = face > 2 ? 0 : -1;
  34705. 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];
  34706. position.set(coordinates, positionSize * vertices * face);
  34707. uv.set(uv1, uvSize * vertices * face);
  34708. var fill = [face, face, face, face, face, face];
  34709. faceIndex.set(fill, faceIndexSize * vertices * face);
  34710. }
  34711. var planes = new BufferGeometry();
  34712. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  34713. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  34714. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  34715. _lodPlanes.push(planes);
  34716. if (lod > LOD_MIN) {
  34717. lod--;
  34718. }
  34719. }
  34720. return {
  34721. _lodPlanes: _lodPlanes,
  34722. _sizeLods: _sizeLods,
  34723. _sigmas: _sigmas
  34724. };
  34725. }
  34726. function _createRenderTarget(params) {
  34727. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  34728. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  34729. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  34730. cubeUVRenderTarget.scissorTest = true;
  34731. return cubeUVRenderTarget;
  34732. }
  34733. function _setViewport(target, x, y, width, height) {
  34734. target.viewport.set(x, y, width, height);
  34735. target.scissor.set(x, y, width, height);
  34736. }
  34737. function _getBlurShader(maxSamples) {
  34738. var weights = new Float32Array(maxSamples);
  34739. var poleAxis = new Vector3(0, 1, 0);
  34740. var shaderMaterial = new RawShaderMaterial({
  34741. name: 'SphericalGaussianBlur',
  34742. defines: {
  34743. 'n': maxSamples
  34744. },
  34745. uniforms: {
  34746. 'envMap': {
  34747. value: null
  34748. },
  34749. 'samples': {
  34750. value: 1
  34751. },
  34752. 'weights': {
  34753. value: weights
  34754. },
  34755. 'latitudinal': {
  34756. value: false
  34757. },
  34758. 'dTheta': {
  34759. value: 0
  34760. },
  34761. 'mipInt': {
  34762. value: 0
  34763. },
  34764. 'poleAxis': {
  34765. value: poleAxis
  34766. },
  34767. 'inputEncoding': {
  34768. value: ENCODINGS[LinearEncoding]
  34769. },
  34770. 'outputEncoding': {
  34771. value: ENCODINGS[LinearEncoding]
  34772. }
  34773. },
  34774. vertexShader: _getCommonVertexShader(),
  34775. fragmentShader:
  34776. /* glsl */
  34777. "\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",
  34778. blending: NoBlending,
  34779. depthTest: false,
  34780. depthWrite: false
  34781. });
  34782. return shaderMaterial;
  34783. }
  34784. function _getEquirectShader() {
  34785. var texelSize = new Vector2(1, 1);
  34786. var shaderMaterial = new RawShaderMaterial({
  34787. name: 'EquirectangularToCubeUV',
  34788. uniforms: {
  34789. 'envMap': {
  34790. value: null
  34791. },
  34792. 'texelSize': {
  34793. value: texelSize
  34794. },
  34795. 'inputEncoding': {
  34796. value: ENCODINGS[LinearEncoding]
  34797. },
  34798. 'outputEncoding': {
  34799. value: ENCODINGS[LinearEncoding]
  34800. }
  34801. },
  34802. vertexShader: _getCommonVertexShader(),
  34803. fragmentShader:
  34804. /* glsl */
  34805. "\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",
  34806. blending: NoBlending,
  34807. depthTest: false,
  34808. depthWrite: false
  34809. });
  34810. return shaderMaterial;
  34811. }
  34812. function _getCubemapShader() {
  34813. var shaderMaterial = new RawShaderMaterial({
  34814. name: 'CubemapToCubeUV',
  34815. uniforms: {
  34816. 'envMap': {
  34817. value: null
  34818. },
  34819. 'inputEncoding': {
  34820. value: ENCODINGS[LinearEncoding]
  34821. },
  34822. 'outputEncoding': {
  34823. value: ENCODINGS[LinearEncoding]
  34824. }
  34825. },
  34826. vertexShader: _getCommonVertexShader(),
  34827. fragmentShader:
  34828. /* glsl */
  34829. "\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",
  34830. blending: NoBlending,
  34831. depthTest: false,
  34832. depthWrite: false
  34833. });
  34834. return shaderMaterial;
  34835. }
  34836. function _getCommonVertexShader() {
  34837. return (
  34838. /* glsl */
  34839. "\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"
  34840. );
  34841. }
  34842. function _getEncodings() {
  34843. return (
  34844. /* glsl */
  34845. "\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"
  34846. );
  34847. }
  34848. function Face4(a, b, c, d, normal, color, materialIndex) {
  34849. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  34850. return new Face3(a, b, c, normal, color, materialIndex);
  34851. }
  34852. var LineStrip = 0;
  34853. var LinePieces = 1;
  34854. var NoColors = 0;
  34855. var FaceColors = 1;
  34856. var VertexColors = 2;
  34857. function MeshFaceMaterial(materials) {
  34858. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  34859. return materials;
  34860. }
  34861. function MultiMaterial(materials) {
  34862. if (materials === void 0) {
  34863. materials = [];
  34864. }
  34865. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  34866. materials.isMultiMaterial = true;
  34867. materials.materials = materials;
  34868. materials.clone = function () {
  34869. return materials.slice();
  34870. };
  34871. return materials;
  34872. }
  34873. function PointCloud(geometry, material) {
  34874. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  34875. return new Points(geometry, material);
  34876. }
  34877. function Particle(material) {
  34878. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  34879. return new Sprite(material);
  34880. }
  34881. function ParticleSystem(geometry, material) {
  34882. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  34883. return new Points(geometry, material);
  34884. }
  34885. function PointCloudMaterial(parameters) {
  34886. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  34887. return new PointsMaterial(parameters);
  34888. }
  34889. function ParticleBasicMaterial(parameters) {
  34890. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  34891. return new PointsMaterial(parameters);
  34892. }
  34893. function ParticleSystemMaterial(parameters) {
  34894. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  34895. return new PointsMaterial(parameters);
  34896. }
  34897. function Vertex(x, y, z) {
  34898. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  34899. return new Vector3(x, y, z);
  34900. } //
  34901. function DynamicBufferAttribute(array, itemSize) {
  34902. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  34903. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  34904. }
  34905. function Int8Attribute(array, itemSize) {
  34906. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  34907. return new Int8BufferAttribute(array, itemSize);
  34908. }
  34909. function Uint8Attribute(array, itemSize) {
  34910. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  34911. return new Uint8BufferAttribute(array, itemSize);
  34912. }
  34913. function Uint8ClampedAttribute(array, itemSize) {
  34914. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  34915. return new Uint8ClampedBufferAttribute(array, itemSize);
  34916. }
  34917. function Int16Attribute(array, itemSize) {
  34918. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  34919. return new Int16BufferAttribute(array, itemSize);
  34920. }
  34921. function Uint16Attribute(array, itemSize) {
  34922. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  34923. return new Uint16BufferAttribute(array, itemSize);
  34924. }
  34925. function Int32Attribute(array, itemSize) {
  34926. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  34927. return new Int32BufferAttribute(array, itemSize);
  34928. }
  34929. function Uint32Attribute(array, itemSize) {
  34930. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  34931. return new Uint32BufferAttribute(array, itemSize);
  34932. }
  34933. function Float32Attribute(array, itemSize) {
  34934. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  34935. return new Float32BufferAttribute(array, itemSize);
  34936. }
  34937. function Float64Attribute(array, itemSize) {
  34938. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  34939. return new Float64BufferAttribute(array, itemSize);
  34940. } //
  34941. Curve.create = function (construct, getPoint) {
  34942. console.log('THREE.Curve.create() has been deprecated');
  34943. construct.prototype = Object.create(Curve.prototype);
  34944. construct.prototype.constructor = construct;
  34945. construct.prototype.getPoint = getPoint;
  34946. return construct;
  34947. }; //
  34948. Object.assign(Path.prototype, {
  34949. fromPoints: function fromPoints(points) {
  34950. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  34951. return this.setFromPoints(points);
  34952. }
  34953. }); //
  34954. function ClosedSplineCurve3(points) {
  34955. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  34956. CatmullRomCurve3.call(this, points);
  34957. this.type = 'catmullrom';
  34958. this.closed = true;
  34959. }
  34960. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  34961. function SplineCurve3(points) {
  34962. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  34963. CatmullRomCurve3.call(this, points);
  34964. this.type = 'catmullrom';
  34965. }
  34966. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  34967. function Spline(points) {
  34968. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  34969. CatmullRomCurve3.call(this, points);
  34970. this.type = 'catmullrom';
  34971. }
  34972. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  34973. Object.assign(Spline.prototype, {
  34974. initFromArray: function initFromArray()
  34975. /* a */
  34976. {
  34977. console.error('THREE.Spline: .initFromArray() has been removed.');
  34978. },
  34979. getControlPointsArray: function getControlPointsArray()
  34980. /* optionalTarget */
  34981. {
  34982. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  34983. },
  34984. reparametrizeByArcLength: function reparametrizeByArcLength()
  34985. /* samplingCoef */
  34986. {
  34987. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  34988. }
  34989. }); //
  34990. function AxisHelper(size) {
  34991. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  34992. return new AxesHelper(size);
  34993. }
  34994. function BoundingBoxHelper(object, color) {
  34995. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  34996. return new BoxHelper(object, color);
  34997. }
  34998. function EdgesHelper(object, hex) {
  34999. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  35000. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  35001. color: hex !== undefined ? hex : 0xffffff
  35002. }));
  35003. }
  35004. GridHelper.prototype.setColors = function () {
  35005. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  35006. };
  35007. SkeletonHelper.prototype.update = function () {
  35008. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  35009. };
  35010. function WireframeHelper(object, hex) {
  35011. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  35012. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  35013. color: hex !== undefined ? hex : 0xffffff
  35014. }));
  35015. } //
  35016. Object.assign(Loader.prototype, {
  35017. extractUrlBase: function extractUrlBase(url) {
  35018. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  35019. return LoaderUtils.extractUrlBase(url);
  35020. }
  35021. });
  35022. Loader.Handlers = {
  35023. add: function add()
  35024. /* regex, loader */
  35025. {
  35026. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  35027. },
  35028. get: function get()
  35029. /* file */
  35030. {
  35031. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  35032. }
  35033. };
  35034. function XHRLoader(manager) {
  35035. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  35036. return new FileLoader(manager);
  35037. }
  35038. function BinaryTextureLoader(manager) {
  35039. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  35040. return new DataTextureLoader(manager);
  35041. } //
  35042. Object.assign(Box2.prototype, {
  35043. center: function center(optionalTarget) {
  35044. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  35045. return this.getCenter(optionalTarget);
  35046. },
  35047. empty: function empty() {
  35048. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  35049. return this.isEmpty();
  35050. },
  35051. isIntersectionBox: function isIntersectionBox(box) {
  35052. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  35053. return this.intersectsBox(box);
  35054. },
  35055. size: function size(optionalTarget) {
  35056. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  35057. return this.getSize(optionalTarget);
  35058. }
  35059. });
  35060. Object.assign(Box3.prototype, {
  35061. center: function center(optionalTarget) {
  35062. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  35063. return this.getCenter(optionalTarget);
  35064. },
  35065. empty: function empty() {
  35066. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  35067. return this.isEmpty();
  35068. },
  35069. isIntersectionBox: function isIntersectionBox(box) {
  35070. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  35071. return this.intersectsBox(box);
  35072. },
  35073. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35074. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35075. return this.intersectsSphere(sphere);
  35076. },
  35077. size: function size(optionalTarget) {
  35078. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  35079. return this.getSize(optionalTarget);
  35080. }
  35081. });
  35082. Object.assign(Sphere.prototype, {
  35083. empty: function empty() {
  35084. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  35085. return this.isEmpty();
  35086. }
  35087. });
  35088. Frustum.prototype.setFromMatrix = function (m) {
  35089. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  35090. return this.setFromProjectionMatrix(m);
  35091. };
  35092. Line3.prototype.center = function (optionalTarget) {
  35093. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  35094. return this.getCenter(optionalTarget);
  35095. };
  35096. Object.assign(MathUtils, {
  35097. random16: function random16() {
  35098. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  35099. return Math.random();
  35100. },
  35101. nearestPowerOfTwo: function nearestPowerOfTwo(value) {
  35102. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  35103. return MathUtils.floorPowerOfTwo(value);
  35104. },
  35105. nextPowerOfTwo: function nextPowerOfTwo(value) {
  35106. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  35107. return MathUtils.ceilPowerOfTwo(value);
  35108. }
  35109. });
  35110. Object.assign(Matrix3.prototype, {
  35111. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35112. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  35113. return this.toArray(array, offset);
  35114. },
  35115. multiplyVector3: function multiplyVector3(vector) {
  35116. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  35117. return vector.applyMatrix3(this);
  35118. },
  35119. multiplyVector3Array: function multiplyVector3Array()
  35120. /* a */
  35121. {
  35122. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  35123. },
  35124. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35125. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  35126. return attribute.applyMatrix3(this);
  35127. },
  35128. applyToVector3Array: function applyToVector3Array()
  35129. /* array, offset, length */
  35130. {
  35131. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  35132. },
  35133. getInverse: function getInverse(matrix) {
  35134. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35135. return this.copy(matrix).invert();
  35136. }
  35137. });
  35138. Object.assign(Matrix4.prototype, {
  35139. extractPosition: function extractPosition(m) {
  35140. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  35141. return this.copyPosition(m);
  35142. },
  35143. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35144. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  35145. return this.toArray(array, offset);
  35146. },
  35147. getPosition: function getPosition() {
  35148. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  35149. return new Vector3().setFromMatrixColumn(this, 3);
  35150. },
  35151. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  35152. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  35153. return this.makeRotationFromQuaternion(q);
  35154. },
  35155. multiplyToArray: function multiplyToArray() {
  35156. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  35157. },
  35158. multiplyVector3: function multiplyVector3(vector) {
  35159. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35160. return vector.applyMatrix4(this);
  35161. },
  35162. multiplyVector4: function multiplyVector4(vector) {
  35163. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35164. return vector.applyMatrix4(this);
  35165. },
  35166. multiplyVector3Array: function multiplyVector3Array()
  35167. /* a */
  35168. {
  35169. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  35170. },
  35171. rotateAxis: function rotateAxis(v) {
  35172. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  35173. v.transformDirection(this);
  35174. },
  35175. crossVector: function crossVector(vector) {
  35176. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35177. return vector.applyMatrix4(this);
  35178. },
  35179. translate: function translate() {
  35180. console.error('THREE.Matrix4: .translate() has been removed.');
  35181. },
  35182. rotateX: function rotateX() {
  35183. console.error('THREE.Matrix4: .rotateX() has been removed.');
  35184. },
  35185. rotateY: function rotateY() {
  35186. console.error('THREE.Matrix4: .rotateY() has been removed.');
  35187. },
  35188. rotateZ: function rotateZ() {
  35189. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  35190. },
  35191. rotateByAxis: function rotateByAxis() {
  35192. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  35193. },
  35194. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35195. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  35196. return attribute.applyMatrix4(this);
  35197. },
  35198. applyToVector3Array: function applyToVector3Array()
  35199. /* array, offset, length */
  35200. {
  35201. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  35202. },
  35203. makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {
  35204. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  35205. return this.makePerspective(left, right, top, bottom, near, far);
  35206. },
  35207. getInverse: function getInverse(matrix) {
  35208. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35209. return this.copy(matrix).invert();
  35210. }
  35211. });
  35212. Plane.prototype.isIntersectionLine = function (line) {
  35213. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  35214. return this.intersectsLine(line);
  35215. };
  35216. Object.assign(Quaternion.prototype, {
  35217. multiplyVector3: function multiplyVector3(vector) {
  35218. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  35219. return vector.applyQuaternion(this);
  35220. },
  35221. inverse: function inverse() {
  35222. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  35223. return this.invert();
  35224. }
  35225. });
  35226. Object.assign(Ray.prototype, {
  35227. isIntersectionBox: function isIntersectionBox(box) {
  35228. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  35229. return this.intersectsBox(box);
  35230. },
  35231. isIntersectionPlane: function isIntersectionPlane(plane) {
  35232. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  35233. return this.intersectsPlane(plane);
  35234. },
  35235. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35236. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35237. return this.intersectsSphere(sphere);
  35238. }
  35239. });
  35240. Object.assign(Triangle.prototype, {
  35241. area: function area() {
  35242. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  35243. return this.getArea();
  35244. },
  35245. barycoordFromPoint: function barycoordFromPoint(point, target) {
  35246. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35247. return this.getBarycoord(point, target);
  35248. },
  35249. midpoint: function midpoint(target) {
  35250. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  35251. return this.getMidpoint(target);
  35252. },
  35253. normal: function normal(target) {
  35254. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35255. return this.getNormal(target);
  35256. },
  35257. plane: function plane(target) {
  35258. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  35259. return this.getPlane(target);
  35260. }
  35261. });
  35262. Object.assign(Triangle, {
  35263. barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {
  35264. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35265. return Triangle.getBarycoord(point, a, b, c, target);
  35266. },
  35267. normal: function normal(a, b, c, target) {
  35268. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35269. return Triangle.getNormal(a, b, c, target);
  35270. }
  35271. });
  35272. Object.assign(Shape.prototype, {
  35273. extractAllPoints: function extractAllPoints(divisions) {
  35274. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  35275. return this.extractPoints(divisions);
  35276. },
  35277. extrude: function extrude(options) {
  35278. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  35279. return new ExtrudeGeometry(this, options);
  35280. },
  35281. makeGeometry: function makeGeometry(options) {
  35282. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  35283. return new ShapeGeometry(this, options);
  35284. }
  35285. });
  35286. Object.assign(Vector2.prototype, {
  35287. fromAttribute: function fromAttribute(attribute, index, offset) {
  35288. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35289. return this.fromBufferAttribute(attribute, index, offset);
  35290. },
  35291. distanceToManhattan: function distanceToManhattan(v) {
  35292. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  35293. return this.manhattanDistanceTo(v);
  35294. },
  35295. lengthManhattan: function lengthManhattan() {
  35296. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  35297. return this.manhattanLength();
  35298. }
  35299. });
  35300. Object.assign(Vector3.prototype, {
  35301. setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {
  35302. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  35303. },
  35304. setEulerFromQuaternion: function setEulerFromQuaternion() {
  35305. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  35306. },
  35307. getPositionFromMatrix: function getPositionFromMatrix(m) {
  35308. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  35309. return this.setFromMatrixPosition(m);
  35310. },
  35311. getScaleFromMatrix: function getScaleFromMatrix(m) {
  35312. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  35313. return this.setFromMatrixScale(m);
  35314. },
  35315. getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {
  35316. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  35317. return this.setFromMatrixColumn(matrix, index);
  35318. },
  35319. applyProjection: function applyProjection(m) {
  35320. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  35321. return this.applyMatrix4(m);
  35322. },
  35323. fromAttribute: function fromAttribute(attribute, index, offset) {
  35324. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35325. return this.fromBufferAttribute(attribute, index, offset);
  35326. },
  35327. distanceToManhattan: function distanceToManhattan(v) {
  35328. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  35329. return this.manhattanDistanceTo(v);
  35330. },
  35331. lengthManhattan: function lengthManhattan() {
  35332. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  35333. return this.manhattanLength();
  35334. }
  35335. });
  35336. Object.assign(Vector4.prototype, {
  35337. fromAttribute: function fromAttribute(attribute, index, offset) {
  35338. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35339. return this.fromBufferAttribute(attribute, index, offset);
  35340. },
  35341. lengthManhattan: function lengthManhattan() {
  35342. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  35343. return this.manhattanLength();
  35344. }
  35345. }); //
  35346. Object.assign(Object3D.prototype, {
  35347. getChildByName: function getChildByName(name) {
  35348. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  35349. return this.getObjectByName(name);
  35350. },
  35351. renderDepth: function renderDepth() {
  35352. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  35353. },
  35354. translate: function translate(distance, axis) {
  35355. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  35356. return this.translateOnAxis(axis, distance);
  35357. },
  35358. getWorldRotation: function getWorldRotation() {
  35359. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  35360. },
  35361. applyMatrix: function applyMatrix(matrix) {
  35362. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  35363. return this.applyMatrix4(matrix);
  35364. }
  35365. });
  35366. Object.defineProperties(Object3D.prototype, {
  35367. eulerOrder: {
  35368. get: function get() {
  35369. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  35370. return this.rotation.order;
  35371. },
  35372. set: function set(value) {
  35373. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  35374. this.rotation.order = value;
  35375. }
  35376. },
  35377. useQuaternion: {
  35378. get: function get() {
  35379. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  35380. },
  35381. set: function set() {
  35382. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  35383. }
  35384. }
  35385. });
  35386. Object.assign(Mesh.prototype, {
  35387. setDrawMode: function setDrawMode() {
  35388. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  35389. }
  35390. });
  35391. Object.defineProperties(Mesh.prototype, {
  35392. drawMode: {
  35393. get: function get() {
  35394. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  35395. return TrianglesDrawMode;
  35396. },
  35397. set: function set() {
  35398. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  35399. }
  35400. }
  35401. });
  35402. Object.defineProperties(LOD.prototype, {
  35403. objects: {
  35404. get: function get() {
  35405. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  35406. return this.levels;
  35407. }
  35408. }
  35409. });
  35410. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  35411. get: function get() {
  35412. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  35413. },
  35414. set: function set() {
  35415. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  35416. }
  35417. });
  35418. SkinnedMesh.prototype.initBones = function () {
  35419. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  35420. };
  35421. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  35422. get: function get() {
  35423. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  35424. return this.arcLengthDivisions;
  35425. },
  35426. set: function set(value) {
  35427. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  35428. this.arcLengthDivisions = value;
  35429. }
  35430. }); //
  35431. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  35432. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  35433. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  35434. this.setFocalLength(focalLength);
  35435. }; //
  35436. Object.defineProperties(Light.prototype, {
  35437. onlyShadow: {
  35438. set: function set() {
  35439. console.warn('THREE.Light: .onlyShadow has been removed.');
  35440. }
  35441. },
  35442. shadowCameraFov: {
  35443. set: function set(value) {
  35444. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  35445. this.shadow.camera.fov = value;
  35446. }
  35447. },
  35448. shadowCameraLeft: {
  35449. set: function set(value) {
  35450. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  35451. this.shadow.camera.left = value;
  35452. }
  35453. },
  35454. shadowCameraRight: {
  35455. set: function set(value) {
  35456. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  35457. this.shadow.camera.right = value;
  35458. }
  35459. },
  35460. shadowCameraTop: {
  35461. set: function set(value) {
  35462. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  35463. this.shadow.camera.top = value;
  35464. }
  35465. },
  35466. shadowCameraBottom: {
  35467. set: function set(value) {
  35468. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  35469. this.shadow.camera.bottom = value;
  35470. }
  35471. },
  35472. shadowCameraNear: {
  35473. set: function set(value) {
  35474. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  35475. this.shadow.camera.near = value;
  35476. }
  35477. },
  35478. shadowCameraFar: {
  35479. set: function set(value) {
  35480. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  35481. this.shadow.camera.far = value;
  35482. }
  35483. },
  35484. shadowCameraVisible: {
  35485. set: function set() {
  35486. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  35487. }
  35488. },
  35489. shadowBias: {
  35490. set: function set(value) {
  35491. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  35492. this.shadow.bias = value;
  35493. }
  35494. },
  35495. shadowDarkness: {
  35496. set: function set() {
  35497. console.warn('THREE.Light: .shadowDarkness has been removed.');
  35498. }
  35499. },
  35500. shadowMapWidth: {
  35501. set: function set(value) {
  35502. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  35503. this.shadow.mapSize.width = value;
  35504. }
  35505. },
  35506. shadowMapHeight: {
  35507. set: function set(value) {
  35508. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  35509. this.shadow.mapSize.height = value;
  35510. }
  35511. }
  35512. }); //
  35513. Object.defineProperties(BufferAttribute.prototype, {
  35514. length: {
  35515. get: function get() {
  35516. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  35517. return this.array.length;
  35518. }
  35519. },
  35520. dynamic: {
  35521. get: function get() {
  35522. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  35523. return this.usage === DynamicDrawUsage;
  35524. },
  35525. set: function set()
  35526. /* value */
  35527. {
  35528. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  35529. this.setUsage(DynamicDrawUsage);
  35530. }
  35531. }
  35532. });
  35533. Object.assign(BufferAttribute.prototype, {
  35534. setDynamic: function setDynamic(value) {
  35535. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  35536. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  35537. return this;
  35538. },
  35539. copyIndicesArray: function copyIndicesArray()
  35540. /* indices */
  35541. {
  35542. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  35543. },
  35544. setArray: function setArray()
  35545. /* array */
  35546. {
  35547. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  35548. }
  35549. });
  35550. Object.assign(BufferGeometry.prototype, {
  35551. addIndex: function addIndex(index) {
  35552. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  35553. this.setIndex(index);
  35554. },
  35555. addAttribute: function addAttribute(name, attribute) {
  35556. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  35557. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  35558. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  35559. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  35560. }
  35561. if (name === 'index') {
  35562. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  35563. this.setIndex(attribute);
  35564. return this;
  35565. }
  35566. return this.setAttribute(name, attribute);
  35567. },
  35568. addDrawCall: function addDrawCall(start, count, indexOffset) {
  35569. if (indexOffset !== undefined) {
  35570. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  35571. }
  35572. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  35573. this.addGroup(start, count);
  35574. },
  35575. clearDrawCalls: function clearDrawCalls() {
  35576. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  35577. this.clearGroups();
  35578. },
  35579. computeOffsets: function computeOffsets() {
  35580. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  35581. },
  35582. removeAttribute: function removeAttribute(name) {
  35583. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  35584. return this.deleteAttribute(name);
  35585. },
  35586. applyMatrix: function applyMatrix(matrix) {
  35587. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  35588. return this.applyMatrix4(matrix);
  35589. }
  35590. });
  35591. Object.defineProperties(BufferGeometry.prototype, {
  35592. drawcalls: {
  35593. get: function get() {
  35594. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  35595. return this.groups;
  35596. }
  35597. },
  35598. offsets: {
  35599. get: function get() {
  35600. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  35601. return this.groups;
  35602. }
  35603. }
  35604. });
  35605. Object.defineProperties(InstancedBufferGeometry.prototype, {
  35606. maxInstancedCount: {
  35607. get: function get() {
  35608. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  35609. return this.instanceCount;
  35610. },
  35611. set: function set(value) {
  35612. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  35613. this.instanceCount = value;
  35614. }
  35615. }
  35616. });
  35617. Object.defineProperties(Raycaster.prototype, {
  35618. linePrecision: {
  35619. get: function get() {
  35620. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  35621. return this.params.Line.threshold;
  35622. },
  35623. set: function set(value) {
  35624. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  35625. this.params.Line.threshold = value;
  35626. }
  35627. }
  35628. });
  35629. Object.defineProperties(InterleavedBuffer.prototype, {
  35630. dynamic: {
  35631. get: function get() {
  35632. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  35633. return this.usage === DynamicDrawUsage;
  35634. },
  35635. set: function set(value) {
  35636. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  35637. this.setUsage(value);
  35638. }
  35639. }
  35640. });
  35641. Object.assign(InterleavedBuffer.prototype, {
  35642. setDynamic: function setDynamic(value) {
  35643. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  35644. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  35645. return this;
  35646. },
  35647. setArray: function setArray()
  35648. /* array */
  35649. {
  35650. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  35651. }
  35652. }); //
  35653. Object.assign(ExtrudeGeometry.prototype, {
  35654. getArrays: function getArrays() {
  35655. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  35656. },
  35657. addShapeList: function addShapeList() {
  35658. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  35659. },
  35660. addShape: function addShape() {
  35661. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  35662. }
  35663. }); //
  35664. Object.assign(Scene.prototype, {
  35665. dispose: function dispose() {
  35666. console.error('THREE.Scene: .dispose() has been removed.');
  35667. }
  35668. }); //
  35669. Object.defineProperties(Uniform.prototype, {
  35670. dynamic: {
  35671. set: function set() {
  35672. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  35673. }
  35674. },
  35675. onUpdate: {
  35676. value: function value() {
  35677. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  35678. return this;
  35679. }
  35680. }
  35681. }); //
  35682. Object.defineProperties(Material.prototype, {
  35683. wrapAround: {
  35684. get: function get() {
  35685. console.warn('THREE.Material: .wrapAround has been removed.');
  35686. },
  35687. set: function set() {
  35688. console.warn('THREE.Material: .wrapAround has been removed.');
  35689. }
  35690. },
  35691. overdraw: {
  35692. get: function get() {
  35693. console.warn('THREE.Material: .overdraw has been removed.');
  35694. },
  35695. set: function set() {
  35696. console.warn('THREE.Material: .overdraw has been removed.');
  35697. }
  35698. },
  35699. wrapRGB: {
  35700. get: function get() {
  35701. console.warn('THREE.Material: .wrapRGB has been removed.');
  35702. return new Color();
  35703. }
  35704. },
  35705. shading: {
  35706. get: function get() {
  35707. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  35708. },
  35709. set: function set(value) {
  35710. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  35711. this.flatShading = value === FlatShading;
  35712. }
  35713. },
  35714. stencilMask: {
  35715. get: function get() {
  35716. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  35717. return this.stencilFuncMask;
  35718. },
  35719. set: function set(value) {
  35720. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  35721. this.stencilFuncMask = value;
  35722. }
  35723. }
  35724. });
  35725. Object.defineProperties(MeshPhongMaterial.prototype, {
  35726. metal: {
  35727. get: function get() {
  35728. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  35729. return false;
  35730. },
  35731. set: function set() {
  35732. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  35733. }
  35734. }
  35735. });
  35736. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  35737. transparency: {
  35738. get: function get() {
  35739. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  35740. return this.transmission;
  35741. },
  35742. set: function set(value) {
  35743. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  35744. this.transmission = value;
  35745. }
  35746. }
  35747. });
  35748. Object.defineProperties(ShaderMaterial.prototype, {
  35749. derivatives: {
  35750. get: function get() {
  35751. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  35752. return this.extensions.derivatives;
  35753. },
  35754. set: function set(value) {
  35755. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  35756. this.extensions.derivatives = value;
  35757. }
  35758. }
  35759. }); //
  35760. Object.assign(WebGLRenderer.prototype, {
  35761. clearTarget: function clearTarget(renderTarget, color, depth, stencil) {
  35762. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  35763. this.setRenderTarget(renderTarget);
  35764. this.clear(color, depth, stencil);
  35765. },
  35766. animate: function animate(callback) {
  35767. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  35768. this.setAnimationLoop(callback);
  35769. },
  35770. getCurrentRenderTarget: function getCurrentRenderTarget() {
  35771. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  35772. return this.getRenderTarget();
  35773. },
  35774. getMaxAnisotropy: function getMaxAnisotropy() {
  35775. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  35776. return this.capabilities.getMaxAnisotropy();
  35777. },
  35778. getPrecision: function getPrecision() {
  35779. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  35780. return this.capabilities.precision;
  35781. },
  35782. resetGLState: function resetGLState() {
  35783. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  35784. return this.state.reset();
  35785. },
  35786. supportsFloatTextures: function supportsFloatTextures() {
  35787. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  35788. return this.extensions.get('OES_texture_float');
  35789. },
  35790. supportsHalfFloatTextures: function supportsHalfFloatTextures() {
  35791. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  35792. return this.extensions.get('OES_texture_half_float');
  35793. },
  35794. supportsStandardDerivatives: function supportsStandardDerivatives() {
  35795. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  35796. return this.extensions.get('OES_standard_derivatives');
  35797. },
  35798. supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {
  35799. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  35800. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  35801. },
  35802. supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {
  35803. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  35804. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  35805. },
  35806. supportsBlendMinMax: function supportsBlendMinMax() {
  35807. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  35808. return this.extensions.get('EXT_blend_minmax');
  35809. },
  35810. supportsVertexTextures: function supportsVertexTextures() {
  35811. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  35812. return this.capabilities.vertexTextures;
  35813. },
  35814. supportsInstancedArrays: function supportsInstancedArrays() {
  35815. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  35816. return this.extensions.get('ANGLE_instanced_arrays');
  35817. },
  35818. enableScissorTest: function enableScissorTest(boolean) {
  35819. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  35820. this.setScissorTest(boolean);
  35821. },
  35822. initMaterial: function initMaterial() {
  35823. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  35824. },
  35825. addPrePlugin: function addPrePlugin() {
  35826. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  35827. },
  35828. addPostPlugin: function addPostPlugin() {
  35829. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  35830. },
  35831. updateShadowMap: function updateShadowMap() {
  35832. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  35833. },
  35834. setFaceCulling: function setFaceCulling() {
  35835. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  35836. },
  35837. allocTextureUnit: function allocTextureUnit() {
  35838. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  35839. },
  35840. setTexture: function setTexture() {
  35841. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  35842. },
  35843. setTextureCube: function setTextureCube() {
  35844. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  35845. },
  35846. getActiveMipMapLevel: function getActiveMipMapLevel() {
  35847. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  35848. return this.getActiveMipmapLevel();
  35849. }
  35850. });
  35851. Object.defineProperties(WebGLRenderer.prototype, {
  35852. shadowMapEnabled: {
  35853. get: function get() {
  35854. return this.shadowMap.enabled;
  35855. },
  35856. set: function set(value) {
  35857. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  35858. this.shadowMap.enabled = value;
  35859. }
  35860. },
  35861. shadowMapType: {
  35862. get: function get() {
  35863. return this.shadowMap.type;
  35864. },
  35865. set: function set(value) {
  35866. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  35867. this.shadowMap.type = value;
  35868. }
  35869. },
  35870. shadowMapCullFace: {
  35871. get: function get() {
  35872. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  35873. return undefined;
  35874. },
  35875. set: function set()
  35876. /* value */
  35877. {
  35878. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  35879. }
  35880. },
  35881. context: {
  35882. get: function get() {
  35883. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  35884. return this.getContext();
  35885. }
  35886. },
  35887. vr: {
  35888. get: function get() {
  35889. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  35890. return this.xr;
  35891. }
  35892. },
  35893. gammaInput: {
  35894. get: function get() {
  35895. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  35896. return false;
  35897. },
  35898. set: function set() {
  35899. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  35900. }
  35901. },
  35902. gammaOutput: {
  35903. get: function get() {
  35904. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  35905. return false;
  35906. },
  35907. set: function set(value) {
  35908. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  35909. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  35910. }
  35911. },
  35912. toneMappingWhitePoint: {
  35913. get: function get() {
  35914. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  35915. return 1.0;
  35916. },
  35917. set: function set() {
  35918. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  35919. }
  35920. }
  35921. });
  35922. Object.defineProperties(WebGLShadowMap.prototype, {
  35923. cullFace: {
  35924. get: function get() {
  35925. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  35926. return undefined;
  35927. },
  35928. set: function set()
  35929. /* cullFace */
  35930. {
  35931. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  35932. }
  35933. },
  35934. renderReverseSided: {
  35935. get: function get() {
  35936. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  35937. return undefined;
  35938. },
  35939. set: function set() {
  35940. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  35941. }
  35942. },
  35943. renderSingleSided: {
  35944. get: function get() {
  35945. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  35946. return undefined;
  35947. },
  35948. set: function set() {
  35949. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  35950. }
  35951. }
  35952. });
  35953. function WebGLRenderTargetCube(width, height, options) {
  35954. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  35955. return new WebGLCubeRenderTarget(width, options);
  35956. } //
  35957. Object.defineProperties(WebGLRenderTarget.prototype, {
  35958. wrapS: {
  35959. get: function get() {
  35960. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  35961. return this.texture.wrapS;
  35962. },
  35963. set: function set(value) {
  35964. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  35965. this.texture.wrapS = value;
  35966. }
  35967. },
  35968. wrapT: {
  35969. get: function get() {
  35970. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  35971. return this.texture.wrapT;
  35972. },
  35973. set: function set(value) {
  35974. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  35975. this.texture.wrapT = value;
  35976. }
  35977. },
  35978. magFilter: {
  35979. get: function get() {
  35980. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  35981. return this.texture.magFilter;
  35982. },
  35983. set: function set(value) {
  35984. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  35985. this.texture.magFilter = value;
  35986. }
  35987. },
  35988. minFilter: {
  35989. get: function get() {
  35990. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  35991. return this.texture.minFilter;
  35992. },
  35993. set: function set(value) {
  35994. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  35995. this.texture.minFilter = value;
  35996. }
  35997. },
  35998. anisotropy: {
  35999. get: function get() {
  36000. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36001. return this.texture.anisotropy;
  36002. },
  36003. set: function set(value) {
  36004. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36005. this.texture.anisotropy = value;
  36006. }
  36007. },
  36008. offset: {
  36009. get: function get() {
  36010. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36011. return this.texture.offset;
  36012. },
  36013. set: function set(value) {
  36014. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36015. this.texture.offset = value;
  36016. }
  36017. },
  36018. repeat: {
  36019. get: function get() {
  36020. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36021. return this.texture.repeat;
  36022. },
  36023. set: function set(value) {
  36024. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36025. this.texture.repeat = value;
  36026. }
  36027. },
  36028. format: {
  36029. get: function get() {
  36030. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36031. return this.texture.format;
  36032. },
  36033. set: function set(value) {
  36034. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36035. this.texture.format = value;
  36036. }
  36037. },
  36038. type: {
  36039. get: function get() {
  36040. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36041. return this.texture.type;
  36042. },
  36043. set: function set(value) {
  36044. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36045. this.texture.type = value;
  36046. }
  36047. },
  36048. generateMipmaps: {
  36049. get: function get() {
  36050. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36051. return this.texture.generateMipmaps;
  36052. },
  36053. set: function set(value) {
  36054. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36055. this.texture.generateMipmaps = value;
  36056. }
  36057. }
  36058. }); //
  36059. Object.defineProperties(Audio.prototype, {
  36060. load: {
  36061. value: function value(file) {
  36062. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  36063. var scope = this;
  36064. var audioLoader = new AudioLoader();
  36065. audioLoader.load(file, function (buffer) {
  36066. scope.setBuffer(buffer);
  36067. });
  36068. return this;
  36069. }
  36070. },
  36071. startTime: {
  36072. set: function set() {
  36073. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  36074. }
  36075. }
  36076. });
  36077. AudioAnalyser.prototype.getData = function () {
  36078. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  36079. return this.getFrequencyData();
  36080. }; //
  36081. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  36082. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  36083. return this.update(renderer, scene);
  36084. };
  36085. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  36086. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  36087. return this.renderTarget.clear(renderer, color, depth, stencil);
  36088. }; //
  36089. var GeometryUtils = {
  36090. merge: function merge(geometry1, geometry2, materialIndexOffset) {
  36091. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  36092. var matrix;
  36093. if (geometry2.isMesh) {
  36094. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  36095. matrix = geometry2.matrix;
  36096. geometry2 = geometry2.geometry;
  36097. }
  36098. geometry1.merge(geometry2, matrix, materialIndexOffset);
  36099. },
  36100. center: function center(geometry) {
  36101. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  36102. return geometry.center();
  36103. }
  36104. };
  36105. ImageUtils.crossOrigin = undefined;
  36106. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  36107. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  36108. var loader = new TextureLoader();
  36109. loader.setCrossOrigin(this.crossOrigin);
  36110. var texture = loader.load(url, onLoad, undefined, onError);
  36111. if (mapping) texture.mapping = mapping;
  36112. return texture;
  36113. };
  36114. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  36115. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  36116. var loader = new CubeTextureLoader();
  36117. loader.setCrossOrigin(this.crossOrigin);
  36118. var texture = loader.load(urls, onLoad, undefined, onError);
  36119. if (mapping) texture.mapping = mapping;
  36120. return texture;
  36121. };
  36122. ImageUtils.loadCompressedTexture = function () {
  36123. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  36124. };
  36125. ImageUtils.loadCompressedTextureCube = function () {
  36126. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  36127. }; //
  36128. function CanvasRenderer() {
  36129. console.error('THREE.CanvasRenderer has been removed');
  36130. } //
  36131. function JSONLoader() {
  36132. console.error('THREE.JSONLoader has been removed.');
  36133. } //
  36134. var SceneUtils = {
  36135. createMultiMaterialObject: function createMultiMaterialObject()
  36136. /* geometry, materials */
  36137. {
  36138. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36139. },
  36140. detach: function detach()
  36141. /* child, parent, scene */
  36142. {
  36143. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36144. },
  36145. attach: function attach()
  36146. /* child, scene, parent */
  36147. {
  36148. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36149. }
  36150. }; //
  36151. function LensFlare() {
  36152. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  36153. }
  36154. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  36155. /* eslint-disable no-undef */
  36156. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  36157. detail: {
  36158. revision: REVISION
  36159. }
  36160. }));
  36161. /* eslint-enable no-undef */
  36162. }
  36163. if (typeof window !== 'undefined') {
  36164. if (window.__THREE__) {
  36165. console.warn('WARNING: Multiple instances of Three.js being imported.');
  36166. } else {
  36167. window.__THREE__ = REVISION;
  36168. }
  36169. }
  36170. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  36171. exports.AddEquation = AddEquation;
  36172. exports.AddOperation = AddOperation;
  36173. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  36174. exports.AdditiveBlending = AdditiveBlending;
  36175. exports.AlphaFormat = AlphaFormat;
  36176. exports.AlwaysDepth = AlwaysDepth;
  36177. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  36178. exports.AmbientLight = AmbientLight;
  36179. exports.AmbientLightProbe = AmbientLightProbe;
  36180. exports.AnimationClip = AnimationClip;
  36181. exports.AnimationLoader = AnimationLoader;
  36182. exports.AnimationMixer = AnimationMixer;
  36183. exports.AnimationObjectGroup = AnimationObjectGroup;
  36184. exports.AnimationUtils = AnimationUtils;
  36185. exports.ArcCurve = ArcCurve;
  36186. exports.ArrayCamera = ArrayCamera;
  36187. exports.ArrowHelper = ArrowHelper;
  36188. exports.Audio = Audio;
  36189. exports.AudioAnalyser = AudioAnalyser;
  36190. exports.AudioContext = AudioContext;
  36191. exports.AudioListener = AudioListener;
  36192. exports.AudioLoader = AudioLoader;
  36193. exports.AxesHelper = AxesHelper;
  36194. exports.AxisHelper = AxisHelper;
  36195. exports.BackSide = BackSide;
  36196. exports.BasicDepthPacking = BasicDepthPacking;
  36197. exports.BasicShadowMap = BasicShadowMap;
  36198. exports.BinaryTextureLoader = BinaryTextureLoader;
  36199. exports.Bone = Bone;
  36200. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  36201. exports.BoundingBoxHelper = BoundingBoxHelper;
  36202. exports.Box2 = Box2;
  36203. exports.Box3 = Box3;
  36204. exports.Box3Helper = Box3Helper;
  36205. exports.BoxBufferGeometry = BoxGeometry;
  36206. exports.BoxGeometry = BoxGeometry;
  36207. exports.BoxHelper = BoxHelper;
  36208. exports.BufferAttribute = BufferAttribute;
  36209. exports.BufferGeometry = BufferGeometry;
  36210. exports.BufferGeometryLoader = BufferGeometryLoader;
  36211. exports.ByteType = ByteType;
  36212. exports.Cache = Cache;
  36213. exports.Camera = Camera;
  36214. exports.CameraHelper = CameraHelper;
  36215. exports.CanvasRenderer = CanvasRenderer;
  36216. exports.CanvasTexture = CanvasTexture;
  36217. exports.CatmullRomCurve3 = CatmullRomCurve3;
  36218. exports.CineonToneMapping = CineonToneMapping;
  36219. exports.CircleBufferGeometry = CircleGeometry;
  36220. exports.CircleGeometry = CircleGeometry;
  36221. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  36222. exports.Clock = Clock;
  36223. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  36224. exports.Color = Color;
  36225. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  36226. exports.CompressedTexture = CompressedTexture;
  36227. exports.CompressedTextureLoader = CompressedTextureLoader;
  36228. exports.ConeBufferGeometry = ConeGeometry;
  36229. exports.ConeGeometry = ConeGeometry;
  36230. exports.CubeCamera = CubeCamera;
  36231. exports.CubeReflectionMapping = CubeReflectionMapping;
  36232. exports.CubeRefractionMapping = CubeRefractionMapping;
  36233. exports.CubeTexture = CubeTexture;
  36234. exports.CubeTextureLoader = CubeTextureLoader;
  36235. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  36236. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  36237. exports.CubicBezierCurve = CubicBezierCurve;
  36238. exports.CubicBezierCurve3 = CubicBezierCurve3;
  36239. exports.CubicInterpolant = CubicInterpolant;
  36240. exports.CullFaceBack = CullFaceBack;
  36241. exports.CullFaceFront = CullFaceFront;
  36242. exports.CullFaceFrontBack = CullFaceFrontBack;
  36243. exports.CullFaceNone = CullFaceNone;
  36244. exports.Curve = Curve;
  36245. exports.CurvePath = CurvePath;
  36246. exports.CustomBlending = CustomBlending;
  36247. exports.CustomToneMapping = CustomToneMapping;
  36248. exports.CylinderBufferGeometry = CylinderGeometry;
  36249. exports.CylinderGeometry = CylinderGeometry;
  36250. exports.Cylindrical = Cylindrical;
  36251. exports.DataTexture = DataTexture;
  36252. exports.DataTexture2DArray = DataTexture2DArray;
  36253. exports.DataTexture3D = DataTexture3D;
  36254. exports.DataTextureLoader = DataTextureLoader;
  36255. exports.DataUtils = DataUtils;
  36256. exports.DecrementStencilOp = DecrementStencilOp;
  36257. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  36258. exports.DefaultLoadingManager = DefaultLoadingManager;
  36259. exports.DepthFormat = DepthFormat;
  36260. exports.DepthStencilFormat = DepthStencilFormat;
  36261. exports.DepthTexture = DepthTexture;
  36262. exports.DirectionalLight = DirectionalLight;
  36263. exports.DirectionalLightHelper = DirectionalLightHelper;
  36264. exports.DiscreteInterpolant = DiscreteInterpolant;
  36265. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  36266. exports.DodecahedronGeometry = DodecahedronGeometry;
  36267. exports.DoubleSide = DoubleSide;
  36268. exports.DstAlphaFactor = DstAlphaFactor;
  36269. exports.DstColorFactor = DstColorFactor;
  36270. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  36271. exports.DynamicCopyUsage = DynamicCopyUsage;
  36272. exports.DynamicDrawUsage = DynamicDrawUsage;
  36273. exports.DynamicReadUsage = DynamicReadUsage;
  36274. exports.EdgesGeometry = EdgesGeometry;
  36275. exports.EdgesHelper = EdgesHelper;
  36276. exports.EllipseCurve = EllipseCurve;
  36277. exports.EqualDepth = EqualDepth;
  36278. exports.EqualStencilFunc = EqualStencilFunc;
  36279. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  36280. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  36281. exports.Euler = Euler;
  36282. exports.EventDispatcher = EventDispatcher;
  36283. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  36284. exports.ExtrudeGeometry = ExtrudeGeometry;
  36285. exports.Face3 = Face3;
  36286. exports.Face4 = Face4;
  36287. exports.FaceColors = FaceColors;
  36288. exports.FileLoader = FileLoader;
  36289. exports.FlatShading = FlatShading;
  36290. exports.Float16BufferAttribute = Float16BufferAttribute;
  36291. exports.Float32Attribute = Float32Attribute;
  36292. exports.Float32BufferAttribute = Float32BufferAttribute;
  36293. exports.Float64Attribute = Float64Attribute;
  36294. exports.Float64BufferAttribute = Float64BufferAttribute;
  36295. exports.FloatType = FloatType;
  36296. exports.Fog = Fog;
  36297. exports.FogExp2 = FogExp2;
  36298. exports.Font = Font;
  36299. exports.FontLoader = FontLoader;
  36300. exports.FrontSide = FrontSide;
  36301. exports.Frustum = Frustum;
  36302. exports.GLBufferAttribute = GLBufferAttribute;
  36303. exports.GLSL1 = GLSL1;
  36304. exports.GLSL3 = GLSL3;
  36305. exports.GammaEncoding = GammaEncoding;
  36306. exports.GeometryUtils = GeometryUtils;
  36307. exports.GreaterDepth = GreaterDepth;
  36308. exports.GreaterEqualDepth = GreaterEqualDepth;
  36309. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  36310. exports.GreaterStencilFunc = GreaterStencilFunc;
  36311. exports.GridHelper = GridHelper;
  36312. exports.Group = Group;
  36313. exports.HalfFloatType = HalfFloatType;
  36314. exports.HemisphereLight = HemisphereLight;
  36315. exports.HemisphereLightHelper = HemisphereLightHelper;
  36316. exports.HemisphereLightProbe = HemisphereLightProbe;
  36317. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  36318. exports.IcosahedronGeometry = IcosahedronGeometry;
  36319. exports.ImageBitmapLoader = ImageBitmapLoader;
  36320. exports.ImageLoader = ImageLoader;
  36321. exports.ImageUtils = ImageUtils;
  36322. exports.ImmediateRenderObject = ImmediateRenderObject;
  36323. exports.IncrementStencilOp = IncrementStencilOp;
  36324. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  36325. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  36326. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  36327. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  36328. exports.InstancedMesh = InstancedMesh;
  36329. exports.Int16Attribute = Int16Attribute;
  36330. exports.Int16BufferAttribute = Int16BufferAttribute;
  36331. exports.Int32Attribute = Int32Attribute;
  36332. exports.Int32BufferAttribute = Int32BufferAttribute;
  36333. exports.Int8Attribute = Int8Attribute;
  36334. exports.Int8BufferAttribute = Int8BufferAttribute;
  36335. exports.IntType = IntType;
  36336. exports.InterleavedBuffer = InterleavedBuffer;
  36337. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  36338. exports.Interpolant = Interpolant;
  36339. exports.InterpolateDiscrete = InterpolateDiscrete;
  36340. exports.InterpolateLinear = InterpolateLinear;
  36341. exports.InterpolateSmooth = InterpolateSmooth;
  36342. exports.InvertStencilOp = InvertStencilOp;
  36343. exports.JSONLoader = JSONLoader;
  36344. exports.KeepStencilOp = KeepStencilOp;
  36345. exports.KeyframeTrack = KeyframeTrack;
  36346. exports.LOD = LOD;
  36347. exports.LatheBufferGeometry = LatheGeometry;
  36348. exports.LatheGeometry = LatheGeometry;
  36349. exports.Layers = Layers;
  36350. exports.LensFlare = LensFlare;
  36351. exports.LessDepth = LessDepth;
  36352. exports.LessEqualDepth = LessEqualDepth;
  36353. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  36354. exports.LessStencilFunc = LessStencilFunc;
  36355. exports.Light = Light;
  36356. exports.LightProbe = LightProbe;
  36357. exports.Line = Line;
  36358. exports.Line3 = Line3;
  36359. exports.LineBasicMaterial = LineBasicMaterial;
  36360. exports.LineCurve = LineCurve;
  36361. exports.LineCurve3 = LineCurve3;
  36362. exports.LineDashedMaterial = LineDashedMaterial;
  36363. exports.LineLoop = LineLoop;
  36364. exports.LinePieces = LinePieces;
  36365. exports.LineSegments = LineSegments;
  36366. exports.LineStrip = LineStrip;
  36367. exports.LinearEncoding = LinearEncoding;
  36368. exports.LinearFilter = LinearFilter;
  36369. exports.LinearInterpolant = LinearInterpolant;
  36370. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  36371. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  36372. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  36373. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  36374. exports.LinearToneMapping = LinearToneMapping;
  36375. exports.Loader = Loader;
  36376. exports.LoaderUtils = LoaderUtils;
  36377. exports.LoadingManager = LoadingManager;
  36378. exports.LogLuvEncoding = LogLuvEncoding;
  36379. exports.LoopOnce = LoopOnce;
  36380. exports.LoopPingPong = LoopPingPong;
  36381. exports.LoopRepeat = LoopRepeat;
  36382. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  36383. exports.LuminanceFormat = LuminanceFormat;
  36384. exports.MOUSE = MOUSE;
  36385. exports.Material = Material;
  36386. exports.MaterialLoader = MaterialLoader;
  36387. exports.Math = MathUtils;
  36388. exports.MathUtils = MathUtils;
  36389. exports.Matrix3 = Matrix3;
  36390. exports.Matrix4 = Matrix4;
  36391. exports.MaxEquation = MaxEquation;
  36392. exports.Mesh = Mesh;
  36393. exports.MeshBasicMaterial = MeshBasicMaterial;
  36394. exports.MeshDepthMaterial = MeshDepthMaterial;
  36395. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  36396. exports.MeshFaceMaterial = MeshFaceMaterial;
  36397. exports.MeshLambertMaterial = MeshLambertMaterial;
  36398. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  36399. exports.MeshNormalMaterial = MeshNormalMaterial;
  36400. exports.MeshPhongMaterial = MeshPhongMaterial;
  36401. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  36402. exports.MeshStandardMaterial = MeshStandardMaterial;
  36403. exports.MeshToonMaterial = MeshToonMaterial;
  36404. exports.MinEquation = MinEquation;
  36405. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  36406. exports.MixOperation = MixOperation;
  36407. exports.MultiMaterial = MultiMaterial;
  36408. exports.MultiplyBlending = MultiplyBlending;
  36409. exports.MultiplyOperation = MultiplyOperation;
  36410. exports.NearestFilter = NearestFilter;
  36411. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  36412. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  36413. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  36414. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  36415. exports.NeverDepth = NeverDepth;
  36416. exports.NeverStencilFunc = NeverStencilFunc;
  36417. exports.NoBlending = NoBlending;
  36418. exports.NoColors = NoColors;
  36419. exports.NoToneMapping = NoToneMapping;
  36420. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  36421. exports.NormalBlending = NormalBlending;
  36422. exports.NotEqualDepth = NotEqualDepth;
  36423. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  36424. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  36425. exports.Object3D = Object3D;
  36426. exports.ObjectLoader = ObjectLoader;
  36427. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  36428. exports.OctahedronBufferGeometry = OctahedronGeometry;
  36429. exports.OctahedronGeometry = OctahedronGeometry;
  36430. exports.OneFactor = OneFactor;
  36431. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  36432. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  36433. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  36434. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  36435. exports.OrthographicCamera = OrthographicCamera;
  36436. exports.PCFShadowMap = PCFShadowMap;
  36437. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  36438. exports.PMREMGenerator = PMREMGenerator;
  36439. exports.ParametricBufferGeometry = ParametricGeometry;
  36440. exports.ParametricGeometry = ParametricGeometry;
  36441. exports.Particle = Particle;
  36442. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  36443. exports.ParticleSystem = ParticleSystem;
  36444. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  36445. exports.Path = Path;
  36446. exports.PerspectiveCamera = PerspectiveCamera;
  36447. exports.Plane = Plane;
  36448. exports.PlaneBufferGeometry = PlaneGeometry;
  36449. exports.PlaneGeometry = PlaneGeometry;
  36450. exports.PlaneHelper = PlaneHelper;
  36451. exports.PointCloud = PointCloud;
  36452. exports.PointCloudMaterial = PointCloudMaterial;
  36453. exports.PointLight = PointLight;
  36454. exports.PointLightHelper = PointLightHelper;
  36455. exports.Points = Points;
  36456. exports.PointsMaterial = PointsMaterial;
  36457. exports.PolarGridHelper = PolarGridHelper;
  36458. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  36459. exports.PolyhedronGeometry = PolyhedronGeometry;
  36460. exports.PositionalAudio = PositionalAudio;
  36461. exports.PropertyBinding = PropertyBinding;
  36462. exports.PropertyMixer = PropertyMixer;
  36463. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  36464. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  36465. exports.Quaternion = Quaternion;
  36466. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  36467. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  36468. exports.REVISION = REVISION;
  36469. exports.RGBADepthPacking = RGBADepthPacking;
  36470. exports.RGBAFormat = RGBAFormat;
  36471. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  36472. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  36473. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  36474. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  36475. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  36476. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  36477. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  36478. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  36479. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  36480. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  36481. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  36482. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  36483. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  36484. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  36485. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  36486. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  36487. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  36488. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  36489. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  36490. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  36491. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  36492. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  36493. exports.RGBDEncoding = RGBDEncoding;
  36494. exports.RGBEEncoding = RGBEEncoding;
  36495. exports.RGBEFormat = RGBEFormat;
  36496. exports.RGBFormat = RGBFormat;
  36497. exports.RGBIntegerFormat = RGBIntegerFormat;
  36498. exports.RGBM16Encoding = RGBM16Encoding;
  36499. exports.RGBM7Encoding = RGBM7Encoding;
  36500. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  36501. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  36502. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  36503. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  36504. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  36505. exports.RGFormat = RGFormat;
  36506. exports.RGIntegerFormat = RGIntegerFormat;
  36507. exports.RawShaderMaterial = RawShaderMaterial;
  36508. exports.Ray = Ray;
  36509. exports.Raycaster = Raycaster;
  36510. exports.RectAreaLight = RectAreaLight;
  36511. exports.RedFormat = RedFormat;
  36512. exports.RedIntegerFormat = RedIntegerFormat;
  36513. exports.ReinhardToneMapping = ReinhardToneMapping;
  36514. exports.RepeatWrapping = RepeatWrapping;
  36515. exports.ReplaceStencilOp = ReplaceStencilOp;
  36516. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  36517. exports.RingBufferGeometry = RingGeometry;
  36518. exports.RingGeometry = RingGeometry;
  36519. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  36520. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  36521. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  36522. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  36523. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  36524. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  36525. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  36526. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  36527. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  36528. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  36529. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  36530. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  36531. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  36532. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  36533. exports.Scene = Scene;
  36534. exports.SceneUtils = SceneUtils;
  36535. exports.ShaderChunk = ShaderChunk;
  36536. exports.ShaderLib = ShaderLib;
  36537. exports.ShaderMaterial = ShaderMaterial;
  36538. exports.ShadowMaterial = ShadowMaterial;
  36539. exports.Shape = Shape;
  36540. exports.ShapeBufferGeometry = ShapeGeometry;
  36541. exports.ShapeGeometry = ShapeGeometry;
  36542. exports.ShapePath = ShapePath;
  36543. exports.ShapeUtils = ShapeUtils;
  36544. exports.ShortType = ShortType;
  36545. exports.Skeleton = Skeleton;
  36546. exports.SkeletonHelper = SkeletonHelper;
  36547. exports.SkinnedMesh = SkinnedMesh;
  36548. exports.SmoothShading = SmoothShading;
  36549. exports.Sphere = Sphere;
  36550. exports.SphereBufferGeometry = SphereGeometry;
  36551. exports.SphereGeometry = SphereGeometry;
  36552. exports.Spherical = Spherical;
  36553. exports.SphericalHarmonics3 = SphericalHarmonics3;
  36554. exports.Spline = Spline;
  36555. exports.SplineCurve = SplineCurve;
  36556. exports.SplineCurve3 = SplineCurve3;
  36557. exports.SpotLight = SpotLight;
  36558. exports.SpotLightHelper = SpotLightHelper;
  36559. exports.Sprite = Sprite;
  36560. exports.SpriteMaterial = SpriteMaterial;
  36561. exports.SrcAlphaFactor = SrcAlphaFactor;
  36562. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  36563. exports.SrcColorFactor = SrcColorFactor;
  36564. exports.StaticCopyUsage = StaticCopyUsage;
  36565. exports.StaticDrawUsage = StaticDrawUsage;
  36566. exports.StaticReadUsage = StaticReadUsage;
  36567. exports.StereoCamera = StereoCamera;
  36568. exports.StreamCopyUsage = StreamCopyUsage;
  36569. exports.StreamDrawUsage = StreamDrawUsage;
  36570. exports.StreamReadUsage = StreamReadUsage;
  36571. exports.StringKeyframeTrack = StringKeyframeTrack;
  36572. exports.SubtractEquation = SubtractEquation;
  36573. exports.SubtractiveBlending = SubtractiveBlending;
  36574. exports.TOUCH = TOUCH;
  36575. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  36576. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  36577. exports.TetrahedronGeometry = TetrahedronGeometry;
  36578. exports.TextBufferGeometry = TextGeometry;
  36579. exports.TextGeometry = TextGeometry;
  36580. exports.Texture = Texture;
  36581. exports.TextureLoader = TextureLoader;
  36582. exports.TorusBufferGeometry = TorusGeometry;
  36583. exports.TorusGeometry = TorusGeometry;
  36584. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  36585. exports.TorusKnotGeometry = TorusKnotGeometry;
  36586. exports.Triangle = Triangle;
  36587. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  36588. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  36589. exports.TrianglesDrawMode = TrianglesDrawMode;
  36590. exports.TubeBufferGeometry = TubeGeometry;
  36591. exports.TubeGeometry = TubeGeometry;
  36592. exports.UVMapping = UVMapping;
  36593. exports.Uint16Attribute = Uint16Attribute;
  36594. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  36595. exports.Uint32Attribute = Uint32Attribute;
  36596. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  36597. exports.Uint8Attribute = Uint8Attribute;
  36598. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  36599. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  36600. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  36601. exports.Uniform = Uniform;
  36602. exports.UniformsLib = UniformsLib;
  36603. exports.UniformsUtils = UniformsUtils;
  36604. exports.UnsignedByteType = UnsignedByteType;
  36605. exports.UnsignedInt248Type = UnsignedInt248Type;
  36606. exports.UnsignedIntType = UnsignedIntType;
  36607. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  36608. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  36609. exports.UnsignedShort565Type = UnsignedShort565Type;
  36610. exports.UnsignedShortType = UnsignedShortType;
  36611. exports.VSMShadowMap = VSMShadowMap;
  36612. exports.Vector2 = Vector2;
  36613. exports.Vector3 = Vector3;
  36614. exports.Vector4 = Vector4;
  36615. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  36616. exports.Vertex = Vertex;
  36617. exports.VertexColors = VertexColors;
  36618. exports.VideoTexture = VideoTexture;
  36619. exports.WebGL1Renderer = WebGL1Renderer;
  36620. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  36621. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  36622. exports.WebGLRenderTarget = WebGLRenderTarget;
  36623. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  36624. exports.WebGLRenderer = WebGLRenderer;
  36625. exports.WebGLUtils = WebGLUtils;
  36626. exports.WireframeGeometry = WireframeGeometry;
  36627. exports.WireframeHelper = WireframeHelper;
  36628. exports.WrapAroundEnding = WrapAroundEnding;
  36629. exports.XHRLoader = XHRLoader;
  36630. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  36631. exports.ZeroFactor = ZeroFactor;
  36632. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  36633. exports.ZeroStencilOp = ZeroStencilOp;
  36634. exports.sRGBEncoding = sRGBEncoding;
  36635. Object.defineProperty(exports, '__esModule', { value: true });
  36636. })));
  36637. },{}],58:[function(_dereq_,module,exports){
  36638. THREE.DRACOLoader = function ( manager ) {
  36639. THREE.Loader.call( this, manager );
  36640. this.decoderPath = '';
  36641. this.decoderConfig = {};
  36642. this.decoderBinary = null;
  36643. this.decoderPending = null;
  36644. this.workerLimit = 4;
  36645. this.workerPool = [];
  36646. this.workerNextTaskID = 1;
  36647. this.workerSourceURL = '';
  36648. this.defaultAttributeIDs = {
  36649. position: 'POSITION',
  36650. normal: 'NORMAL',
  36651. color: 'COLOR',
  36652. uv: 'TEX_COORD'
  36653. };
  36654. this.defaultAttributeTypes = {
  36655. position: 'Float32Array',
  36656. normal: 'Float32Array',
  36657. color: 'Float32Array',
  36658. uv: 'Float32Array'
  36659. };
  36660. };
  36661. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36662. constructor: THREE.DRACOLoader,
  36663. setDecoderPath: function ( path ) {
  36664. this.decoderPath = path;
  36665. return this;
  36666. },
  36667. setDecoderConfig: function ( config ) {
  36668. this.decoderConfig = config;
  36669. return this;
  36670. },
  36671. setWorkerLimit: function ( workerLimit ) {
  36672. this.workerLimit = workerLimit;
  36673. return this;
  36674. },
  36675. /** @deprecated */
  36676. setVerbosity: function () {
  36677. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  36678. },
  36679. /** @deprecated */
  36680. setDrawMode: function () {
  36681. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  36682. },
  36683. /** @deprecated */
  36684. setSkipDequantization: function () {
  36685. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  36686. },
  36687. load: function ( url, onLoad, onProgress, onError ) {
  36688. var loader = new THREE.FileLoader( this.manager );
  36689. loader.setPath( this.path );
  36690. loader.setResponseType( 'arraybuffer' );
  36691. loader.setRequestHeader( this.requestHeader );
  36692. loader.setWithCredentials( this.withCredentials );
  36693. loader.load( url, ( buffer ) => {
  36694. var taskConfig = {
  36695. attributeIDs: this.defaultAttributeIDs,
  36696. attributeTypes: this.defaultAttributeTypes,
  36697. useUniqueIDs: false
  36698. };
  36699. this.decodeGeometry( buffer, taskConfig )
  36700. .then( onLoad )
  36701. .catch( onError );
  36702. }, onProgress, onError );
  36703. },
  36704. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  36705. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  36706. var taskConfig = {
  36707. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  36708. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  36709. useUniqueIDs: !! attributeIDs
  36710. };
  36711. this.decodeGeometry( buffer, taskConfig ).then( callback );
  36712. },
  36713. decodeGeometry: function ( buffer, taskConfig ) {
  36714. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  36715. // references (rather than names) to typed array constructors. These must be
  36716. // serialized before sending them to the worker.
  36717. for ( var attribute in taskConfig.attributeTypes ) {
  36718. var type = taskConfig.attributeTypes[ attribute ];
  36719. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  36720. taskConfig.attributeTypes[ attribute ] = type.name;
  36721. }
  36722. }
  36723. //
  36724. var taskKey = JSON.stringify( taskConfig );
  36725. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  36726. // again from this thread.
  36727. if ( THREE.DRACOLoader.taskCache.has( buffer ) ) {
  36728. var cachedTask = THREE.DRACOLoader.taskCache.get( buffer );
  36729. if ( cachedTask.key === taskKey ) {
  36730. return cachedTask.promise;
  36731. } else if ( buffer.byteLength === 0 ) {
  36732. // Technically, it would be possible to wait for the previous task to complete,
  36733. // transfer the buffer back, and decode again with the second configuration. That
  36734. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  36735. // different ways, so this is left unimplemented.
  36736. throw new Error(
  36737. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  36738. 'settings. Buffer has already been transferred.'
  36739. );
  36740. }
  36741. }
  36742. //
  36743. var worker;
  36744. var taskID = this.workerNextTaskID ++;
  36745. var taskCost = buffer.byteLength;
  36746. // Obtain a worker and assign a task, and construct a geometry instance
  36747. // when the task completes.
  36748. var geometryPending = this._getWorker( taskID, taskCost )
  36749. .then( ( _worker ) => {
  36750. worker = _worker;
  36751. return new Promise( ( resolve, reject ) => {
  36752. worker._callbacks[ taskID ] = { resolve, reject };
  36753. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  36754. // this.debug();
  36755. } );
  36756. } )
  36757. .then( ( message ) => this._createGeometry( message.geometry ) );
  36758. // Remove task from the task list.
  36759. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  36760. geometryPending
  36761. .catch( () => true )
  36762. .then( () => {
  36763. if ( worker && taskID ) {
  36764. this._releaseTask( worker, taskID );
  36765. // this.debug();
  36766. }
  36767. } );
  36768. // Cache the task result.
  36769. THREE.DRACOLoader.taskCache.set( buffer, {
  36770. key: taskKey,
  36771. promise: geometryPending
  36772. } );
  36773. return geometryPending;
  36774. },
  36775. _createGeometry: function ( geometryData ) {
  36776. var geometry = new THREE.BufferGeometry();
  36777. if ( geometryData.index ) {
  36778. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  36779. }
  36780. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  36781. var attribute = geometryData.attributes[ i ];
  36782. var name = attribute.name;
  36783. var array = attribute.array;
  36784. var itemSize = attribute.itemSize;
  36785. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  36786. }
  36787. return geometry;
  36788. },
  36789. _loadLibrary: function ( url, responseType ) {
  36790. var loader = new THREE.FileLoader( this.manager );
  36791. loader.setPath( this.decoderPath );
  36792. loader.setResponseType( responseType );
  36793. loader.setWithCredentials( this.withCredentials );
  36794. return new Promise( ( resolve, reject ) => {
  36795. loader.load( url, resolve, undefined, reject );
  36796. } );
  36797. },
  36798. preload: function () {
  36799. this._initDecoder();
  36800. return this;
  36801. },
  36802. _initDecoder: function () {
  36803. if ( this.decoderPending ) return this.decoderPending;
  36804. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  36805. var librariesPending = [];
  36806. if ( useJS ) {
  36807. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  36808. } else {
  36809. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  36810. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  36811. }
  36812. this.decoderPending = Promise.all( librariesPending )
  36813. .then( ( libraries ) => {
  36814. var jsContent = libraries[ 0 ];
  36815. if ( ! useJS ) {
  36816. this.decoderConfig.wasmBinary = libraries[ 1 ];
  36817. }
  36818. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  36819. var body = [
  36820. '/* draco decoder */',
  36821. jsContent,
  36822. '',
  36823. '/* worker */',
  36824. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  36825. ].join( '\n' );
  36826. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  36827. } );
  36828. return this.decoderPending;
  36829. },
  36830. _getWorker: function ( taskID, taskCost ) {
  36831. return this._initDecoder().then( () => {
  36832. if ( this.workerPool.length < this.workerLimit ) {
  36833. var worker = new Worker( this.workerSourceURL );
  36834. worker._callbacks = {};
  36835. worker._taskCosts = {};
  36836. worker._taskLoad = 0;
  36837. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  36838. worker.onmessage = function ( e ) {
  36839. var message = e.data;
  36840. switch ( message.type ) {
  36841. case 'decode':
  36842. worker._callbacks[ message.id ].resolve( message );
  36843. break;
  36844. case 'error':
  36845. worker._callbacks[ message.id ].reject( message );
  36846. break;
  36847. default:
  36848. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  36849. }
  36850. };
  36851. this.workerPool.push( worker );
  36852. } else {
  36853. this.workerPool.sort( function ( a, b ) {
  36854. return a._taskLoad > b._taskLoad ? - 1 : 1;
  36855. } );
  36856. }
  36857. var worker = this.workerPool[ this.workerPool.length - 1 ];
  36858. worker._taskCosts[ taskID ] = taskCost;
  36859. worker._taskLoad += taskCost;
  36860. return worker;
  36861. } );
  36862. },
  36863. _releaseTask: function ( worker, taskID ) {
  36864. worker._taskLoad -= worker._taskCosts[ taskID ];
  36865. delete worker._callbacks[ taskID ];
  36866. delete worker._taskCosts[ taskID ];
  36867. },
  36868. debug: function () {
  36869. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  36870. },
  36871. dispose: function () {
  36872. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  36873. this.workerPool[ i ].terminate();
  36874. }
  36875. this.workerPool.length = 0;
  36876. return this;
  36877. }
  36878. } );
  36879. /* WEB WORKER */
  36880. THREE.DRACOLoader.DRACOWorker = function () {
  36881. var decoderConfig;
  36882. var decoderPending;
  36883. onmessage = function ( e ) {
  36884. var message = e.data;
  36885. switch ( message.type ) {
  36886. case 'init':
  36887. decoderConfig = message.decoderConfig;
  36888. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  36889. decoderConfig.onModuleLoaded = function ( draco ) {
  36890. // Module is Promise-like. Wrap before resolving to avoid loop.
  36891. resolve( { draco: draco } );
  36892. };
  36893. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  36894. } );
  36895. break;
  36896. case 'decode':
  36897. var buffer = message.buffer;
  36898. var taskConfig = message.taskConfig;
  36899. decoderPending.then( ( module ) => {
  36900. var draco = module.draco;
  36901. var decoder = new draco.Decoder();
  36902. var decoderBuffer = new draco.DecoderBuffer();
  36903. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  36904. try {
  36905. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  36906. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  36907. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  36908. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  36909. } catch ( error ) {
  36910. console.error( error );
  36911. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  36912. } finally {
  36913. draco.destroy( decoderBuffer );
  36914. draco.destroy( decoder );
  36915. }
  36916. } );
  36917. break;
  36918. }
  36919. };
  36920. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  36921. var attributeIDs = taskConfig.attributeIDs;
  36922. var attributeTypes = taskConfig.attributeTypes;
  36923. var dracoGeometry;
  36924. var decodingStatus;
  36925. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  36926. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36927. dracoGeometry = new draco.Mesh();
  36928. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  36929. } else if ( geometryType === draco.POINT_CLOUD ) {
  36930. dracoGeometry = new draco.PointCloud();
  36931. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  36932. } else {
  36933. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  36934. }
  36935. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  36936. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  36937. }
  36938. var geometry = { index: null, attributes: [] };
  36939. // Gather all vertex attributes.
  36940. for ( var attributeName in attributeIDs ) {
  36941. var attributeType = self[ attributeTypes[ attributeName ] ];
  36942. var attribute;
  36943. var attributeID;
  36944. // A Draco file may be created with default vertex attributes, whose attribute IDs
  36945. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  36946. // a Draco file may contain a custom set of attributes, identified by known unique
  36947. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  36948. if ( taskConfig.useUniqueIDs ) {
  36949. attributeID = attributeIDs[ attributeName ];
  36950. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  36951. } else {
  36952. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  36953. if ( attributeID === - 1 ) continue;
  36954. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  36955. }
  36956. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  36957. }
  36958. // Add index.
  36959. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36960. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  36961. }
  36962. draco.destroy( dracoGeometry );
  36963. return geometry;
  36964. }
  36965. function decodeIndex( draco, decoder, dracoGeometry ) {
  36966. var numFaces = dracoGeometry.num_faces();
  36967. var numIndices = numFaces * 3;
  36968. var byteLength = numIndices * 4;
  36969. var ptr = draco._malloc( byteLength );
  36970. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  36971. var index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  36972. draco._free( ptr );
  36973. return { array: index, itemSize: 1 };
  36974. }
  36975. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  36976. var numComponents = attribute.num_components();
  36977. var numPoints = dracoGeometry.num_points();
  36978. var numValues = numPoints * numComponents;
  36979. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  36980. var dataType = getDracoDataType( draco, attributeType );
  36981. var ptr = draco._malloc( byteLength );
  36982. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  36983. var array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  36984. draco._free( ptr );
  36985. return {
  36986. name: attributeName,
  36987. array: array,
  36988. itemSize: numComponents
  36989. };
  36990. }
  36991. function getDracoDataType( draco, attributeType ) {
  36992. switch ( attributeType ) {
  36993. case Float32Array: return draco.DT_FLOAT32;
  36994. case Int8Array: return draco.DT_INT8;
  36995. case Int16Array: return draco.DT_INT16;
  36996. case Int32Array: return draco.DT_INT32;
  36997. case Uint8Array: return draco.DT_UINT8;
  36998. case Uint16Array: return draco.DT_UINT16;
  36999. case Uint32Array: return draco.DT_UINT32;
  37000. }
  37001. }
  37002. };
  37003. THREE.DRACOLoader.taskCache = new WeakMap();
  37004. /** Deprecated static methods */
  37005. /** @deprecated */
  37006. THREE.DRACOLoader.setDecoderPath = function () {
  37007. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  37008. };
  37009. /** @deprecated */
  37010. THREE.DRACOLoader.setDecoderConfig = function () {
  37011. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  37012. };
  37013. /** @deprecated */
  37014. THREE.DRACOLoader.releaseDecoderModule = function () {
  37015. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  37016. };
  37017. /** @deprecated */
  37018. THREE.DRACOLoader.getDecoderModule = function () {
  37019. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  37020. };
  37021. },{}],59:[function(_dereq_,module,exports){
  37022. THREE.GLTFLoader = ( function () {
  37023. function GLTFLoader( manager ) {
  37024. THREE.Loader.call( this, manager );
  37025. this.dracoLoader = null;
  37026. this.ddsLoader = null;
  37027. this.ktx2Loader = null;
  37028. this.meshoptDecoder = null;
  37029. this.pluginCallbacks = [];
  37030. this.register( function ( parser ) {
  37031. return new GLTFMaterialsClearcoatExtension( parser );
  37032. } );
  37033. this.register( function ( parser ) {
  37034. return new GLTFTextureBasisUExtension( parser );
  37035. } );
  37036. this.register( function ( parser ) {
  37037. return new GLTFTextureWebPExtension( parser );
  37038. } );
  37039. this.register( function ( parser ) {
  37040. return new GLTFMaterialsTransmissionExtension( parser );
  37041. } );
  37042. this.register( function ( parser ) {
  37043. return new GLTFLightsExtension( parser );
  37044. } );
  37045. this.register( function ( parser ) {
  37046. return new GLTFMeshoptCompression( parser );
  37047. } );
  37048. }
  37049. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  37050. constructor: GLTFLoader,
  37051. load: function ( url, onLoad, onProgress, onError ) {
  37052. var scope = this;
  37053. var resourcePath;
  37054. if ( this.resourcePath !== '' ) {
  37055. resourcePath = this.resourcePath;
  37056. } else if ( this.path !== '' ) {
  37057. resourcePath = this.path;
  37058. } else {
  37059. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  37060. }
  37061. // Tells the LoadingManager to track an extra item, which resolves after
  37062. // the model is fully loaded. This means the count of items loaded will
  37063. // be incorrect, but ensures manager.onLoad() does not fire early.
  37064. this.manager.itemStart( url );
  37065. var _onError = function ( e ) {
  37066. if ( onError ) {
  37067. onError( e );
  37068. } else {
  37069. console.error( e );
  37070. }
  37071. scope.manager.itemError( url );
  37072. scope.manager.itemEnd( url );
  37073. };
  37074. var loader = new THREE.FileLoader( this.manager );
  37075. loader.setPath( this.path );
  37076. loader.setResponseType( 'arraybuffer' );
  37077. loader.setRequestHeader( this.requestHeader );
  37078. loader.setWithCredentials( this.withCredentials );
  37079. loader.load( url, function ( data ) {
  37080. try {
  37081. scope.parse( data, resourcePath, function ( gltf ) {
  37082. onLoad( gltf );
  37083. scope.manager.itemEnd( url );
  37084. }, _onError );
  37085. } catch ( e ) {
  37086. _onError( e );
  37087. }
  37088. }, onProgress, _onError );
  37089. },
  37090. setDRACOLoader: function ( dracoLoader ) {
  37091. this.dracoLoader = dracoLoader;
  37092. return this;
  37093. },
  37094. setDDSLoader: function ( ddsLoader ) {
  37095. this.ddsLoader = ddsLoader;
  37096. return this;
  37097. },
  37098. setKTX2Loader: function ( ktx2Loader ) {
  37099. this.ktx2Loader = ktx2Loader;
  37100. return this;
  37101. },
  37102. setMeshoptDecoder: function ( meshoptDecoder ) {
  37103. this.meshoptDecoder = meshoptDecoder;
  37104. return this;
  37105. },
  37106. register: function ( callback ) {
  37107. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  37108. this.pluginCallbacks.push( callback );
  37109. }
  37110. return this;
  37111. },
  37112. unregister: function ( callback ) {
  37113. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  37114. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  37115. }
  37116. return this;
  37117. },
  37118. parse: function ( data, path, onLoad, onError ) {
  37119. var content;
  37120. var extensions = {};
  37121. var plugins = {};
  37122. if ( typeof data === 'string' ) {
  37123. content = data;
  37124. } else {
  37125. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  37126. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  37127. try {
  37128. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  37129. } catch ( error ) {
  37130. if ( onError ) onError( error );
  37131. return;
  37132. }
  37133. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  37134. } else {
  37135. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  37136. }
  37137. }
  37138. var json = JSON.parse( content );
  37139. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  37140. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  37141. return;
  37142. }
  37143. var parser = new GLTFParser( json, {
  37144. path: path || this.resourcePath || '',
  37145. crossOrigin: this.crossOrigin,
  37146. manager: this.manager,
  37147. ktx2Loader: this.ktx2Loader,
  37148. meshoptDecoder: this.meshoptDecoder
  37149. } );
  37150. parser.fileLoader.setRequestHeader( this.requestHeader );
  37151. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  37152. var plugin = this.pluginCallbacks[ i ]( parser );
  37153. plugins[ plugin.name ] = plugin;
  37154. // Workaround to avoid determining as unknown extension
  37155. // in addUnknownExtensionsToUserData().
  37156. // Remove this workaround if we move all the existing
  37157. // extension handlers to plugin system
  37158. extensions[ plugin.name ] = true;
  37159. }
  37160. if ( json.extensionsUsed ) {
  37161. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  37162. var extensionName = json.extensionsUsed[ i ];
  37163. var extensionsRequired = json.extensionsRequired || [];
  37164. switch ( extensionName ) {
  37165. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  37166. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  37167. break;
  37168. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  37169. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  37170. break;
  37171. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  37172. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  37173. break;
  37174. case EXTENSIONS.MSFT_TEXTURE_DDS:
  37175. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  37176. break;
  37177. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  37178. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  37179. break;
  37180. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  37181. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  37182. break;
  37183. default:
  37184. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  37185. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  37186. }
  37187. }
  37188. }
  37189. }
  37190. parser.setExtensions( extensions );
  37191. parser.setPlugins( plugins );
  37192. parser.parse( onLoad, onError );
  37193. }
  37194. } );
  37195. /* GLTFREGISTRY */
  37196. function GLTFRegistry() {
  37197. var objects = {};
  37198. return {
  37199. get: function ( key ) {
  37200. return objects[ key ];
  37201. },
  37202. add: function ( key, object ) {
  37203. objects[ key ] = object;
  37204. },
  37205. remove: function ( key ) {
  37206. delete objects[ key ];
  37207. },
  37208. removeAll: function () {
  37209. objects = {};
  37210. }
  37211. };
  37212. }
  37213. /*********************************/
  37214. /********** EXTENSIONS ***********/
  37215. /*********************************/
  37216. var EXTENSIONS = {
  37217. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  37218. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  37219. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  37220. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  37221. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  37222. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  37223. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  37224. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  37225. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  37226. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  37227. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  37228. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  37229. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  37230. };
  37231. /**
  37232. * DDS Texture Extension
  37233. *
  37234. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  37235. *
  37236. */
  37237. function GLTFTextureDDSExtension( ddsLoader ) {
  37238. if ( ! ddsLoader ) {
  37239. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  37240. }
  37241. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  37242. this.ddsLoader = ddsLoader;
  37243. }
  37244. /**
  37245. * Punctual Lights Extension
  37246. *
  37247. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  37248. */
  37249. function GLTFLightsExtension( parser ) {
  37250. this.parser = parser;
  37251. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  37252. // Object3D instance caches
  37253. this.cache = { refs: {}, uses: {} };
  37254. }
  37255. GLTFLightsExtension.prototype._markDefs = function () {
  37256. var parser = this.parser;
  37257. var nodeDefs = this.parser.json.nodes || [];
  37258. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37259. var nodeDef = nodeDefs[ nodeIndex ];
  37260. if ( nodeDef.extensions
  37261. && nodeDef.extensions[ this.name ]
  37262. && nodeDef.extensions[ this.name ].light !== undefined ) {
  37263. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  37264. }
  37265. }
  37266. };
  37267. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  37268. var parser = this.parser;
  37269. var cacheKey = 'light:' + lightIndex;
  37270. var dependency = parser.cache.get( cacheKey );
  37271. if ( dependency ) return dependency;
  37272. var json = parser.json;
  37273. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  37274. var lightDefs = extensions.lights || [];
  37275. var lightDef = lightDefs[ lightIndex ];
  37276. var lightNode;
  37277. var color = new THREE.Color( 0xffffff );
  37278. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  37279. var range = lightDef.range !== undefined ? lightDef.range : 0;
  37280. switch ( lightDef.type ) {
  37281. case 'directional':
  37282. lightNode = new THREE.DirectionalLight( color );
  37283. lightNode.target.position.set( 0, 0, - 1 );
  37284. lightNode.add( lightNode.target );
  37285. break;
  37286. case 'point':
  37287. lightNode = new THREE.PointLight( color );
  37288. lightNode.distance = range;
  37289. break;
  37290. case 'spot':
  37291. lightNode = new THREE.SpotLight( color );
  37292. lightNode.distance = range;
  37293. // Handle spotlight properties.
  37294. lightDef.spot = lightDef.spot || {};
  37295. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  37296. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  37297. lightNode.angle = lightDef.spot.outerConeAngle;
  37298. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  37299. lightNode.target.position.set( 0, 0, - 1 );
  37300. lightNode.add( lightNode.target );
  37301. break;
  37302. default:
  37303. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  37304. }
  37305. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  37306. // here, because node-level parsing will only override position if explicitly specified.
  37307. lightNode.position.set( 0, 0, 0 );
  37308. lightNode.decay = 2;
  37309. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  37310. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  37311. dependency = Promise.resolve( lightNode );
  37312. parser.cache.add( cacheKey, dependency );
  37313. return dependency;
  37314. };
  37315. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  37316. var self = this;
  37317. var parser = this.parser;
  37318. var json = parser.json;
  37319. var nodeDef = json.nodes[ nodeIndex ];
  37320. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  37321. var lightIndex = lightDef.light;
  37322. if ( lightIndex === undefined ) return null;
  37323. return this._loadLight( lightIndex ).then( function ( light ) {
  37324. return parser._getNodeRef( self.cache, lightIndex, light );
  37325. } );
  37326. };
  37327. /**
  37328. * Unlit Materials Extension
  37329. *
  37330. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  37331. */
  37332. function GLTFMaterialsUnlitExtension() {
  37333. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  37334. }
  37335. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  37336. return THREE.MeshBasicMaterial;
  37337. };
  37338. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  37339. var pending = [];
  37340. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37341. materialParams.opacity = 1.0;
  37342. var metallicRoughness = materialDef.pbrMetallicRoughness;
  37343. if ( metallicRoughness ) {
  37344. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37345. var array = metallicRoughness.baseColorFactor;
  37346. materialParams.color.fromArray( array );
  37347. materialParams.opacity = array[ 3 ];
  37348. }
  37349. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37350. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37351. }
  37352. }
  37353. return Promise.all( pending );
  37354. };
  37355. /**
  37356. * Clearcoat Materials Extension
  37357. *
  37358. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  37359. */
  37360. function GLTFMaterialsClearcoatExtension( parser ) {
  37361. this.parser = parser;
  37362. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  37363. }
  37364. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  37365. var parser = this.parser;
  37366. var materialDef = parser.json.materials[ materialIndex ];
  37367. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  37368. return THREE.MeshPhysicalMaterial;
  37369. };
  37370. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37371. var parser = this.parser;
  37372. var materialDef = parser.json.materials[ materialIndex ];
  37373. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37374. return Promise.resolve();
  37375. }
  37376. var pending = [];
  37377. var extension = materialDef.extensions[ this.name ];
  37378. if ( extension.clearcoatFactor !== undefined ) {
  37379. materialParams.clearcoat = extension.clearcoatFactor;
  37380. }
  37381. if ( extension.clearcoatTexture !== undefined ) {
  37382. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  37383. }
  37384. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  37385. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  37386. }
  37387. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  37388. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  37389. }
  37390. if ( extension.clearcoatNormalTexture !== undefined ) {
  37391. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  37392. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  37393. var scale = extension.clearcoatNormalTexture.scale;
  37394. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  37395. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, -scale );
  37396. }
  37397. }
  37398. return Promise.all( pending );
  37399. };
  37400. /**
  37401. * Transmission Materials Extension
  37402. *
  37403. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  37404. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  37405. */
  37406. function GLTFMaterialsTransmissionExtension( parser ) {
  37407. this.parser = parser;
  37408. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  37409. }
  37410. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  37411. var parser = this.parser;
  37412. var materialDef = parser.json.materials[ materialIndex ];
  37413. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  37414. return THREE.MeshPhysicalMaterial;
  37415. };
  37416. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37417. var parser = this.parser;
  37418. var materialDef = parser.json.materials[ materialIndex ];
  37419. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37420. return Promise.resolve();
  37421. }
  37422. var pending = [];
  37423. var extension = materialDef.extensions[ this.name ];
  37424. if ( extension.transmissionFactor !== undefined ) {
  37425. materialParams.transmission = extension.transmissionFactor;
  37426. }
  37427. if ( extension.transmissionTexture !== undefined ) {
  37428. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  37429. }
  37430. return Promise.all( pending );
  37431. };
  37432. /**
  37433. * BasisU Texture Extension
  37434. *
  37435. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  37436. */
  37437. function GLTFTextureBasisUExtension( parser ) {
  37438. this.parser = parser;
  37439. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  37440. }
  37441. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  37442. var parser = this.parser;
  37443. var json = parser.json;
  37444. var textureDef = json.textures[ textureIndex ];
  37445. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  37446. return null;
  37447. }
  37448. var extension = textureDef.extensions[ this.name ];
  37449. var source = json.images[ extension.source ];
  37450. var loader = parser.options.ktx2Loader;
  37451. if ( ! loader ) {
  37452. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  37453. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  37454. } else {
  37455. // Assumes that the extension is optional and that a fallback texture is present
  37456. return null;
  37457. }
  37458. }
  37459. return parser.loadTextureImage( textureIndex, source, loader );
  37460. };
  37461. /**
  37462. * WebP Texture Extension
  37463. *
  37464. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  37465. */
  37466. function GLTFTextureWebPExtension( parser ) {
  37467. this.parser = parser;
  37468. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  37469. this.isSupported = null;
  37470. }
  37471. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  37472. var name = this.name;
  37473. var parser = this.parser;
  37474. var json = parser.json;
  37475. var textureDef = json.textures[ textureIndex ];
  37476. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  37477. return null;
  37478. }
  37479. var extension = textureDef.extensions[ name ];
  37480. var source = json.images[ extension.source ];
  37481. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  37482. return this.detectSupport().then( function ( isSupported ) {
  37483. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  37484. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  37485. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  37486. }
  37487. // Fall back to PNG or JPEG.
  37488. return parser.loadTexture( textureIndex );
  37489. } );
  37490. };
  37491. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  37492. if ( ! this.isSupported ) {
  37493. this.isSupported = new Promise( function ( resolve ) {
  37494. var image = new Image();
  37495. // Lossy test image. Support for lossy images doesn't guarantee support for all
  37496. // WebP images, unfortunately.
  37497. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  37498. image.onload = image.onerror = function () {
  37499. resolve( image.height === 1 );
  37500. };
  37501. } );
  37502. }
  37503. return this.isSupported;
  37504. };
  37505. /**
  37506. * meshopt BufferView Compression Extension
  37507. *
  37508. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  37509. */
  37510. function GLTFMeshoptCompression( parser ) {
  37511. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  37512. this.parser = parser;
  37513. }
  37514. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  37515. var json = this.parser.json;
  37516. var bufferView = json.bufferViews[ index ];
  37517. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  37518. var extensionDef = bufferView.extensions[ this.name ];
  37519. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  37520. var decoder = this.parser.options.meshoptDecoder;
  37521. if ( ! decoder || ! decoder.supported ) {
  37522. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  37523. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  37524. } else {
  37525. // Assumes that the extension is optional and that fallback buffer data is present
  37526. return null;
  37527. }
  37528. }
  37529. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  37530. var byteOffset = extensionDef.byteOffset || 0;
  37531. var byteLength = extensionDef.byteLength || 0;
  37532. var count = extensionDef.count;
  37533. var stride = extensionDef.byteStride;
  37534. var result = new ArrayBuffer( count * stride );
  37535. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  37536. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  37537. return result;
  37538. } );
  37539. } else {
  37540. return null;
  37541. }
  37542. };
  37543. /* BINARY EXTENSION */
  37544. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  37545. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  37546. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  37547. function GLTFBinaryExtension( data ) {
  37548. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  37549. this.content = null;
  37550. this.body = null;
  37551. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  37552. this.header = {
  37553. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  37554. version: headerView.getUint32( 4, true ),
  37555. length: headerView.getUint32( 8, true )
  37556. };
  37557. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  37558. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  37559. } else if ( this.header.version < 2.0 ) {
  37560. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  37561. }
  37562. var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  37563. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  37564. var chunkIndex = 0;
  37565. while ( chunkIndex < chunkContentsLength ) {
  37566. var chunkLength = chunkView.getUint32( chunkIndex, true );
  37567. chunkIndex += 4;
  37568. var chunkType = chunkView.getUint32( chunkIndex, true );
  37569. chunkIndex += 4;
  37570. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  37571. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  37572. this.content = THREE.LoaderUtils.decodeText( contentArray );
  37573. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  37574. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  37575. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  37576. }
  37577. // Clients must ignore chunks with unknown types.
  37578. chunkIndex += chunkLength;
  37579. }
  37580. if ( this.content === null ) {
  37581. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  37582. }
  37583. }
  37584. /**
  37585. * DRACO Mesh Compression Extension
  37586. *
  37587. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  37588. */
  37589. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  37590. if ( ! dracoLoader ) {
  37591. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  37592. }
  37593. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  37594. this.json = json;
  37595. this.dracoLoader = dracoLoader;
  37596. this.dracoLoader.preload();
  37597. }
  37598. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  37599. var json = this.json;
  37600. var dracoLoader = this.dracoLoader;
  37601. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  37602. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  37603. var threeAttributeMap = {};
  37604. var attributeNormalizedMap = {};
  37605. var attributeTypeMap = {};
  37606. for ( var attributeName in gltfAttributeMap ) {
  37607. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37608. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  37609. }
  37610. for ( attributeName in primitive.attributes ) {
  37611. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37612. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  37613. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  37614. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  37615. attributeTypeMap[ threeAttributeName ] = componentType;
  37616. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  37617. }
  37618. }
  37619. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  37620. return new Promise( function ( resolve ) {
  37621. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  37622. for ( var attributeName in geometry.attributes ) {
  37623. var attribute = geometry.attributes[ attributeName ];
  37624. var normalized = attributeNormalizedMap[ attributeName ];
  37625. if ( normalized !== undefined ) attribute.normalized = normalized;
  37626. }
  37627. resolve( geometry );
  37628. }, threeAttributeMap, attributeTypeMap );
  37629. } );
  37630. } );
  37631. };
  37632. /**
  37633. * Texture Transform Extension
  37634. *
  37635. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  37636. */
  37637. function GLTFTextureTransformExtension() {
  37638. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  37639. }
  37640. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  37641. texture = texture.clone();
  37642. if ( transform.offset !== undefined ) {
  37643. texture.offset.fromArray( transform.offset );
  37644. }
  37645. if ( transform.rotation !== undefined ) {
  37646. texture.rotation = transform.rotation;
  37647. }
  37648. if ( transform.scale !== undefined ) {
  37649. texture.repeat.fromArray( transform.scale );
  37650. }
  37651. if ( transform.texCoord !== undefined ) {
  37652. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  37653. }
  37654. texture.needsUpdate = true;
  37655. return texture;
  37656. };
  37657. /**
  37658. * Specular-Glossiness Extension
  37659. *
  37660. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  37661. */
  37662. /**
  37663. * A sub class of THREE.StandardMaterial with some of the functionality
  37664. * changed via the `onBeforeCompile` callback
  37665. * @pailhead
  37666. */
  37667. function GLTFMeshStandardSGMaterial( params ) {
  37668. THREE.MeshStandardMaterial.call( this );
  37669. this.isGLTFSpecularGlossinessMaterial = true;
  37670. //various chunks that need replacing
  37671. var specularMapParsFragmentChunk = [
  37672. '#ifdef USE_SPECULARMAP',
  37673. ' uniform sampler2D specularMap;',
  37674. '#endif'
  37675. ].join( '\n' );
  37676. var glossinessMapParsFragmentChunk = [
  37677. '#ifdef USE_GLOSSINESSMAP',
  37678. ' uniform sampler2D glossinessMap;',
  37679. '#endif'
  37680. ].join( '\n' );
  37681. var specularMapFragmentChunk = [
  37682. 'vec3 specularFactor = specular;',
  37683. '#ifdef USE_SPECULARMAP',
  37684. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  37685. ' texelSpecular = sRGBToLinear( texelSpecular );',
  37686. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37687. ' specularFactor *= texelSpecular.rgb;',
  37688. '#endif'
  37689. ].join( '\n' );
  37690. var glossinessMapFragmentChunk = [
  37691. 'float glossinessFactor = glossiness;',
  37692. '#ifdef USE_GLOSSINESSMAP',
  37693. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  37694. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37695. ' glossinessFactor *= texelGlossiness.a;',
  37696. '#endif'
  37697. ].join( '\n' );
  37698. var lightPhysicalFragmentChunk = [
  37699. 'PhysicalMaterial material;',
  37700. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  37701. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  37702. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  37703. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  37704. 'material.specularRoughness += geometryRoughness;',
  37705. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  37706. 'material.specularColor = specularFactor;',
  37707. ].join( '\n' );
  37708. var uniforms = {
  37709. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  37710. glossiness: { value: 1 },
  37711. specularMap: { value: null },
  37712. glossinessMap: { value: null }
  37713. };
  37714. this._extraUniforms = uniforms;
  37715. this.onBeforeCompile = function ( shader ) {
  37716. for ( var uniformName in uniforms ) {
  37717. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  37718. }
  37719. shader.fragmentShader = shader.fragmentShader
  37720. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  37721. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  37722. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  37723. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  37724. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  37725. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  37726. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  37727. };
  37728. Object.defineProperties( this, {
  37729. specular: {
  37730. get: function () {
  37731. return uniforms.specular.value;
  37732. },
  37733. set: function ( v ) {
  37734. uniforms.specular.value = v;
  37735. }
  37736. },
  37737. specularMap: {
  37738. get: function () {
  37739. return uniforms.specularMap.value;
  37740. },
  37741. set: function ( v ) {
  37742. uniforms.specularMap.value = v;
  37743. if ( v ) {
  37744. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  37745. } else {
  37746. delete this.defines.USE_SPECULARMAP;
  37747. }
  37748. }
  37749. },
  37750. glossiness: {
  37751. get: function () {
  37752. return uniforms.glossiness.value;
  37753. },
  37754. set: function ( v ) {
  37755. uniforms.glossiness.value = v;
  37756. }
  37757. },
  37758. glossinessMap: {
  37759. get: function () {
  37760. return uniforms.glossinessMap.value;
  37761. },
  37762. set: function ( v ) {
  37763. uniforms.glossinessMap.value = v;
  37764. if ( v ) {
  37765. this.defines.USE_GLOSSINESSMAP = '';
  37766. this.defines.USE_UV = '';
  37767. } else {
  37768. delete this.defines.USE_GLOSSINESSMAP;
  37769. delete this.defines.USE_UV;
  37770. }
  37771. }
  37772. }
  37773. } );
  37774. delete this.metalness;
  37775. delete this.roughness;
  37776. delete this.metalnessMap;
  37777. delete this.roughnessMap;
  37778. this.setValues( params );
  37779. }
  37780. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  37781. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  37782. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  37783. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  37784. this.specularMap = source.specularMap;
  37785. this.specular.copy( source.specular );
  37786. this.glossinessMap = source.glossinessMap;
  37787. this.glossiness = source.glossiness;
  37788. delete this.metalness;
  37789. delete this.roughness;
  37790. delete this.metalnessMap;
  37791. delete this.roughnessMap;
  37792. return this;
  37793. };
  37794. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  37795. return {
  37796. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  37797. specularGlossinessParams: [
  37798. 'color',
  37799. 'map',
  37800. 'lightMap',
  37801. 'lightMapIntensity',
  37802. 'aoMap',
  37803. 'aoMapIntensity',
  37804. 'emissive',
  37805. 'emissiveIntensity',
  37806. 'emissiveMap',
  37807. 'bumpMap',
  37808. 'bumpScale',
  37809. 'normalMap',
  37810. 'normalMapType',
  37811. 'displacementMap',
  37812. 'displacementScale',
  37813. 'displacementBias',
  37814. 'specularMap',
  37815. 'specular',
  37816. 'glossinessMap',
  37817. 'glossiness',
  37818. 'alphaMap',
  37819. 'envMap',
  37820. 'envMapIntensity',
  37821. 'refractionRatio',
  37822. ],
  37823. getMaterialType: function () {
  37824. return GLTFMeshStandardSGMaterial;
  37825. },
  37826. extendParams: function ( materialParams, materialDef, parser ) {
  37827. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  37828. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37829. materialParams.opacity = 1.0;
  37830. var pending = [];
  37831. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  37832. var array = pbrSpecularGlossiness.diffuseFactor;
  37833. materialParams.color.fromArray( array );
  37834. materialParams.opacity = array[ 3 ];
  37835. }
  37836. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  37837. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  37838. }
  37839. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  37840. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  37841. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  37842. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  37843. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  37844. }
  37845. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  37846. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  37847. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  37848. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  37849. }
  37850. return Promise.all( pending );
  37851. },
  37852. createMaterial: function ( materialParams ) {
  37853. var material = new GLTFMeshStandardSGMaterial( materialParams );
  37854. material.fog = true;
  37855. material.color = materialParams.color;
  37856. material.map = materialParams.map === undefined ? null : materialParams.map;
  37857. material.lightMap = null;
  37858. material.lightMapIntensity = 1.0;
  37859. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  37860. material.aoMapIntensity = 1.0;
  37861. material.emissive = materialParams.emissive;
  37862. material.emissiveIntensity = 1.0;
  37863. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  37864. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  37865. material.bumpScale = 1;
  37866. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  37867. material.normalMapType = THREE.TangentSpaceNormalMap;
  37868. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  37869. material.displacementMap = null;
  37870. material.displacementScale = 1;
  37871. material.displacementBias = 0;
  37872. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  37873. material.specular = materialParams.specular;
  37874. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  37875. material.glossiness = materialParams.glossiness;
  37876. material.alphaMap = null;
  37877. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  37878. material.envMapIntensity = 1.0;
  37879. material.refractionRatio = 0.98;
  37880. return material;
  37881. },
  37882. };
  37883. }
  37884. /**
  37885. * Mesh Quantization Extension
  37886. *
  37887. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  37888. */
  37889. function GLTFMeshQuantizationExtension() {
  37890. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  37891. }
  37892. /*********************************/
  37893. /********** INTERPOLATION ********/
  37894. /*********************************/
  37895. // Spline Interpolation
  37896. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  37897. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  37898. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  37899. }
  37900. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  37901. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  37902. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  37903. // Copies a sample value to the result buffer. See description of glTF
  37904. // CUBICSPLINE values layout in interpolate_() function below.
  37905. var result = this.resultBuffer,
  37906. values = this.sampleValues,
  37907. valueSize = this.valueSize,
  37908. offset = index * valueSize * 3 + valueSize;
  37909. for ( var i = 0; i !== valueSize; i ++ ) {
  37910. result[ i ] = values[ offset + i ];
  37911. }
  37912. return result;
  37913. };
  37914. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37915. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37916. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  37917. var result = this.resultBuffer;
  37918. var values = this.sampleValues;
  37919. var stride = this.valueSize;
  37920. var stride2 = stride * 2;
  37921. var stride3 = stride * 3;
  37922. var td = t1 - t0;
  37923. var p = ( t - t0 ) / td;
  37924. var pp = p * p;
  37925. var ppp = pp * p;
  37926. var offset1 = i1 * stride3;
  37927. var offset0 = offset1 - stride3;
  37928. var s2 = - 2 * ppp + 3 * pp;
  37929. var s3 = ppp - pp;
  37930. var s0 = 1 - s2;
  37931. var s1 = s3 - pp + p;
  37932. // Layout of keyframe output values for CUBICSPLINE animations:
  37933. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  37934. for ( var i = 0; i !== stride; i ++ ) {
  37935. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  37936. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  37937. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  37938. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  37939. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  37940. }
  37941. return result;
  37942. };
  37943. /*********************************/
  37944. /********** INTERNALS ************/
  37945. /*********************************/
  37946. /* CONSTANTS */
  37947. var WEBGL_CONSTANTS = {
  37948. FLOAT: 5126,
  37949. //FLOAT_MAT2: 35674,
  37950. FLOAT_MAT3: 35675,
  37951. FLOAT_MAT4: 35676,
  37952. FLOAT_VEC2: 35664,
  37953. FLOAT_VEC3: 35665,
  37954. FLOAT_VEC4: 35666,
  37955. LINEAR: 9729,
  37956. REPEAT: 10497,
  37957. SAMPLER_2D: 35678,
  37958. POINTS: 0,
  37959. LINES: 1,
  37960. LINE_LOOP: 2,
  37961. LINE_STRIP: 3,
  37962. TRIANGLES: 4,
  37963. TRIANGLE_STRIP: 5,
  37964. TRIANGLE_FAN: 6,
  37965. UNSIGNED_BYTE: 5121,
  37966. UNSIGNED_SHORT: 5123
  37967. };
  37968. var WEBGL_COMPONENT_TYPES = {
  37969. 5120: Int8Array,
  37970. 5121: Uint8Array,
  37971. 5122: Int16Array,
  37972. 5123: Uint16Array,
  37973. 5125: Uint32Array,
  37974. 5126: Float32Array
  37975. };
  37976. var WEBGL_FILTERS = {
  37977. 9728: THREE.NearestFilter,
  37978. 9729: THREE.LinearFilter,
  37979. 9984: THREE.NearestMipmapNearestFilter,
  37980. 9985: THREE.LinearMipmapNearestFilter,
  37981. 9986: THREE.NearestMipmapLinearFilter,
  37982. 9987: THREE.LinearMipmapLinearFilter
  37983. };
  37984. var WEBGL_WRAPPINGS = {
  37985. 33071: THREE.ClampToEdgeWrapping,
  37986. 33648: THREE.MirroredRepeatWrapping,
  37987. 10497: THREE.RepeatWrapping
  37988. };
  37989. var WEBGL_TYPE_SIZES = {
  37990. 'SCALAR': 1,
  37991. 'VEC2': 2,
  37992. 'VEC3': 3,
  37993. 'VEC4': 4,
  37994. 'MAT2': 4,
  37995. 'MAT3': 9,
  37996. 'MAT4': 16
  37997. };
  37998. var ATTRIBUTES = {
  37999. POSITION: 'position',
  38000. NORMAL: 'normal',
  38001. TANGENT: 'tangent',
  38002. TEXCOORD_0: 'uv',
  38003. TEXCOORD_1: 'uv2',
  38004. COLOR_0: 'color',
  38005. WEIGHTS_0: 'skinWeight',
  38006. JOINTS_0: 'skinIndex',
  38007. };
  38008. var PATH_PROPERTIES = {
  38009. scale: 'scale',
  38010. translation: 'position',
  38011. rotation: 'quaternion',
  38012. weights: 'morphTargetInfluences'
  38013. };
  38014. var INTERPOLATION = {
  38015. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  38016. // keyframe track will be initialized with a default interpolation type, then modified.
  38017. LINEAR: THREE.InterpolateLinear,
  38018. STEP: THREE.InterpolateDiscrete
  38019. };
  38020. var ALPHA_MODES = {
  38021. OPAQUE: 'OPAQUE',
  38022. MASK: 'MASK',
  38023. BLEND: 'BLEND'
  38024. };
  38025. /* UTILITY FUNCTIONS */
  38026. function resolveURL( url, path ) {
  38027. // Invalid URL
  38028. if ( typeof url !== 'string' || url === '' ) return '';
  38029. // Host Relative URL
  38030. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  38031. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  38032. }
  38033. // Absolute URL http://,https://,//
  38034. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  38035. // Data URI
  38036. if ( /^data:.*,.*$/i.test( url ) ) return url;
  38037. // Blob URL
  38038. if ( /^blob:.*$/i.test( url ) ) return url;
  38039. // Relative URL
  38040. return path + url;
  38041. }
  38042. /**
  38043. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  38044. */
  38045. function createDefaultMaterial( cache ) {
  38046. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  38047. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  38048. color: 0xFFFFFF,
  38049. emissive: 0x000000,
  38050. metalness: 1,
  38051. roughness: 1,
  38052. transparent: false,
  38053. depthTest: true,
  38054. side: THREE.FrontSide
  38055. } );
  38056. }
  38057. return cache[ 'DefaultMaterial' ];
  38058. }
  38059. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  38060. // Add unknown glTF extensions to an object's userData.
  38061. for ( var name in objectDef.extensions ) {
  38062. if ( knownExtensions[ name ] === undefined ) {
  38063. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  38064. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  38065. }
  38066. }
  38067. }
  38068. /**
  38069. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  38070. * @param {GLTF.definition} gltfDef
  38071. */
  38072. function assignExtrasToUserData( object, gltfDef ) {
  38073. if ( gltfDef.extras !== undefined ) {
  38074. if ( typeof gltfDef.extras === 'object' ) {
  38075. Object.assign( object.userData, gltfDef.extras );
  38076. } else {
  38077. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  38078. }
  38079. }
  38080. }
  38081. /**
  38082. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  38083. *
  38084. * @param {THREE.BufferGeometry} geometry
  38085. * @param {Array<GLTF.Target>} targets
  38086. * @param {GLTFParser} parser
  38087. * @return {Promise<THREE.BufferGeometry>}
  38088. */
  38089. function addMorphTargets( geometry, targets, parser ) {
  38090. var hasMorphPosition = false;
  38091. var hasMorphNormal = false;
  38092. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38093. var target = targets[ i ];
  38094. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  38095. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  38096. if ( hasMorphPosition && hasMorphNormal ) break;
  38097. }
  38098. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  38099. var pendingPositionAccessors = [];
  38100. var pendingNormalAccessors = [];
  38101. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38102. var target = targets[ i ];
  38103. if ( hasMorphPosition ) {
  38104. var pendingAccessor = target.POSITION !== undefined
  38105. ? parser.getDependency( 'accessor', target.POSITION )
  38106. : geometry.attributes.position;
  38107. pendingPositionAccessors.push( pendingAccessor );
  38108. }
  38109. if ( hasMorphNormal ) {
  38110. var pendingAccessor = target.NORMAL !== undefined
  38111. ? parser.getDependency( 'accessor', target.NORMAL )
  38112. : geometry.attributes.normal;
  38113. pendingNormalAccessors.push( pendingAccessor );
  38114. }
  38115. }
  38116. return Promise.all( [
  38117. Promise.all( pendingPositionAccessors ),
  38118. Promise.all( pendingNormalAccessors )
  38119. ] ).then( function ( accessors ) {
  38120. var morphPositions = accessors[ 0 ];
  38121. var morphNormals = accessors[ 1 ];
  38122. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  38123. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  38124. geometry.morphTargetsRelative = true;
  38125. return geometry;
  38126. } );
  38127. }
  38128. /**
  38129. * @param {THREE.Mesh} mesh
  38130. * @param {GLTF.Mesh} meshDef
  38131. */
  38132. function updateMorphTargets( mesh, meshDef ) {
  38133. mesh.updateMorphTargets();
  38134. if ( meshDef.weights !== undefined ) {
  38135. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  38136. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  38137. }
  38138. }
  38139. // .extras has user-defined data, so check that .extras.targetNames is an array.
  38140. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  38141. var targetNames = meshDef.extras.targetNames;
  38142. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  38143. mesh.morphTargetDictionary = {};
  38144. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  38145. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  38146. }
  38147. } else {
  38148. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  38149. }
  38150. }
  38151. }
  38152. function createPrimitiveKey( primitiveDef ) {
  38153. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  38154. var geometryKey;
  38155. if ( dracoExtension ) {
  38156. geometryKey = 'draco:' + dracoExtension.bufferView
  38157. + ':' + dracoExtension.indices
  38158. + ':' + createAttributesKey( dracoExtension.attributes );
  38159. } else {
  38160. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  38161. }
  38162. return geometryKey;
  38163. }
  38164. function createAttributesKey( attributes ) {
  38165. var attributesKey = '';
  38166. var keys = Object.keys( attributes ).sort();
  38167. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  38168. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  38169. }
  38170. return attributesKey;
  38171. }
  38172. /* GLTF PARSER */
  38173. function GLTFParser( json, options ) {
  38174. this.json = json || {};
  38175. this.extensions = {};
  38176. this.plugins = {};
  38177. this.options = options || {};
  38178. // loader object cache
  38179. this.cache = new GLTFRegistry();
  38180. // associations between Three.js objects and glTF elements
  38181. this.associations = new Map();
  38182. // BufferGeometry caching
  38183. this.primitiveCache = {};
  38184. // Object3D instance caches
  38185. this.meshCache = { refs: {}, uses: {} };
  38186. this.cameraCache = { refs: {}, uses: {} };
  38187. this.lightCache = { refs: {}, uses: {} };
  38188. // Track node names, to ensure no duplicates
  38189. this.nodeNamesUsed = {};
  38190. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  38191. // expensive work of uploading a texture to the GPU off the main thread.
  38192. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  38193. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  38194. } else {
  38195. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  38196. }
  38197. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  38198. this.fileLoader = new THREE.FileLoader( this.options.manager );
  38199. this.fileLoader.setResponseType( 'arraybuffer' );
  38200. if ( this.options.crossOrigin === 'use-credentials' ) {
  38201. this.fileLoader.setWithCredentials( true );
  38202. }
  38203. }
  38204. GLTFParser.prototype.setExtensions = function ( extensions ) {
  38205. this.extensions = extensions;
  38206. };
  38207. GLTFParser.prototype.setPlugins = function ( plugins ) {
  38208. this.plugins = plugins;
  38209. };
  38210. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  38211. var parser = this;
  38212. var json = this.json;
  38213. var extensions = this.extensions;
  38214. // Clear the loader cache
  38215. this.cache.removeAll();
  38216. // Mark the special nodes/meshes in json for efficient parse
  38217. this._invokeAll( function ( ext ) {
  38218. return ext._markDefs && ext._markDefs();
  38219. } );
  38220. Promise.all( [
  38221. this.getDependencies( 'scene' ),
  38222. this.getDependencies( 'animation' ),
  38223. this.getDependencies( 'camera' ),
  38224. ] ).then( function ( dependencies ) {
  38225. var result = {
  38226. scene: dependencies[ 0 ][ json.scene || 0 ],
  38227. scenes: dependencies[ 0 ],
  38228. animations: dependencies[ 1 ],
  38229. cameras: dependencies[ 2 ],
  38230. asset: json.asset,
  38231. parser: parser,
  38232. userData: {}
  38233. };
  38234. addUnknownExtensionsToUserData( extensions, result, json );
  38235. assignExtrasToUserData( result, json );
  38236. onLoad( result );
  38237. } ).catch( onError );
  38238. };
  38239. /**
  38240. * Marks the special nodes/meshes in json for efficient parse.
  38241. */
  38242. GLTFParser.prototype._markDefs = function () {
  38243. var nodeDefs = this.json.nodes || [];
  38244. var skinDefs = this.json.skins || [];
  38245. var meshDefs = this.json.meshes || [];
  38246. // Nothing in the node definition indicates whether it is a Bone or an
  38247. // Object3D. Use the skins' joint references to mark bones.
  38248. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  38249. var joints = skinDefs[ skinIndex ].joints;
  38250. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  38251. nodeDefs[ joints[ i ] ].isBone = true;
  38252. }
  38253. }
  38254. // Iterate over all nodes, marking references to shared resources,
  38255. // as well as skeleton joints.
  38256. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  38257. var nodeDef = nodeDefs[ nodeIndex ];
  38258. if ( nodeDef.mesh !== undefined ) {
  38259. this._addNodeRef( this.meshCache, nodeDef.mesh );
  38260. // Nothing in the mesh definition indicates whether it is
  38261. // a SkinnedMesh or Mesh. Use the node's mesh reference
  38262. // to mark SkinnedMesh if node has skin.
  38263. if ( nodeDef.skin !== undefined ) {
  38264. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  38265. }
  38266. }
  38267. if ( nodeDef.camera !== undefined ) {
  38268. this._addNodeRef( this.cameraCache, nodeDef.camera );
  38269. }
  38270. }
  38271. };
  38272. /**
  38273. * Counts references to shared node / Object3D resources. These resources
  38274. * can be reused, or "instantiated", at multiple nodes in the scene
  38275. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  38276. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  38277. * Textures) can be reused directly and are not marked here.
  38278. *
  38279. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  38280. */
  38281. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  38282. if ( index === undefined ) return;
  38283. if ( cache.refs[ index ] === undefined ) {
  38284. cache.refs[ index ] = cache.uses[ index ] = 0;
  38285. }
  38286. cache.refs[ index ] ++;
  38287. };
  38288. /** Returns a reference to a shared resource, cloning it if necessary. */
  38289. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  38290. if ( cache.refs[ index ] <= 1 ) return object;
  38291. var ref = object.clone();
  38292. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  38293. return ref;
  38294. };
  38295. GLTFParser.prototype._invokeOne = function ( func ) {
  38296. var extensions = Object.values( this.plugins );
  38297. extensions.push( this );
  38298. for ( var i = 0; i < extensions.length; i ++ ) {
  38299. var result = func( extensions[ i ] );
  38300. if ( result ) return result;
  38301. }
  38302. };
  38303. GLTFParser.prototype._invokeAll = function ( func ) {
  38304. var extensions = Object.values( this.plugins );
  38305. extensions.unshift( this );
  38306. var pending = [];
  38307. for ( var i = 0; i < extensions.length; i ++ ) {
  38308. var result = func( extensions[ i ] );
  38309. if ( result ) pending.push( result );
  38310. }
  38311. return pending;
  38312. };
  38313. /**
  38314. * Requests the specified dependency asynchronously, with caching.
  38315. * @param {string} type
  38316. * @param {number} index
  38317. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  38318. */
  38319. GLTFParser.prototype.getDependency = function ( type, index ) {
  38320. var cacheKey = type + ':' + index;
  38321. var dependency = this.cache.get( cacheKey );
  38322. if ( ! dependency ) {
  38323. switch ( type ) {
  38324. case 'scene':
  38325. dependency = this.loadScene( index );
  38326. break;
  38327. case 'node':
  38328. dependency = this.loadNode( index );
  38329. break;
  38330. case 'mesh':
  38331. dependency = this._invokeOne( function ( ext ) {
  38332. return ext.loadMesh && ext.loadMesh( index );
  38333. } );
  38334. break;
  38335. case 'accessor':
  38336. dependency = this.loadAccessor( index );
  38337. break;
  38338. case 'bufferView':
  38339. dependency = this._invokeOne( function ( ext ) {
  38340. return ext.loadBufferView && ext.loadBufferView( index );
  38341. } );
  38342. break;
  38343. case 'buffer':
  38344. dependency = this.loadBuffer( index );
  38345. break;
  38346. case 'material':
  38347. dependency = this._invokeOne( function ( ext ) {
  38348. return ext.loadMaterial && ext.loadMaterial( index );
  38349. } );
  38350. break;
  38351. case 'texture':
  38352. dependency = this._invokeOne( function ( ext ) {
  38353. return ext.loadTexture && ext.loadTexture( index );
  38354. } );
  38355. break;
  38356. case 'skin':
  38357. dependency = this.loadSkin( index );
  38358. break;
  38359. case 'animation':
  38360. dependency = this.loadAnimation( index );
  38361. break;
  38362. case 'camera':
  38363. dependency = this.loadCamera( index );
  38364. break;
  38365. default:
  38366. throw new Error( 'Unknown type: ' + type );
  38367. }
  38368. this.cache.add( cacheKey, dependency );
  38369. }
  38370. return dependency;
  38371. };
  38372. /**
  38373. * Requests all dependencies of the specified type asynchronously, with caching.
  38374. * @param {string} type
  38375. * @return {Promise<Array<Object>>}
  38376. */
  38377. GLTFParser.prototype.getDependencies = function ( type ) {
  38378. var dependencies = this.cache.get( type );
  38379. if ( ! dependencies ) {
  38380. var parser = this;
  38381. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  38382. dependencies = Promise.all( defs.map( function ( def, index ) {
  38383. return parser.getDependency( type, index );
  38384. } ) );
  38385. this.cache.add( type, dependencies );
  38386. }
  38387. return dependencies;
  38388. };
  38389. /**
  38390. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38391. * @param {number} bufferIndex
  38392. * @return {Promise<ArrayBuffer>}
  38393. */
  38394. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  38395. var bufferDef = this.json.buffers[ bufferIndex ];
  38396. var loader = this.fileLoader;
  38397. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  38398. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  38399. }
  38400. // If present, GLB container is required to be the first buffer.
  38401. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  38402. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  38403. }
  38404. var options = this.options;
  38405. return new Promise( function ( resolve, reject ) {
  38406. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  38407. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  38408. } );
  38409. } );
  38410. };
  38411. /**
  38412. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38413. * @param {number} bufferViewIndex
  38414. * @return {Promise<ArrayBuffer>}
  38415. */
  38416. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  38417. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  38418. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  38419. var byteLength = bufferViewDef.byteLength || 0;
  38420. var byteOffset = bufferViewDef.byteOffset || 0;
  38421. return buffer.slice( byteOffset, byteOffset + byteLength );
  38422. } );
  38423. };
  38424. /**
  38425. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  38426. * @param {number} accessorIndex
  38427. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  38428. */
  38429. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  38430. var parser = this;
  38431. var json = this.json;
  38432. var accessorDef = this.json.accessors[ accessorIndex ];
  38433. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  38434. // Ignore empty accessors, which may be used to declare runtime
  38435. // information about attributes coming from another source (e.g. Draco
  38436. // compression extension).
  38437. return Promise.resolve( null );
  38438. }
  38439. var pendingBufferViews = [];
  38440. if ( accessorDef.bufferView !== undefined ) {
  38441. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  38442. } else {
  38443. pendingBufferViews.push( null );
  38444. }
  38445. if ( accessorDef.sparse !== undefined ) {
  38446. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  38447. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  38448. }
  38449. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  38450. var bufferView = bufferViews[ 0 ];
  38451. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  38452. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  38453. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  38454. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  38455. var itemBytes = elementBytes * itemSize;
  38456. var byteOffset = accessorDef.byteOffset || 0;
  38457. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  38458. var normalized = accessorDef.normalized === true;
  38459. var array, bufferAttribute;
  38460. // The buffer is not interleaved if the stride is the item size in bytes.
  38461. if ( byteStride && byteStride !== itemBytes ) {
  38462. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  38463. // This makes sure that IBA.count reflects accessor.count properly
  38464. var ibSlice = Math.floor( byteOffset / byteStride );
  38465. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  38466. var ib = parser.cache.get( ibCacheKey );
  38467. if ( ! ib ) {
  38468. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  38469. // Integer parameters to IB/IBA are in array elements, not bytes.
  38470. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  38471. parser.cache.add( ibCacheKey, ib );
  38472. }
  38473. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  38474. } else {
  38475. if ( bufferView === null ) {
  38476. array = new TypedArray( accessorDef.count * itemSize );
  38477. } else {
  38478. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  38479. }
  38480. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  38481. }
  38482. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  38483. if ( accessorDef.sparse !== undefined ) {
  38484. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  38485. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  38486. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  38487. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  38488. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  38489. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  38490. if ( bufferView !== null ) {
  38491. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  38492. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  38493. }
  38494. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  38495. var index = sparseIndices[ i ];
  38496. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  38497. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  38498. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  38499. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  38500. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  38501. }
  38502. }
  38503. return bufferAttribute;
  38504. } );
  38505. };
  38506. /**
  38507. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  38508. * @param {number} textureIndex
  38509. * @return {Promise<THREE.Texture>}
  38510. */
  38511. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  38512. var parser = this;
  38513. var json = this.json;
  38514. var options = this.options;
  38515. var textureDef = json.textures[ textureIndex ];
  38516. var textureExtensions = textureDef.extensions || {};
  38517. var source;
  38518. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  38519. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  38520. } else {
  38521. source = json.images[ textureDef.source ];
  38522. }
  38523. var loader;
  38524. if ( source.uri ) {
  38525. loader = options.manager.getHandler( source.uri );
  38526. }
  38527. if ( ! loader ) {
  38528. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  38529. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  38530. : this.textureLoader;
  38531. }
  38532. return this.loadTextureImage( textureIndex, source, loader );
  38533. };
  38534. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  38535. var parser = this;
  38536. var json = this.json;
  38537. var options = this.options;
  38538. var textureDef = json.textures[ textureIndex ];
  38539. var URL = self.URL || self.webkitURL;
  38540. var sourceURI = source.uri;
  38541. var isObjectURL = false;
  38542. var hasAlpha = true;
  38543. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  38544. if ( source.bufferView !== undefined ) {
  38545. // Load binary image data from bufferView, if provided.
  38546. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  38547. if ( source.mimeType === 'image/png' ) {
  38548. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  38549. // alpha channel. This check is conservative — the image could have an alpha
  38550. // channel with all values == 1, and the indexed type (colorType == 3) only
  38551. // sometimes contains alpha.
  38552. //
  38553. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  38554. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  38555. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  38556. }
  38557. isObjectURL = true;
  38558. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  38559. sourceURI = URL.createObjectURL( blob );
  38560. return sourceURI;
  38561. } );
  38562. }
  38563. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  38564. return new Promise( function ( resolve, reject ) {
  38565. var onLoad = resolve;
  38566. if ( loader.isImageBitmapLoader === true ) {
  38567. onLoad = function ( imageBitmap ) {
  38568. resolve( new THREE.CanvasTexture( imageBitmap ) );
  38569. };
  38570. }
  38571. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  38572. } );
  38573. } ).then( function ( texture ) {
  38574. // Clean up resources and configure Texture.
  38575. if ( isObjectURL === true ) {
  38576. URL.revokeObjectURL( sourceURI );
  38577. }
  38578. texture.flipY = false;
  38579. if ( textureDef.name ) texture.name = textureDef.name;
  38580. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  38581. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  38582. var samplers = json.samplers || {};
  38583. var sampler = samplers[ textureDef.sampler ] || {};
  38584. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  38585. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  38586. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  38587. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  38588. parser.associations.set( texture, {
  38589. type: 'textures',
  38590. index: textureIndex
  38591. } );
  38592. return texture;
  38593. } );
  38594. };
  38595. /**
  38596. * Asynchronously assigns a texture to the given material parameters.
  38597. * @param {Object} materialParams
  38598. * @param {string} mapName
  38599. * @param {Object} mapDef
  38600. * @return {Promise}
  38601. */
  38602. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  38603. var parser = this;
  38604. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  38605. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  38606. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  38607. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  38608. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  38609. }
  38610. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  38611. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  38612. if ( transform ) {
  38613. var gltfReference = parser.associations.get( texture );
  38614. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  38615. parser.associations.set( texture, gltfReference );
  38616. }
  38617. }
  38618. materialParams[ mapName ] = texture;
  38619. } );
  38620. };
  38621. /**
  38622. * Assigns final material to a Mesh, Line, or Points instance. The instance
  38623. * already has a material (generated from the glTF material options alone)
  38624. * but reuse of the same glTF material may require multiple threejs materials
  38625. * to accomodate different primitive types, defines, etc. New materials will
  38626. * be created if necessary, and reused from a cache.
  38627. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  38628. */
  38629. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  38630. var geometry = mesh.geometry;
  38631. var material = mesh.material;
  38632. var useVertexTangents = geometry.attributes.tangent !== undefined;
  38633. var useVertexColors = geometry.attributes.color !== undefined;
  38634. var useFlatShading = geometry.attributes.normal === undefined;
  38635. var useSkinning = mesh.isSkinnedMesh === true;
  38636. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  38637. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  38638. if ( mesh.isPoints ) {
  38639. var cacheKey = 'PointsMaterial:' + material.uuid;
  38640. var pointsMaterial = this.cache.get( cacheKey );
  38641. if ( ! pointsMaterial ) {
  38642. pointsMaterial = new THREE.PointsMaterial();
  38643. THREE.Material.prototype.copy.call( pointsMaterial, material );
  38644. pointsMaterial.color.copy( material.color );
  38645. pointsMaterial.map = material.map;
  38646. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  38647. this.cache.add( cacheKey, pointsMaterial );
  38648. }
  38649. material = pointsMaterial;
  38650. } else if ( mesh.isLine ) {
  38651. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  38652. var lineMaterial = this.cache.get( cacheKey );
  38653. if ( ! lineMaterial ) {
  38654. lineMaterial = new THREE.LineBasicMaterial();
  38655. THREE.Material.prototype.copy.call( lineMaterial, material );
  38656. lineMaterial.color.copy( material.color );
  38657. this.cache.add( cacheKey, lineMaterial );
  38658. }
  38659. material = lineMaterial;
  38660. }
  38661. // Clone the material if it will be modified
  38662. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  38663. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  38664. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  38665. if ( useSkinning ) cacheKey += 'skinning:';
  38666. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  38667. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  38668. if ( useFlatShading ) cacheKey += 'flat-shading:';
  38669. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  38670. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  38671. var cachedMaterial = this.cache.get( cacheKey );
  38672. if ( ! cachedMaterial ) {
  38673. cachedMaterial = material.clone();
  38674. if ( useSkinning ) cachedMaterial.skinning = true;
  38675. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  38676. if ( useFlatShading ) cachedMaterial.flatShading = true;
  38677. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  38678. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  38679. if ( useVertexTangents ) {
  38680. cachedMaterial.vertexTangents = true;
  38681. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38682. if ( material.normalScale ) material.normalScale.y *= -1;
  38683. if ( material.clearcoatNormalScale ) material.clearcoatNormalScale.y *= -1;
  38684. }
  38685. this.cache.add( cacheKey, cachedMaterial );
  38686. this.associations.set( cachedMaterial, this.associations.get( material ) );
  38687. }
  38688. material = cachedMaterial;
  38689. }
  38690. // workarounds for mesh and geometry
  38691. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  38692. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  38693. }
  38694. mesh.material = material;
  38695. };
  38696. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  38697. return THREE.MeshStandardMaterial;
  38698. };
  38699. /**
  38700. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  38701. * @param {number} materialIndex
  38702. * @return {Promise<THREE.Material>}
  38703. */
  38704. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  38705. var parser = this;
  38706. var json = this.json;
  38707. var extensions = this.extensions;
  38708. var materialDef = json.materials[ materialIndex ];
  38709. var materialType;
  38710. var materialParams = {};
  38711. var materialExtensions = materialDef.extensions || {};
  38712. var pending = [];
  38713. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  38714. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  38715. materialType = sgExtension.getMaterialType();
  38716. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  38717. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  38718. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  38719. materialType = kmuExtension.getMaterialType();
  38720. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  38721. } else {
  38722. // Specification:
  38723. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  38724. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  38725. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38726. materialParams.opacity = 1.0;
  38727. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  38728. var array = metallicRoughness.baseColorFactor;
  38729. materialParams.color.fromArray( array );
  38730. materialParams.opacity = array[ 3 ];
  38731. }
  38732. if ( metallicRoughness.baseColorTexture !== undefined ) {
  38733. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  38734. }
  38735. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  38736. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  38737. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  38738. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38739. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38740. }
  38741. materialType = this._invokeOne( function ( ext ) {
  38742. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  38743. } );
  38744. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  38745. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  38746. } ) ) );
  38747. }
  38748. if ( materialDef.doubleSided === true ) {
  38749. materialParams.side = THREE.DoubleSide;
  38750. }
  38751. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  38752. if ( alphaMode === ALPHA_MODES.BLEND ) {
  38753. materialParams.transparent = true;
  38754. // See: https://github.com/mrdoob/three.js/issues/17706
  38755. materialParams.depthWrite = false;
  38756. } else {
  38757. materialParams.transparent = false;
  38758. if ( alphaMode === ALPHA_MODES.MASK ) {
  38759. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  38760. }
  38761. }
  38762. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38763. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  38764. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38765. materialParams.normalScale = new THREE.Vector2( 1, -1 );
  38766. if ( materialDef.normalTexture.scale !== undefined ) {
  38767. materialParams.normalScale.set( materialDef.normalTexture.scale, -materialDef.normalTexture.scale );
  38768. }
  38769. }
  38770. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38771. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  38772. if ( materialDef.occlusionTexture.strength !== undefined ) {
  38773. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  38774. }
  38775. }
  38776. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38777. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  38778. }
  38779. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38780. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  38781. }
  38782. return Promise.all( pending ).then( function () {
  38783. var material;
  38784. if ( materialType === GLTFMeshStandardSGMaterial ) {
  38785. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  38786. } else {
  38787. material = new materialType( materialParams );
  38788. }
  38789. if ( materialDef.name ) material.name = materialDef.name;
  38790. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  38791. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  38792. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  38793. assignExtrasToUserData( material, materialDef );
  38794. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  38795. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  38796. return material;
  38797. } );
  38798. };
  38799. /** When Object3D instances are targeted by animation, they need unique names. */
  38800. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  38801. var sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
  38802. var name = sanitizedName;
  38803. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  38804. name = sanitizedName + '_' + i;
  38805. }
  38806. this.nodeNamesUsed[ name ] = true;
  38807. return name;
  38808. };
  38809. /**
  38810. * @param {THREE.BufferGeometry} geometry
  38811. * @param {GLTF.Primitive} primitiveDef
  38812. * @param {GLTFParser} parser
  38813. */
  38814. function computeBounds( geometry, primitiveDef, parser ) {
  38815. var attributes = primitiveDef.attributes;
  38816. var box = new THREE.Box3();
  38817. if ( attributes.POSITION !== undefined ) {
  38818. var accessor = parser.json.accessors[ attributes.POSITION ];
  38819. var min = accessor.min;
  38820. var max = accessor.max;
  38821. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38822. if ( min !== undefined && max !== undefined ) {
  38823. box.set(
  38824. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  38825. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  38826. } else {
  38827. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38828. return;
  38829. }
  38830. } else {
  38831. return;
  38832. }
  38833. var targets = primitiveDef.targets;
  38834. if ( targets !== undefined ) {
  38835. var maxDisplacement = new THREE.Vector3();
  38836. var vector = new THREE.Vector3();
  38837. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38838. var target = targets[ i ];
  38839. if ( target.POSITION !== undefined ) {
  38840. var accessor = parser.json.accessors[ target.POSITION ];
  38841. var min = accessor.min;
  38842. var max = accessor.max;
  38843. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38844. if ( min !== undefined && max !== undefined ) {
  38845. // we need to get max of absolute components because target weight is [-1,1]
  38846. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  38847. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  38848. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  38849. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  38850. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  38851. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  38852. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  38853. maxDisplacement.max( vector );
  38854. } else {
  38855. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38856. }
  38857. }
  38858. }
  38859. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  38860. box.expandByVector( maxDisplacement );
  38861. }
  38862. geometry.boundingBox = box;
  38863. var sphere = new THREE.Sphere();
  38864. box.getCenter( sphere.center );
  38865. sphere.radius = box.min.distanceTo( box.max ) / 2;
  38866. geometry.boundingSphere = sphere;
  38867. }
  38868. /**
  38869. * @param {THREE.BufferGeometry} geometry
  38870. * @param {GLTF.Primitive} primitiveDef
  38871. * @param {GLTFParser} parser
  38872. * @return {Promise<THREE.BufferGeometry>}
  38873. */
  38874. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  38875. var attributes = primitiveDef.attributes;
  38876. var pending = [];
  38877. function assignAttributeAccessor( accessorIndex, attributeName ) {
  38878. return parser.getDependency( 'accessor', accessorIndex )
  38879. .then( function ( accessor ) {
  38880. geometry.setAttribute( attributeName, accessor );
  38881. } );
  38882. }
  38883. for ( var gltfAttributeName in attributes ) {
  38884. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  38885. // Skip attributes already provided by e.g. Draco extension.
  38886. if ( threeAttributeName in geometry.attributes ) continue;
  38887. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  38888. }
  38889. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  38890. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  38891. geometry.setIndex( accessor );
  38892. } );
  38893. pending.push( accessor );
  38894. }
  38895. assignExtrasToUserData( geometry, primitiveDef );
  38896. computeBounds( geometry, primitiveDef, parser );
  38897. return Promise.all( pending ).then( function () {
  38898. return primitiveDef.targets !== undefined
  38899. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  38900. : geometry;
  38901. } );
  38902. }
  38903. /**
  38904. * @param {THREE.BufferGeometry} geometry
  38905. * @param {Number} drawMode
  38906. * @return {THREE.BufferGeometry}
  38907. */
  38908. function toTrianglesDrawMode( geometry, drawMode ) {
  38909. var index = geometry.getIndex();
  38910. // generate index if not present
  38911. if ( index === null ) {
  38912. var indices = [];
  38913. var position = geometry.getAttribute( 'position' );
  38914. if ( position !== undefined ) {
  38915. for ( var i = 0; i < position.count; i ++ ) {
  38916. indices.push( i );
  38917. }
  38918. geometry.setIndex( indices );
  38919. index = geometry.getIndex();
  38920. } else {
  38921. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  38922. return geometry;
  38923. }
  38924. }
  38925. //
  38926. var numberOfTriangles = index.count - 2;
  38927. var newIndices = [];
  38928. if ( drawMode === THREE.TriangleFanDrawMode ) {
  38929. // gl.TRIANGLE_FAN
  38930. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  38931. newIndices.push( index.getX( 0 ) );
  38932. newIndices.push( index.getX( i ) );
  38933. newIndices.push( index.getX( i + 1 ) );
  38934. }
  38935. } else {
  38936. // gl.TRIANGLE_STRIP
  38937. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  38938. if ( i % 2 === 0 ) {
  38939. newIndices.push( index.getX( i ) );
  38940. newIndices.push( index.getX( i + 1 ) );
  38941. newIndices.push( index.getX( i + 2 ) );
  38942. } else {
  38943. newIndices.push( index.getX( i + 2 ) );
  38944. newIndices.push( index.getX( i + 1 ) );
  38945. newIndices.push( index.getX( i ) );
  38946. }
  38947. }
  38948. }
  38949. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  38950. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  38951. }
  38952. // build final geometry
  38953. var newGeometry = geometry.clone();
  38954. newGeometry.setIndex( newIndices );
  38955. return newGeometry;
  38956. }
  38957. /**
  38958. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  38959. *
  38960. * Creates BufferGeometries from primitives.
  38961. *
  38962. * @param {Array<GLTF.Primitive>} primitives
  38963. * @return {Promise<Array<THREE.BufferGeometry>>}
  38964. */
  38965. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  38966. var parser = this;
  38967. var extensions = this.extensions;
  38968. var cache = this.primitiveCache;
  38969. function createDracoPrimitive( primitive ) {
  38970. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  38971. .decodePrimitive( primitive, parser )
  38972. .then( function ( geometry ) {
  38973. return addPrimitiveAttributes( geometry, primitive, parser );
  38974. } );
  38975. }
  38976. var pending = [];
  38977. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38978. var primitive = primitives[ i ];
  38979. var cacheKey = createPrimitiveKey( primitive );
  38980. // See if we've already created this geometry
  38981. var cached = cache[ cacheKey ];
  38982. if ( cached ) {
  38983. // Use the cached geometry if it exists
  38984. pending.push( cached.promise );
  38985. } else {
  38986. var geometryPromise;
  38987. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  38988. // Use DRACO geometry if available
  38989. geometryPromise = createDracoPrimitive( primitive );
  38990. } else {
  38991. // Otherwise create a new geometry
  38992. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  38993. }
  38994. // Cache this geometry
  38995. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  38996. pending.push( geometryPromise );
  38997. }
  38998. }
  38999. return Promise.all( pending );
  39000. };
  39001. /**
  39002. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  39003. * @param {number} meshIndex
  39004. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  39005. */
  39006. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  39007. var parser = this;
  39008. var json = this.json;
  39009. var extensions = this.extensions;
  39010. var meshDef = json.meshes[ meshIndex ];
  39011. var primitives = meshDef.primitives;
  39012. var pending = [];
  39013. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  39014. var material = primitives[ i ].material === undefined
  39015. ? createDefaultMaterial( this.cache )
  39016. : this.getDependency( 'material', primitives[ i ].material );
  39017. pending.push( material );
  39018. }
  39019. pending.push( parser.loadGeometries( primitives ) );
  39020. return Promise.all( pending ).then( function ( results ) {
  39021. var materials = results.slice( 0, results.length - 1 );
  39022. var geometries = results[ results.length - 1 ];
  39023. var meshes = [];
  39024. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  39025. var geometry = geometries[ i ];
  39026. var primitive = primitives[ i ];
  39027. // 1. create Mesh
  39028. var mesh;
  39029. var material = materials[ i ];
  39030. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  39031. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  39032. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  39033. primitive.mode === undefined ) {
  39034. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  39035. mesh = meshDef.isSkinnedMesh === true
  39036. ? new THREE.SkinnedMesh( geometry, material )
  39037. : new THREE.Mesh( geometry, material );
  39038. // Fix double sided rendered models on certain mobile devices, see https://github.com/mrdoob/three.js/issues/20997#issuecomment-756082184
  39039. if ( material.isMeshStandardMaterial === true &&
  39040. material.side === THREE.DoubleSide &&
  39041. geometry.getIndex() !== null &&
  39042. geometry.hasAttribute( 'position' ) === true &&
  39043. geometry.hasAttribute( 'normal' ) === true &&
  39044. geometry.hasAttribute( 'uv' ) === true &&
  39045. geometry.hasAttribute( 'tangent' ) === false ) {
  39046. geometry.computeTangents();
  39047. material.vertexTangents = true;
  39048. }
  39049. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  39050. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  39051. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  39052. mesh.normalizeSkinWeights();
  39053. }
  39054. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  39055. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  39056. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  39057. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  39058. }
  39059. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  39060. mesh = new THREE.LineSegments( geometry, material );
  39061. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  39062. mesh = new THREE.Line( geometry, material );
  39063. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  39064. mesh = new THREE.LineLoop( geometry, material );
  39065. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  39066. mesh = new THREE.Points( geometry, material );
  39067. } else {
  39068. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  39069. }
  39070. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  39071. updateMorphTargets( mesh, meshDef );
  39072. }
  39073. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  39074. assignExtrasToUserData( mesh, meshDef );
  39075. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  39076. parser.assignFinalMaterial( mesh );
  39077. meshes.push( mesh );
  39078. }
  39079. if ( meshes.length === 1 ) {
  39080. return meshes[ 0 ];
  39081. }
  39082. var group = new THREE.Group();
  39083. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  39084. group.add( meshes[ i ] );
  39085. }
  39086. return group;
  39087. } );
  39088. };
  39089. /**
  39090. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  39091. * @param {number} cameraIndex
  39092. * @return {Promise<THREE.Camera>}
  39093. */
  39094. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  39095. var camera;
  39096. var cameraDef = this.json.cameras[ cameraIndex ];
  39097. var params = cameraDef[ cameraDef.type ];
  39098. if ( ! params ) {
  39099. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  39100. return;
  39101. }
  39102. if ( cameraDef.type === 'perspective' ) {
  39103. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  39104. } else if ( cameraDef.type === 'orthographic' ) {
  39105. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  39106. }
  39107. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  39108. assignExtrasToUserData( camera, cameraDef );
  39109. return Promise.resolve( camera );
  39110. };
  39111. /**
  39112. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  39113. * @param {number} skinIndex
  39114. * @return {Promise<Object>}
  39115. */
  39116. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  39117. var skinDef = this.json.skins[ skinIndex ];
  39118. var skinEntry = { joints: skinDef.joints };
  39119. if ( skinDef.inverseBindMatrices === undefined ) {
  39120. return Promise.resolve( skinEntry );
  39121. }
  39122. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  39123. skinEntry.inverseBindMatrices = accessor;
  39124. return skinEntry;
  39125. } );
  39126. };
  39127. /**
  39128. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  39129. * @param {number} animationIndex
  39130. * @return {Promise<THREE.AnimationClip>}
  39131. */
  39132. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  39133. var json = this.json;
  39134. var animationDef = json.animations[ animationIndex ];
  39135. var pendingNodes = [];
  39136. var pendingInputAccessors = [];
  39137. var pendingOutputAccessors = [];
  39138. var pendingSamplers = [];
  39139. var pendingTargets = [];
  39140. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  39141. var channel = animationDef.channels[ i ];
  39142. var sampler = animationDef.samplers[ channel.sampler ];
  39143. var target = channel.target;
  39144. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  39145. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  39146. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  39147. pendingNodes.push( this.getDependency( 'node', name ) );
  39148. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  39149. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  39150. pendingSamplers.push( sampler );
  39151. pendingTargets.push( target );
  39152. }
  39153. return Promise.all( [
  39154. Promise.all( pendingNodes ),
  39155. Promise.all( pendingInputAccessors ),
  39156. Promise.all( pendingOutputAccessors ),
  39157. Promise.all( pendingSamplers ),
  39158. Promise.all( pendingTargets )
  39159. ] ).then( function ( dependencies ) {
  39160. var nodes = dependencies[ 0 ];
  39161. var inputAccessors = dependencies[ 1 ];
  39162. var outputAccessors = dependencies[ 2 ];
  39163. var samplers = dependencies[ 3 ];
  39164. var targets = dependencies[ 4 ];
  39165. var tracks = [];
  39166. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  39167. var node = nodes[ i ];
  39168. var inputAccessor = inputAccessors[ i ];
  39169. var outputAccessor = outputAccessors[ i ];
  39170. var sampler = samplers[ i ];
  39171. var target = targets[ i ];
  39172. if ( node === undefined ) continue;
  39173. node.updateMatrix();
  39174. node.matrixAutoUpdate = true;
  39175. var TypedKeyframeTrack;
  39176. switch ( PATH_PROPERTIES[ target.path ] ) {
  39177. case PATH_PROPERTIES.weights:
  39178. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  39179. break;
  39180. case PATH_PROPERTIES.rotation:
  39181. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  39182. break;
  39183. case PATH_PROPERTIES.position:
  39184. case PATH_PROPERTIES.scale:
  39185. default:
  39186. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  39187. break;
  39188. }
  39189. var targetName = node.name ? node.name : node.uuid;
  39190. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  39191. var targetNames = [];
  39192. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  39193. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  39194. node.traverse( function ( object ) {
  39195. if ( object.isMesh === true && object.morphTargetInfluences ) {
  39196. targetNames.push( object.name ? object.name : object.uuid );
  39197. }
  39198. } );
  39199. } else {
  39200. targetNames.push( targetName );
  39201. }
  39202. var outputArray = outputAccessor.array;
  39203. if ( outputAccessor.normalized ) {
  39204. var scale;
  39205. if ( outputArray.constructor === Int8Array ) {
  39206. scale = 1 / 127;
  39207. } else if ( outputArray.constructor === Uint8Array ) {
  39208. scale = 1 / 255;
  39209. } else if ( outputArray.constructor == Int16Array ) {
  39210. scale = 1 / 32767;
  39211. } else if ( outputArray.constructor === Uint16Array ) {
  39212. scale = 1 / 65535;
  39213. } else {
  39214. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  39215. }
  39216. var scaled = new Float32Array( outputArray.length );
  39217. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  39218. scaled[ j ] = outputArray[ j ] * scale;
  39219. }
  39220. outputArray = scaled;
  39221. }
  39222. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  39223. var track = new TypedKeyframeTrack(
  39224. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  39225. inputAccessor.array,
  39226. outputArray,
  39227. interpolation
  39228. );
  39229. // Override interpolation with custom factory method.
  39230. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  39231. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  39232. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  39233. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  39234. // must be divided by three to get the interpolant's sampleSize argument.
  39235. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  39236. };
  39237. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  39238. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  39239. }
  39240. tracks.push( track );
  39241. }
  39242. }
  39243. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  39244. return new THREE.AnimationClip( name, undefined, tracks );
  39245. } );
  39246. };
  39247. /**
  39248. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  39249. * @param {number} nodeIndex
  39250. * @return {Promise<THREE.Object3D>}
  39251. */
  39252. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  39253. var json = this.json;
  39254. var extensions = this.extensions;
  39255. var parser = this;
  39256. var nodeDef = json.nodes[ nodeIndex ];
  39257. // reserve node's name before its dependencies, so the root has the intended name.
  39258. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  39259. return ( function () {
  39260. var pending = [];
  39261. if ( nodeDef.mesh !== undefined ) {
  39262. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  39263. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  39264. // if weights are provided on the node, override weights on the mesh.
  39265. if ( nodeDef.weights !== undefined ) {
  39266. node.traverse( function ( o ) {
  39267. if ( ! o.isMesh ) return;
  39268. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  39269. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  39270. }
  39271. } );
  39272. }
  39273. return node;
  39274. } ) );
  39275. }
  39276. if ( nodeDef.camera !== undefined ) {
  39277. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  39278. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  39279. } ) );
  39280. }
  39281. parser._invokeAll( function ( ext ) {
  39282. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  39283. } ).forEach( function ( promise ) {
  39284. pending.push( promise );
  39285. } );
  39286. return Promise.all( pending );
  39287. }() ).then( function ( objects ) {
  39288. var node;
  39289. // .isBone isn't in glTF spec. See ._markDefs
  39290. if ( nodeDef.isBone === true ) {
  39291. node = new THREE.Bone();
  39292. } else if ( objects.length > 1 ) {
  39293. node = new THREE.Group();
  39294. } else if ( objects.length === 1 ) {
  39295. node = objects[ 0 ];
  39296. } else {
  39297. node = new THREE.Object3D();
  39298. }
  39299. if ( node !== objects[ 0 ] ) {
  39300. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  39301. node.add( objects[ i ] );
  39302. }
  39303. }
  39304. if ( nodeDef.name ) {
  39305. node.userData.name = nodeDef.name;
  39306. node.name = nodeName;
  39307. }
  39308. assignExtrasToUserData( node, nodeDef );
  39309. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  39310. if ( nodeDef.matrix !== undefined ) {
  39311. var matrix = new THREE.Matrix4();
  39312. matrix.fromArray( nodeDef.matrix );
  39313. node.applyMatrix4( matrix );
  39314. } else {
  39315. if ( nodeDef.translation !== undefined ) {
  39316. node.position.fromArray( nodeDef.translation );
  39317. }
  39318. if ( nodeDef.rotation !== undefined ) {
  39319. node.quaternion.fromArray( nodeDef.rotation );
  39320. }
  39321. if ( nodeDef.scale !== undefined ) {
  39322. node.scale.fromArray( nodeDef.scale );
  39323. }
  39324. }
  39325. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  39326. return node;
  39327. } );
  39328. };
  39329. /**
  39330. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  39331. * @param {number} sceneIndex
  39332. * @return {Promise<THREE.Group>}
  39333. */
  39334. GLTFParser.prototype.loadScene = function () {
  39335. // scene node hierachy builder
  39336. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  39337. var nodeDef = json.nodes[ nodeId ];
  39338. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  39339. if ( nodeDef.skin === undefined ) return node;
  39340. // build skeleton here as well
  39341. var skinEntry;
  39342. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  39343. skinEntry = skin;
  39344. var pendingJoints = [];
  39345. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  39346. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  39347. }
  39348. return Promise.all( pendingJoints );
  39349. } ).then( function ( jointNodes ) {
  39350. node.traverse( function ( mesh ) {
  39351. if ( ! mesh.isMesh ) return;
  39352. var bones = [];
  39353. var boneInverses = [];
  39354. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  39355. var jointNode = jointNodes[ j ];
  39356. if ( jointNode ) {
  39357. bones.push( jointNode );
  39358. var mat = new THREE.Matrix4();
  39359. if ( skinEntry.inverseBindMatrices !== undefined ) {
  39360. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  39361. }
  39362. boneInverses.push( mat );
  39363. } else {
  39364. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  39365. }
  39366. }
  39367. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  39368. } );
  39369. return node;
  39370. } );
  39371. } ).then( function ( node ) {
  39372. // build node hierachy
  39373. parentObject.add( node );
  39374. var pending = [];
  39375. if ( nodeDef.children ) {
  39376. var children = nodeDef.children;
  39377. for ( var i = 0, il = children.length; i < il; i ++ ) {
  39378. var child = children[ i ];
  39379. pending.push( buildNodeHierachy( child, node, json, parser ) );
  39380. }
  39381. }
  39382. return Promise.all( pending );
  39383. } );
  39384. }
  39385. return function loadScene( sceneIndex ) {
  39386. var json = this.json;
  39387. var extensions = this.extensions;
  39388. var sceneDef = this.json.scenes[ sceneIndex ];
  39389. var parser = this;
  39390. // Loader returns Group, not Scene.
  39391. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  39392. var scene = new THREE.Group();
  39393. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  39394. assignExtrasToUserData( scene, sceneDef );
  39395. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  39396. var nodeIds = sceneDef.nodes || [];
  39397. var pending = [];
  39398. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  39399. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  39400. }
  39401. return Promise.all( pending ).then( function () {
  39402. return scene;
  39403. } );
  39404. };
  39405. }();
  39406. return GLTFLoader;
  39407. } )();
  39408. },{}],60:[function(_dereq_,module,exports){
  39409. /**
  39410. * Loads a Wavefront .mtl file specifying materials
  39411. */
  39412. THREE.MTLLoader = function ( manager ) {
  39413. THREE.Loader.call( this, manager );
  39414. };
  39415. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  39416. constructor: THREE.MTLLoader,
  39417. /**
  39418. * Loads and parses a MTL asset from a URL.
  39419. *
  39420. * @param {String} url - URL to the MTL file.
  39421. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  39422. * @param {Function} [onProgress] - Callback for download progress.
  39423. * @param {Function} [onError] - Callback for download errors.
  39424. *
  39425. * @see setPath setResourcePath
  39426. *
  39427. * @note In order for relative texture references to resolve correctly
  39428. * you must call setResourcePath() explicitly prior to load.
  39429. */
  39430. load: function ( url, onLoad, onProgress, onError ) {
  39431. var scope = this;
  39432. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  39433. var loader = new THREE.FileLoader( this.manager );
  39434. loader.setPath( this.path );
  39435. loader.setRequestHeader( this.requestHeader );
  39436. loader.setWithCredentials( this.withCredentials );
  39437. loader.load( url, function ( text ) {
  39438. try {
  39439. onLoad( scope.parse( text, path ) );
  39440. } catch ( e ) {
  39441. if ( onError ) {
  39442. onError( e );
  39443. } else {
  39444. console.error( e );
  39445. }
  39446. scope.manager.itemError( url );
  39447. }
  39448. }, onProgress, onError );
  39449. },
  39450. setMaterialOptions: function ( value ) {
  39451. this.materialOptions = value;
  39452. return this;
  39453. },
  39454. /**
  39455. * Parses a MTL file.
  39456. *
  39457. * @param {String} text - Content of MTL file
  39458. * @return {THREE.MTLLoader.MaterialCreator}
  39459. *
  39460. * @see setPath setResourcePath
  39461. *
  39462. * @note In order for relative texture references to resolve correctly
  39463. * you must call setResourcePath() explicitly prior to parse.
  39464. */
  39465. parse: function ( text, path ) {
  39466. var lines = text.split( '\n' );
  39467. var info = {};
  39468. var delimiter_pattern = /\s+/;
  39469. var materialsInfo = {};
  39470. for ( var i = 0; i < lines.length; i ++ ) {
  39471. var line = lines[ i ];
  39472. line = line.trim();
  39473. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  39474. // Blank line or comment ignore
  39475. continue;
  39476. }
  39477. var pos = line.indexOf( ' ' );
  39478. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  39479. key = key.toLowerCase();
  39480. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  39481. value = value.trim();
  39482. if ( key === 'newmtl' ) {
  39483. // New material
  39484. info = { name: value };
  39485. materialsInfo[ value ] = info;
  39486. } else {
  39487. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  39488. var ss = value.split( delimiter_pattern, 3 );
  39489. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  39490. } else {
  39491. info[ key ] = value;
  39492. }
  39493. }
  39494. }
  39495. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  39496. materialCreator.setCrossOrigin( this.crossOrigin );
  39497. materialCreator.setManager( this.manager );
  39498. materialCreator.setMaterials( materialsInfo );
  39499. return materialCreator;
  39500. }
  39501. } );
  39502. /**
  39503. * Create a new THREE.MTLLoader.MaterialCreator
  39504. * @param baseUrl - Url relative to which textures are loaded
  39505. * @param options - Set of options on how to construct the materials
  39506. * side: Which side to apply the material
  39507. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  39508. * wrap: What type of wrapping to apply for textures
  39509. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  39510. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  39511. * Default: false, assumed to be already normalized
  39512. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  39513. * Default: false
  39514. * @constructor
  39515. */
  39516. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  39517. this.baseUrl = baseUrl || '';
  39518. this.options = options;
  39519. this.materialsInfo = {};
  39520. this.materials = {};
  39521. this.materialsArray = [];
  39522. this.nameLookup = {};
  39523. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  39524. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  39525. };
  39526. THREE.MTLLoader.MaterialCreator.prototype = {
  39527. constructor: THREE.MTLLoader.MaterialCreator,
  39528. crossOrigin: 'anonymous',
  39529. setCrossOrigin: function ( value ) {
  39530. this.crossOrigin = value;
  39531. return this;
  39532. },
  39533. setManager: function ( value ) {
  39534. this.manager = value;
  39535. },
  39536. setMaterials: function ( materialsInfo ) {
  39537. this.materialsInfo = this.convert( materialsInfo );
  39538. this.materials = {};
  39539. this.materialsArray = [];
  39540. this.nameLookup = {};
  39541. },
  39542. convert: function ( materialsInfo ) {
  39543. if ( ! this.options ) return materialsInfo;
  39544. var converted = {};
  39545. for ( var mn in materialsInfo ) {
  39546. // Convert materials info into normalized form based on options
  39547. var mat = materialsInfo[ mn ];
  39548. var covmat = {};
  39549. converted[ mn ] = covmat;
  39550. for ( var prop in mat ) {
  39551. var save = true;
  39552. var value = mat[ prop ];
  39553. var lprop = prop.toLowerCase();
  39554. switch ( lprop ) {
  39555. case 'kd':
  39556. case 'ka':
  39557. case 'ks':
  39558. // Diffuse color (color under white light) using RGB values
  39559. if ( this.options && this.options.normalizeRGB ) {
  39560. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  39561. }
  39562. if ( this.options && this.options.ignoreZeroRGBs ) {
  39563. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  39564. // ignore
  39565. save = false;
  39566. }
  39567. }
  39568. break;
  39569. default:
  39570. break;
  39571. }
  39572. if ( save ) {
  39573. covmat[ lprop ] = value;
  39574. }
  39575. }
  39576. }
  39577. return converted;
  39578. },
  39579. preload: function () {
  39580. for ( var mn in this.materialsInfo ) {
  39581. this.create( mn );
  39582. }
  39583. },
  39584. getIndex: function ( materialName ) {
  39585. return this.nameLookup[ materialName ];
  39586. },
  39587. getAsArray: function () {
  39588. var index = 0;
  39589. for ( var mn in this.materialsInfo ) {
  39590. this.materialsArray[ index ] = this.create( mn );
  39591. this.nameLookup[ mn ] = index;
  39592. index ++;
  39593. }
  39594. return this.materialsArray;
  39595. },
  39596. create: function ( materialName ) {
  39597. if ( this.materials[ materialName ] === undefined ) {
  39598. this.createMaterial_( materialName );
  39599. }
  39600. return this.materials[ materialName ];
  39601. },
  39602. createMaterial_: function ( materialName ) {
  39603. // Create material
  39604. var scope = this;
  39605. var mat = this.materialsInfo[ materialName ];
  39606. var params = {
  39607. name: materialName,
  39608. side: this.side
  39609. };
  39610. function resolveURL( baseUrl, url ) {
  39611. if ( typeof url !== 'string' || url === '' )
  39612. return '';
  39613. // Absolute URL
  39614. if ( /^https?:\/\//i.test( url ) ) return url;
  39615. return baseUrl + url;
  39616. }
  39617. function setMapForType( mapType, value ) {
  39618. if ( params[ mapType ] ) return; // Keep the first encountered texture
  39619. var texParams = scope.getTextureParams( value, params );
  39620. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  39621. map.repeat.copy( texParams.scale );
  39622. map.offset.copy( texParams.offset );
  39623. map.wrapS = scope.wrap;
  39624. map.wrapT = scope.wrap;
  39625. params[ mapType ] = map;
  39626. }
  39627. for ( var prop in mat ) {
  39628. var value = mat[ prop ];
  39629. var n;
  39630. if ( value === '' ) continue;
  39631. switch ( prop.toLowerCase() ) {
  39632. // Ns is material specular exponent
  39633. case 'kd':
  39634. // Diffuse color (color under white light) using RGB values
  39635. params.color = new THREE.Color().fromArray( value );
  39636. break;
  39637. case 'ks':
  39638. // Specular color (color when light is reflected from shiny surface) using RGB values
  39639. params.specular = new THREE.Color().fromArray( value );
  39640. break;
  39641. case 'ke':
  39642. // Emissive using RGB values
  39643. params.emissive = new THREE.Color().fromArray( value );
  39644. break;
  39645. case 'map_kd':
  39646. // Diffuse texture map
  39647. setMapForType( 'map', value );
  39648. break;
  39649. case 'map_ks':
  39650. // Specular map
  39651. setMapForType( 'specularMap', value );
  39652. break;
  39653. case 'map_ke':
  39654. // Emissive map
  39655. setMapForType( 'emissiveMap', value );
  39656. break;
  39657. case 'norm':
  39658. setMapForType( 'normalMap', value );
  39659. break;
  39660. case 'map_bump':
  39661. case 'bump':
  39662. // Bump texture map
  39663. setMapForType( 'bumpMap', value );
  39664. break;
  39665. case 'map_d':
  39666. // Alpha map
  39667. setMapForType( 'alphaMap', value );
  39668. params.transparent = true;
  39669. break;
  39670. case 'ns':
  39671. // The specular exponent (defines the focus of the specular highlight)
  39672. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  39673. params.shininess = parseFloat( value );
  39674. break;
  39675. case 'd':
  39676. n = parseFloat( value );
  39677. if ( n < 1 ) {
  39678. params.opacity = n;
  39679. params.transparent = true;
  39680. }
  39681. break;
  39682. case 'tr':
  39683. n = parseFloat( value );
  39684. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  39685. if ( n > 0 ) {
  39686. params.opacity = 1 - n;
  39687. params.transparent = true;
  39688. }
  39689. break;
  39690. default:
  39691. break;
  39692. }
  39693. }
  39694. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  39695. return this.materials[ materialName ];
  39696. },
  39697. getTextureParams: function ( value, matParams ) {
  39698. var texParams = {
  39699. scale: new THREE.Vector2( 1, 1 ),
  39700. offset: new THREE.Vector2( 0, 0 )
  39701. };
  39702. var items = value.split( /\s+/ );
  39703. var pos;
  39704. pos = items.indexOf( '-bm' );
  39705. if ( pos >= 0 ) {
  39706. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  39707. items.splice( pos, 2 );
  39708. }
  39709. pos = items.indexOf( '-s' );
  39710. if ( pos >= 0 ) {
  39711. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39712. items.splice( pos, 4 ); // we expect 3 parameters here!
  39713. }
  39714. pos = items.indexOf( '-o' );
  39715. if ( pos >= 0 ) {
  39716. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39717. items.splice( pos, 4 ); // we expect 3 parameters here!
  39718. }
  39719. texParams.url = items.join( ' ' ).trim();
  39720. return texParams;
  39721. },
  39722. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  39723. var texture;
  39724. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  39725. var loader = manager.getHandler( url );
  39726. if ( loader === null ) {
  39727. loader = new THREE.TextureLoader( manager );
  39728. }
  39729. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  39730. texture = loader.load( url, onLoad, onProgress, onError );
  39731. if ( mapping !== undefined ) texture.mapping = mapping;
  39732. return texture;
  39733. }
  39734. };
  39735. },{}],61:[function(_dereq_,module,exports){
  39736. THREE.OBJLoader = ( function () {
  39737. // o object_name | g group_name
  39738. var object_pattern = /^[og]\s*(.+)?/;
  39739. // mtllib file_reference
  39740. var material_library_pattern = /^mtllib /;
  39741. // usemtl material_name
  39742. var material_use_pattern = /^usemtl /;
  39743. // usemap map_name
  39744. var map_use_pattern = /^usemap /;
  39745. var vA = new THREE.Vector3();
  39746. var vB = new THREE.Vector3();
  39747. var vC = new THREE.Vector3();
  39748. var ab = new THREE.Vector3();
  39749. var cb = new THREE.Vector3();
  39750. function ParserState() {
  39751. var state = {
  39752. objects: [],
  39753. object: {},
  39754. vertices: [],
  39755. normals: [],
  39756. colors: [],
  39757. uvs: [],
  39758. materials: {},
  39759. materialLibraries: [],
  39760. startObject: function ( name, fromDeclaration ) {
  39761. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  39762. // file. We need to use it for the first parsed g/o to keep things in sync.
  39763. if ( this.object && this.object.fromDeclaration === false ) {
  39764. this.object.name = name;
  39765. this.object.fromDeclaration = ( fromDeclaration !== false );
  39766. return;
  39767. }
  39768. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  39769. if ( this.object && typeof this.object._finalize === 'function' ) {
  39770. this.object._finalize( true );
  39771. }
  39772. this.object = {
  39773. name: name || '',
  39774. fromDeclaration: ( fromDeclaration !== false ),
  39775. geometry: {
  39776. vertices: [],
  39777. normals: [],
  39778. colors: [],
  39779. uvs: [],
  39780. hasUVIndices: false
  39781. },
  39782. materials: [],
  39783. smooth: true,
  39784. startMaterial: function ( name, libraries ) {
  39785. var previous = this._finalize( false );
  39786. // New usemtl declaration overwrites an inherited material, except if faces were declared
  39787. // after the material, then it must be preserved for proper MultiMaterial continuation.
  39788. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  39789. this.materials.splice( previous.index, 1 );
  39790. }
  39791. var material = {
  39792. index: this.materials.length,
  39793. name: name || '',
  39794. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  39795. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  39796. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  39797. groupEnd: - 1,
  39798. groupCount: - 1,
  39799. inherited: false,
  39800. clone: function ( index ) {
  39801. var cloned = {
  39802. index: ( typeof index === 'number' ? index : this.index ),
  39803. name: this.name,
  39804. mtllib: this.mtllib,
  39805. smooth: this.smooth,
  39806. groupStart: 0,
  39807. groupEnd: - 1,
  39808. groupCount: - 1,
  39809. inherited: false
  39810. };
  39811. cloned.clone = this.clone.bind( cloned );
  39812. return cloned;
  39813. }
  39814. };
  39815. this.materials.push( material );
  39816. return material;
  39817. },
  39818. currentMaterial: function () {
  39819. if ( this.materials.length > 0 ) {
  39820. return this.materials[ this.materials.length - 1 ];
  39821. }
  39822. return undefined;
  39823. },
  39824. _finalize: function ( end ) {
  39825. var lastMultiMaterial = this.currentMaterial();
  39826. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  39827. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  39828. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  39829. lastMultiMaterial.inherited = false;
  39830. }
  39831. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  39832. if ( end && this.materials.length > 1 ) {
  39833. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  39834. if ( this.materials[ mi ].groupCount <= 0 ) {
  39835. this.materials.splice( mi, 1 );
  39836. }
  39837. }
  39838. }
  39839. // Guarantee at least one empty material, this makes the creation later more straight forward.
  39840. if ( end && this.materials.length === 0 ) {
  39841. this.materials.push( {
  39842. name: '',
  39843. smooth: this.smooth
  39844. } );
  39845. }
  39846. return lastMultiMaterial;
  39847. }
  39848. };
  39849. // Inherit previous objects material.
  39850. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  39851. // If a usemtl declaration is encountered while this new object is being parsed, it will
  39852. // overwrite the inherited material. Exception being that there was already face declarations
  39853. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  39854. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  39855. var declared = previousMaterial.clone( 0 );
  39856. declared.inherited = true;
  39857. this.object.materials.push( declared );
  39858. }
  39859. this.objects.push( this.object );
  39860. },
  39861. finalize: function () {
  39862. if ( this.object && typeof this.object._finalize === 'function' ) {
  39863. this.object._finalize( true );
  39864. }
  39865. },
  39866. parseVertexIndex: function ( value, len ) {
  39867. var index = parseInt( value, 10 );
  39868. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39869. },
  39870. parseNormalIndex: function ( value, len ) {
  39871. var index = parseInt( value, 10 );
  39872. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39873. },
  39874. parseUVIndex: function ( value, len ) {
  39875. var index = parseInt( value, 10 );
  39876. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  39877. },
  39878. addVertex: function ( a, b, c ) {
  39879. var src = this.vertices;
  39880. var dst = this.object.geometry.vertices;
  39881. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39882. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39883. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39884. },
  39885. addVertexPoint: function ( a ) {
  39886. var src = this.vertices;
  39887. var dst = this.object.geometry.vertices;
  39888. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39889. },
  39890. addVertexLine: function ( a ) {
  39891. var src = this.vertices;
  39892. var dst = this.object.geometry.vertices;
  39893. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39894. },
  39895. addNormal: function ( a, b, c ) {
  39896. var src = this.normals;
  39897. var dst = this.object.geometry.normals;
  39898. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39899. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39900. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39901. },
  39902. addFaceNormal: function ( a, b, c ) {
  39903. var src = this.vertices;
  39904. var dst = this.object.geometry.normals;
  39905. vA.fromArray( src, a );
  39906. vB.fromArray( src, b );
  39907. vC.fromArray( src, c );
  39908. cb.subVectors( vC, vB );
  39909. ab.subVectors( vA, vB );
  39910. cb.cross( ab );
  39911. cb.normalize();
  39912. dst.push( cb.x, cb.y, cb.z );
  39913. dst.push( cb.x, cb.y, cb.z );
  39914. dst.push( cb.x, cb.y, cb.z );
  39915. },
  39916. addColor: function ( a, b, c ) {
  39917. var src = this.colors;
  39918. var dst = this.object.geometry.colors;
  39919. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39920. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39921. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39922. },
  39923. addUV: function ( a, b, c ) {
  39924. var src = this.uvs;
  39925. var dst = this.object.geometry.uvs;
  39926. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39927. dst.push( src[ b + 0 ], src[ b + 1 ] );
  39928. dst.push( src[ c + 0 ], src[ c + 1 ] );
  39929. },
  39930. addDefaultUV: function () {
  39931. var dst = this.object.geometry.uvs;
  39932. dst.push( 0, 0 );
  39933. dst.push( 0, 0 );
  39934. dst.push( 0, 0 );
  39935. },
  39936. addUVLine: function ( a ) {
  39937. var src = this.uvs;
  39938. var dst = this.object.geometry.uvs;
  39939. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39940. },
  39941. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  39942. var vLen = this.vertices.length;
  39943. var ia = this.parseVertexIndex( a, vLen );
  39944. var ib = this.parseVertexIndex( b, vLen );
  39945. var ic = this.parseVertexIndex( c, vLen );
  39946. this.addVertex( ia, ib, ic );
  39947. this.addColor( ia, ib, ic );
  39948. // normals
  39949. if ( na !== undefined && na !== '' ) {
  39950. var nLen = this.normals.length;
  39951. ia = this.parseNormalIndex( na, nLen );
  39952. ib = this.parseNormalIndex( nb, nLen );
  39953. ic = this.parseNormalIndex( nc, nLen );
  39954. this.addNormal( ia, ib, ic );
  39955. } else {
  39956. this.addFaceNormal( ia, ib, ic );
  39957. }
  39958. // uvs
  39959. if ( ua !== undefined && ua !== '' ) {
  39960. var uvLen = this.uvs.length;
  39961. ia = this.parseUVIndex( ua, uvLen );
  39962. ib = this.parseUVIndex( ub, uvLen );
  39963. ic = this.parseUVIndex( uc, uvLen );
  39964. this.addUV( ia, ib, ic );
  39965. this.object.geometry.hasUVIndices = true;
  39966. } else {
  39967. // add placeholder values (for inconsistent face definitions)
  39968. this.addDefaultUV();
  39969. }
  39970. },
  39971. addPointGeometry: function ( vertices ) {
  39972. this.object.geometry.type = 'Points';
  39973. var vLen = this.vertices.length;
  39974. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39975. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  39976. this.addVertexPoint( index );
  39977. this.addColor( index );
  39978. }
  39979. },
  39980. addLineGeometry: function ( vertices, uvs ) {
  39981. this.object.geometry.type = 'Line';
  39982. var vLen = this.vertices.length;
  39983. var uvLen = this.uvs.length;
  39984. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39985. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39986. }
  39987. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  39988. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  39989. }
  39990. }
  39991. };
  39992. state.startObject( '', false );
  39993. return state;
  39994. }
  39995. //
  39996. function OBJLoader( manager ) {
  39997. THREE.Loader.call( this, manager );
  39998. this.materials = null;
  39999. }
  40000. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  40001. constructor: OBJLoader,
  40002. load: function ( url, onLoad, onProgress, onError ) {
  40003. var scope = this;
  40004. var loader = new THREE.FileLoader( this.manager );
  40005. loader.setPath( this.path );
  40006. loader.setRequestHeader( this.requestHeader );
  40007. loader.setWithCredentials( this.withCredentials );
  40008. loader.load( url, function ( text ) {
  40009. try {
  40010. onLoad( scope.parse( text ) );
  40011. } catch ( e ) {
  40012. if ( onError ) {
  40013. onError( e );
  40014. } else {
  40015. console.error( e );
  40016. }
  40017. scope.manager.itemError( url );
  40018. }
  40019. }, onProgress, onError );
  40020. },
  40021. setMaterials: function ( materials ) {
  40022. this.materials = materials;
  40023. return this;
  40024. },
  40025. parse: function ( text ) {
  40026. var state = new ParserState();
  40027. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  40028. // This is faster than String.split with regex that splits on both
  40029. text = text.replace( /\r\n/g, '\n' );
  40030. }
  40031. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  40032. // join lines separated by a line continuation character (\)
  40033. text = text.replace( /\\\n/g, '' );
  40034. }
  40035. var lines = text.split( '\n' );
  40036. var line = '', lineFirstChar = '';
  40037. var lineLength = 0;
  40038. var result = [];
  40039. // Faster to just trim left side of the line. Use if available.
  40040. var trimLeft = ( typeof ''.trimLeft === 'function' );
  40041. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  40042. line = lines[ i ];
  40043. line = trimLeft ? line.trimLeft() : line.trim();
  40044. lineLength = line.length;
  40045. if ( lineLength === 0 ) continue;
  40046. lineFirstChar = line.charAt( 0 );
  40047. // @todo invoke passed in handler if any
  40048. if ( lineFirstChar === '#' ) continue;
  40049. if ( lineFirstChar === 'v' ) {
  40050. var data = line.split( /\s+/ );
  40051. switch ( data[ 0 ] ) {
  40052. case 'v':
  40053. state.vertices.push(
  40054. parseFloat( data[ 1 ] ),
  40055. parseFloat( data[ 2 ] ),
  40056. parseFloat( data[ 3 ] )
  40057. );
  40058. if ( data.length >= 7 ) {
  40059. state.colors.push(
  40060. parseFloat( data[ 4 ] ),
  40061. parseFloat( data[ 5 ] ),
  40062. parseFloat( data[ 6 ] )
  40063. );
  40064. } else {
  40065. // if no colors are defined, add placeholders so color and vertex indices match
  40066. state.colors.push( undefined, undefined, undefined );
  40067. }
  40068. break;
  40069. case 'vn':
  40070. state.normals.push(
  40071. parseFloat( data[ 1 ] ),
  40072. parseFloat( data[ 2 ] ),
  40073. parseFloat( data[ 3 ] )
  40074. );
  40075. break;
  40076. case 'vt':
  40077. state.uvs.push(
  40078. parseFloat( data[ 1 ] ),
  40079. parseFloat( data[ 2 ] )
  40080. );
  40081. break;
  40082. }
  40083. } else if ( lineFirstChar === 'f' ) {
  40084. var lineData = line.substr( 1 ).trim();
  40085. var vertexData = lineData.split( /\s+/ );
  40086. var faceVertices = [];
  40087. // Parse the face vertex data into an easy to work with format
  40088. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  40089. var vertex = vertexData[ j ];
  40090. if ( vertex.length > 0 ) {
  40091. var vertexParts = vertex.split( '/' );
  40092. faceVertices.push( vertexParts );
  40093. }
  40094. }
  40095. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  40096. var v1 = faceVertices[ 0 ];
  40097. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  40098. var v2 = faceVertices[ j ];
  40099. var v3 = faceVertices[ j + 1 ];
  40100. state.addFace(
  40101. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  40102. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  40103. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  40104. );
  40105. }
  40106. } else if ( lineFirstChar === 'l' ) {
  40107. var lineParts = line.substring( 1 ).trim().split( ' ' );
  40108. var lineVertices = [], lineUVs = [];
  40109. if ( line.indexOf( '/' ) === - 1 ) {
  40110. lineVertices = lineParts;
  40111. } else {
  40112. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  40113. var parts = lineParts[ li ].split( '/' );
  40114. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  40115. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  40116. }
  40117. }
  40118. state.addLineGeometry( lineVertices, lineUVs );
  40119. } else if ( lineFirstChar === 'p' ) {
  40120. var lineData = line.substr( 1 ).trim();
  40121. var pointData = lineData.split( ' ' );
  40122. state.addPointGeometry( pointData );
  40123. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  40124. // o object_name
  40125. // or
  40126. // g group_name
  40127. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  40128. // var name = result[ 0 ].substr( 1 ).trim();
  40129. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  40130. state.startObject( name );
  40131. } else if ( material_use_pattern.test( line ) ) {
  40132. // material
  40133. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  40134. } else if ( material_library_pattern.test( line ) ) {
  40135. // mtl file
  40136. state.materialLibraries.push( line.substring( 7 ).trim() );
  40137. } else if ( map_use_pattern.test( line ) ) {
  40138. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  40139. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  40140. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  40141. } else if ( lineFirstChar === 's' ) {
  40142. result = line.split( ' ' );
  40143. // smooth shading
  40144. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  40145. // but does not define a usemtl for each face set.
  40146. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  40147. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  40148. // where explicit usemtl defines geometry groups.
  40149. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  40150. /*
  40151. * http://paulbourke.net/dataformats/obj/
  40152. * or
  40153. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  40154. *
  40155. * From chapter "Grouping" Syntax explanation "s group_number":
  40156. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  40157. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  40158. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  40159. * than 0."
  40160. */
  40161. if ( result.length > 1 ) {
  40162. var value = result[ 1 ].trim().toLowerCase();
  40163. state.object.smooth = ( value !== '0' && value !== 'off' );
  40164. } else {
  40165. // ZBrush can produce "s" lines #11707
  40166. state.object.smooth = true;
  40167. }
  40168. var material = state.object.currentMaterial();
  40169. if ( material ) material.smooth = state.object.smooth;
  40170. } else {
  40171. // Handle null terminated files without exception
  40172. if ( line === '\0' ) continue;
  40173. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  40174. }
  40175. }
  40176. state.finalize();
  40177. var container = new THREE.Group();
  40178. container.materialLibraries = [].concat( state.materialLibraries );
  40179. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  40180. if ( hasPrimitives === true ) {
  40181. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  40182. var object = state.objects[ i ];
  40183. var geometry = object.geometry;
  40184. var materials = object.materials;
  40185. var isLine = ( geometry.type === 'Line' );
  40186. var isPoints = ( geometry.type === 'Points' );
  40187. var hasVertexColors = false;
  40188. // Skip o/g line declarations that did not follow with any faces
  40189. if ( geometry.vertices.length === 0 ) continue;
  40190. var buffergeometry = new THREE.BufferGeometry();
  40191. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  40192. if ( geometry.normals.length > 0 ) {
  40193. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  40194. }
  40195. if ( geometry.colors.length > 0 ) {
  40196. hasVertexColors = true;
  40197. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  40198. }
  40199. if ( geometry.hasUVIndices === true ) {
  40200. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  40201. }
  40202. // Create materials
  40203. var createdMaterials = [];
  40204. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40205. var sourceMaterial = materials[ mi ];
  40206. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  40207. var material = state.materials[ materialHash ];
  40208. if ( this.materials !== null ) {
  40209. material = this.materials.create( sourceMaterial.name );
  40210. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  40211. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  40212. var materialLine = new THREE.LineBasicMaterial();
  40213. THREE.Material.prototype.copy.call( materialLine, material );
  40214. materialLine.color.copy( material.color );
  40215. material = materialLine;
  40216. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  40217. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  40218. THREE.Material.prototype.copy.call( materialPoints, material );
  40219. materialPoints.color.copy( material.color );
  40220. materialPoints.map = material.map;
  40221. material = materialPoints;
  40222. }
  40223. }
  40224. if ( material === undefined ) {
  40225. if ( isLine ) {
  40226. material = new THREE.LineBasicMaterial();
  40227. } else if ( isPoints ) {
  40228. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40229. } else {
  40230. material = new THREE.MeshPhongMaterial();
  40231. }
  40232. material.name = sourceMaterial.name;
  40233. material.flatShading = sourceMaterial.smooth ? false : true;
  40234. material.vertexColors = hasVertexColors;
  40235. state.materials[ materialHash ] = material;
  40236. }
  40237. createdMaterials.push( material );
  40238. }
  40239. // Create mesh
  40240. var mesh;
  40241. if ( createdMaterials.length > 1 ) {
  40242. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40243. var sourceMaterial = materials[ mi ];
  40244. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  40245. }
  40246. if ( isLine ) {
  40247. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  40248. } else if ( isPoints ) {
  40249. mesh = new THREE.Points( buffergeometry, createdMaterials );
  40250. } else {
  40251. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  40252. }
  40253. } else {
  40254. if ( isLine ) {
  40255. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  40256. } else if ( isPoints ) {
  40257. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  40258. } else {
  40259. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  40260. }
  40261. }
  40262. mesh.name = object.name;
  40263. container.add( mesh );
  40264. }
  40265. } else {
  40266. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  40267. if ( state.vertices.length > 0 ) {
  40268. var material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40269. var buffergeometry = new THREE.BufferGeometry();
  40270. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( state.vertices, 3 ) );
  40271. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  40272. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( state.colors, 3 ) );
  40273. material.vertexColors = true;
  40274. }
  40275. var points = new THREE.Points( buffergeometry, material );
  40276. container.add( points );
  40277. }
  40278. }
  40279. return container;
  40280. }
  40281. } );
  40282. return OBJLoader;
  40283. } )();
  40284. },{}],62:[function(_dereq_,module,exports){
  40285. THREE.BufferGeometryUtils = {
  40286. computeTangents: function ( geometry ) {
  40287. geometry.computeTangents();
  40288. console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use BufferGeometry.computeTangents() instead.' );
  40289. },
  40290. /**
  40291. * @param {Array<THREE.BufferGeometry>} geometries
  40292. * @param {Boolean} useGroups
  40293. * @return {THREE.BufferGeometry}
  40294. */
  40295. mergeBufferGeometries: function ( geometries, useGroups ) {
  40296. var isIndexed = geometries[ 0 ].index !== null;
  40297. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  40298. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  40299. var attributes = {};
  40300. var morphAttributes = {};
  40301. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  40302. var mergedGeometry = new THREE.BufferGeometry();
  40303. var offset = 0;
  40304. for ( var i = 0; i < geometries.length; ++ i ) {
  40305. var geometry = geometries[ i ];
  40306. var attributesCount = 0;
  40307. // ensure that all geometries are indexed, or none
  40308. if ( isIndexed !== ( geometry.index !== null ) ) {
  40309. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
  40310. return null;
  40311. }
  40312. // gather attributes, exit early if they're different
  40313. for ( var name in geometry.attributes ) {
  40314. if ( ! attributesUsed.has( name ) ) {
  40315. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
  40316. return null;
  40317. }
  40318. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  40319. attributes[ name ].push( geometry.attributes[ name ] );
  40320. attributesCount ++;
  40321. }
  40322. // ensure geometries have the same number of attributes
  40323. if ( attributesCount !== attributesUsed.size ) {
  40324. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  40325. return null;
  40326. }
  40327. // gather morph attributes, exit early if they're different
  40328. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  40329. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  40330. return null;
  40331. }
  40332. for ( var name in geometry.morphAttributes ) {
  40333. if ( ! morphAttributesUsed.has( name ) ) {
  40334. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  40335. return null;
  40336. }
  40337. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  40338. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  40339. }
  40340. // gather .userData
  40341. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  40342. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  40343. if ( useGroups ) {
  40344. var count;
  40345. if ( isIndexed ) {
  40346. count = geometry.index.count;
  40347. } else if ( geometry.attributes.position !== undefined ) {
  40348. count = geometry.attributes.position.count;
  40349. } else {
  40350. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  40351. return null;
  40352. }
  40353. mergedGeometry.addGroup( offset, count, i );
  40354. offset += count;
  40355. }
  40356. }
  40357. // merge indices
  40358. if ( isIndexed ) {
  40359. var indexOffset = 0;
  40360. var mergedIndex = [];
  40361. for ( var i = 0; i < geometries.length; ++ i ) {
  40362. var index = geometries[ i ].index;
  40363. for ( var j = 0; j < index.count; ++ j ) {
  40364. mergedIndex.push( index.getX( j ) + indexOffset );
  40365. }
  40366. indexOffset += geometries[ i ].attributes.position.count;
  40367. }
  40368. mergedGeometry.setIndex( mergedIndex );
  40369. }
  40370. // merge attributes
  40371. for ( var name in attributes ) {
  40372. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  40373. if ( ! mergedAttribute ) {
  40374. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  40375. return null;
  40376. }
  40377. mergedGeometry.setAttribute( name, mergedAttribute );
  40378. }
  40379. // merge morph attributes
  40380. for ( var name in morphAttributes ) {
  40381. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  40382. if ( numMorphTargets === 0 ) break;
  40383. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  40384. mergedGeometry.morphAttributes[ name ] = [];
  40385. for ( var i = 0; i < numMorphTargets; ++ i ) {
  40386. var morphAttributesToMerge = [];
  40387. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  40388. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  40389. }
  40390. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  40391. if ( ! mergedMorphAttribute ) {
  40392. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  40393. return null;
  40394. }
  40395. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  40396. }
  40397. }
  40398. return mergedGeometry;
  40399. },
  40400. /**
  40401. * @param {Array<THREE.BufferAttribute>} attributes
  40402. * @return {THREE.BufferAttribute}
  40403. */
  40404. mergeBufferAttributes: function ( attributes ) {
  40405. var TypedArray;
  40406. var itemSize;
  40407. var normalized;
  40408. var arrayLength = 0;
  40409. for ( var i = 0; i < attributes.length; ++ i ) {
  40410. var attribute = attributes[ i ];
  40411. if ( attribute.isInterleavedBufferAttribute ) {
  40412. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  40413. return null;
  40414. }
  40415. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  40416. if ( TypedArray !== attribute.array.constructor ) {
  40417. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  40418. return null;
  40419. }
  40420. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  40421. if ( itemSize !== attribute.itemSize ) {
  40422. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  40423. return null;
  40424. }
  40425. if ( normalized === undefined ) normalized = attribute.normalized;
  40426. if ( normalized !== attribute.normalized ) {
  40427. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  40428. return null;
  40429. }
  40430. arrayLength += attribute.array.length;
  40431. }
  40432. var array = new TypedArray( arrayLength );
  40433. var offset = 0;
  40434. for ( var i = 0; i < attributes.length; ++ i ) {
  40435. array.set( attributes[ i ].array, offset );
  40436. offset += attributes[ i ].array.length;
  40437. }
  40438. return new THREE.BufferAttribute( array, itemSize, normalized );
  40439. },
  40440. /**
  40441. * @param {Array<THREE.BufferAttribute>} attributes
  40442. * @return {Array<THREE.InterleavedBufferAttribute>}
  40443. */
  40444. interleaveAttributes: function ( attributes ) {
  40445. // Interleaves the provided attributes into an InterleavedBuffer and returns
  40446. // a set of InterleavedBufferAttributes for each attribute
  40447. var TypedArray;
  40448. var arrayLength = 0;
  40449. var stride = 0;
  40450. // calculate the the length and type of the interleavedBuffer
  40451. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  40452. var attribute = attributes[ i ];
  40453. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  40454. if ( TypedArray !== attribute.array.constructor ) {
  40455. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  40456. return null;
  40457. }
  40458. arrayLength += attribute.array.length;
  40459. stride += attribute.itemSize;
  40460. }
  40461. // Create the set of buffer attributes
  40462. var interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  40463. var offset = 0;
  40464. var res = [];
  40465. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  40466. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  40467. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  40468. var attribute = attributes[ j ];
  40469. var itemSize = attribute.itemSize;
  40470. var count = attribute.count;
  40471. var iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  40472. res.push( iba );
  40473. offset += itemSize;
  40474. // Move the data for each attribute into the new interleavedBuffer
  40475. // at the appropriate offset
  40476. for ( var c = 0; c < count; c ++ ) {
  40477. for ( var k = 0; k < itemSize; k ++ ) {
  40478. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  40479. }
  40480. }
  40481. }
  40482. return res;
  40483. },
  40484. /**
  40485. * @param {Array<THREE.BufferGeometry>} geometry
  40486. * @return {number}
  40487. */
  40488. estimateBytesUsed: function ( geometry ) {
  40489. // Return the estimated memory used by this geometry in bytes
  40490. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  40491. // for InterleavedBufferAttributes.
  40492. var mem = 0;
  40493. for ( var name in geometry.attributes ) {
  40494. var attr = geometry.getAttribute( name );
  40495. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  40496. }
  40497. var indices = geometry.getIndex();
  40498. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  40499. return mem;
  40500. },
  40501. /**
  40502. * @param {THREE.BufferGeometry} geometry
  40503. * @param {number} tolerance
  40504. * @return {THREE.BufferGeometry>}
  40505. */
  40506. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  40507. tolerance = Math.max( tolerance, Number.EPSILON );
  40508. // Generate an index buffer if the geometry doesn't have one, or optimize it
  40509. // if it's already available.
  40510. var hashToIndex = {};
  40511. var indices = geometry.getIndex();
  40512. var positions = geometry.getAttribute( 'position' );
  40513. var vertexCount = indices ? indices.count : positions.count;
  40514. // next value for triangle indices
  40515. var nextIndex = 0;
  40516. // attributes and new attribute arrays
  40517. var attributeNames = Object.keys( geometry.attributes );
  40518. var attrArrays = {};
  40519. var morphAttrsArrays = {};
  40520. var newIndices = [];
  40521. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  40522. // initialize the arrays
  40523. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  40524. var name = attributeNames[ i ];
  40525. attrArrays[ name ] = [];
  40526. var morphAttr = geometry.morphAttributes[ name ];
  40527. if ( morphAttr ) {
  40528. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  40529. }
  40530. }
  40531. // convert the error tolerance to an amount of decimal places to truncate to
  40532. var decimalShift = Math.log10( 1 / tolerance );
  40533. var shiftMultiplier = Math.pow( 10, decimalShift );
  40534. for ( var i = 0; i < vertexCount; i ++ ) {
  40535. var index = indices ? indices.getX( i ) : i;
  40536. // Generate a hash for the vertex attributes at the current index 'i'
  40537. var hash = '';
  40538. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  40539. var name = attributeNames[ j ];
  40540. var attribute = geometry.getAttribute( name );
  40541. var itemSize = attribute.itemSize;
  40542. for ( var k = 0; k < itemSize; k ++ ) {
  40543. // double tilde truncates the decimal value
  40544. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  40545. }
  40546. }
  40547. // Add another reference to the vertex if it's already
  40548. // used by another index
  40549. if ( hash in hashToIndex ) {
  40550. newIndices.push( hashToIndex[ hash ] );
  40551. } else {
  40552. // copy data to the new index in the attribute arrays
  40553. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  40554. var name = attributeNames[ j ];
  40555. var attribute = geometry.getAttribute( name );
  40556. var morphAttr = geometry.morphAttributes[ name ];
  40557. var itemSize = attribute.itemSize;
  40558. var newarray = attrArrays[ name ];
  40559. var newMorphArrays = morphAttrsArrays[ name ];
  40560. for ( var k = 0; k < itemSize; k ++ ) {
  40561. var getterFunc = getters[ k ];
  40562. newarray.push( attribute[ getterFunc ]( index ) );
  40563. if ( morphAttr ) {
  40564. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  40565. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  40566. }
  40567. }
  40568. }
  40569. }
  40570. hashToIndex[ hash ] = nextIndex;
  40571. newIndices.push( nextIndex );
  40572. nextIndex ++;
  40573. }
  40574. }
  40575. // Generate typed arrays from new attribute arrays and update
  40576. // the attributeBuffers
  40577. const result = geometry.clone();
  40578. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  40579. var name = attributeNames[ i ];
  40580. var oldAttribute = geometry.getAttribute( name );
  40581. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  40582. var attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  40583. result.setAttribute( name, attribute );
  40584. // Update the attribute arrays
  40585. if ( name in morphAttrsArrays ) {
  40586. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  40587. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  40588. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  40589. var morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  40590. result.morphAttributes[ name ][ j ] = morphAttribute;
  40591. }
  40592. }
  40593. }
  40594. // indices
  40595. result.setIndex( newIndices );
  40596. return result;
  40597. },
  40598. /**
  40599. * @param {THREE.BufferGeometry} geometry
  40600. * @param {number} drawMode
  40601. * @return {THREE.BufferGeometry>}
  40602. */
  40603. toTrianglesDrawMode: function ( geometry, drawMode ) {
  40604. if ( drawMode === THREE.TrianglesDrawMode ) {
  40605. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  40606. return geometry;
  40607. }
  40608. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  40609. var index = geometry.getIndex();
  40610. // generate index if not present
  40611. if ( index === null ) {
  40612. var indices = [];
  40613. var position = geometry.getAttribute( 'position' );
  40614. if ( position !== undefined ) {
  40615. for ( var i = 0; i < position.count; i ++ ) {
  40616. indices.push( i );
  40617. }
  40618. geometry.setIndex( indices );
  40619. index = geometry.getIndex();
  40620. } else {
  40621. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  40622. return geometry;
  40623. }
  40624. }
  40625. //
  40626. var numberOfTriangles = index.count - 2;
  40627. var newIndices = [];
  40628. if ( drawMode === THREE.TriangleFanDrawMode ) {
  40629. // gl.TRIANGLE_FAN
  40630. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  40631. newIndices.push( index.getX( 0 ) );
  40632. newIndices.push( index.getX( i ) );
  40633. newIndices.push( index.getX( i + 1 ) );
  40634. }
  40635. } else {
  40636. // gl.TRIANGLE_STRIP
  40637. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  40638. if ( i % 2 === 0 ) {
  40639. newIndices.push( index.getX( i ) );
  40640. newIndices.push( index.getX( i + 1 ) );
  40641. newIndices.push( index.getX( i + 2 ) );
  40642. } else {
  40643. newIndices.push( index.getX( i + 2 ) );
  40644. newIndices.push( index.getX( i + 1 ) );
  40645. newIndices.push( index.getX( i ) );
  40646. }
  40647. }
  40648. }
  40649. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  40650. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  40651. }
  40652. // build final geometry
  40653. var newGeometry = geometry.clone();
  40654. newGeometry.setIndex( newIndices );
  40655. newGeometry.clearGroups();
  40656. return newGeometry;
  40657. } else {
  40658. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  40659. return geometry;
  40660. }
  40661. },
  40662. /**
  40663. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  40664. * Helpful for Raytracing or Decals.
  40665. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  40666. * @return {Object} An Object with original position/normal attributes and morphed ones.
  40667. */
  40668. computeMorphedAttributes: function ( object ) {
  40669. if ( object.geometry.isBufferGeometry !== true ) {
  40670. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type THREE.BufferGeometry.' );
  40671. return null;
  40672. }
  40673. var _vA = new THREE.Vector3();
  40674. var _vB = new THREE.Vector3();
  40675. var _vC = new THREE.Vector3();
  40676. var _tempA = new THREE.Vector3();
  40677. var _tempB = new THREE.Vector3();
  40678. var _tempC = new THREE.Vector3();
  40679. var _morphA = new THREE.Vector3();
  40680. var _morphB = new THREE.Vector3();
  40681. var _morphC = new THREE.Vector3();
  40682. function _calculateMorphedAttributeData(
  40683. object,
  40684. material,
  40685. attribute,
  40686. morphAttribute,
  40687. morphTargetsRelative,
  40688. a,
  40689. b,
  40690. c,
  40691. modifiedAttributeArray
  40692. ) {
  40693. _vA.fromBufferAttribute( attribute, a );
  40694. _vB.fromBufferAttribute( attribute, b );
  40695. _vC.fromBufferAttribute( attribute, c );
  40696. var morphInfluences = object.morphTargetInfluences;
  40697. if ( material.morphTargets && morphAttribute && morphInfluences ) {
  40698. _morphA.set( 0, 0, 0 );
  40699. _morphB.set( 0, 0, 0 );
  40700. _morphC.set( 0, 0, 0 );
  40701. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  40702. var influence = morphInfluences[ i ];
  40703. var morphAttribute = morphAttribute[ i ];
  40704. if ( influence === 0 ) continue;
  40705. _tempA.fromBufferAttribute( morphAttribute, a );
  40706. _tempB.fromBufferAttribute( morphAttribute, b );
  40707. _tempC.fromBufferAttribute( morphAttribute, c );
  40708. if ( morphTargetsRelative ) {
  40709. _morphA.addScaledVector( _tempA, influence );
  40710. _morphB.addScaledVector( _tempB, influence );
  40711. _morphC.addScaledVector( _tempC, influence );
  40712. } else {
  40713. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  40714. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  40715. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  40716. }
  40717. }
  40718. _vA.add( _morphA );
  40719. _vB.add( _morphB );
  40720. _vC.add( _morphC );
  40721. }
  40722. if ( object.isSkinnedMesh ) {
  40723. object.boneTransform( a, _vA );
  40724. object.boneTransform( b, _vB );
  40725. object.boneTransform( c, _vC );
  40726. }
  40727. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  40728. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  40729. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  40730. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  40731. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  40732. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  40733. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  40734. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  40735. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  40736. }
  40737. var geometry = object.geometry;
  40738. var material = object.material;
  40739. var a, b, c;
  40740. var index = geometry.index;
  40741. var positionAttribute = geometry.attributes.position;
  40742. var morphPosition = geometry.morphAttributes.position;
  40743. var morphTargetsRelative = geometry.morphTargetsRelative;
  40744. var normalAttribute = geometry.attributes.normal;
  40745. var morphNormal = geometry.morphAttributes.position;
  40746. var groups = geometry.groups;
  40747. var drawRange = geometry.drawRange;
  40748. var i, j, il, jl;
  40749. var group, groupMaterial;
  40750. var start, end;
  40751. var modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  40752. var modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  40753. if ( index !== null ) {
  40754. // indexed buffer geometry
  40755. if ( Array.isArray( material ) ) {
  40756. for ( i = 0, il = groups.length; i < il; i ++ ) {
  40757. group = groups[ i ];
  40758. groupMaterial = material[ group.materialIndex ];
  40759. start = Math.max( group.start, drawRange.start );
  40760. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  40761. for ( j = start, jl = end; j < jl; j += 3 ) {
  40762. a = index.getX( j );
  40763. b = index.getX( j + 1 );
  40764. c = index.getX( j + 2 );
  40765. _calculateMorphedAttributeData(
  40766. object,
  40767. groupMaterial,
  40768. positionAttribute,
  40769. morphPosition,
  40770. morphTargetsRelative,
  40771. a, b, c,
  40772. modifiedPosition
  40773. );
  40774. _calculateMorphedAttributeData(
  40775. object,
  40776. groupMaterial,
  40777. normalAttribute,
  40778. morphNormal,
  40779. morphTargetsRelative,
  40780. a, b, c,
  40781. modifiedNormal
  40782. );
  40783. }
  40784. }
  40785. } else {
  40786. start = Math.max( 0, drawRange.start );
  40787. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  40788. for ( i = start, il = end; i < il; i += 3 ) {
  40789. a = index.getX( i );
  40790. b = index.getX( i + 1 );
  40791. c = index.getX( i + 2 );
  40792. _calculateMorphedAttributeData(
  40793. object,
  40794. material,
  40795. positionAttribute,
  40796. morphPosition,
  40797. morphTargetsRelative,
  40798. a, b, c,
  40799. modifiedPosition
  40800. );
  40801. _calculateMorphedAttributeData(
  40802. object,
  40803. material,
  40804. normalAttribute,
  40805. morphNormal,
  40806. morphTargetsRelative,
  40807. a, b, c,
  40808. modifiedNormal
  40809. );
  40810. }
  40811. }
  40812. } else if ( positionAttribute !== undefined ) {
  40813. // non-indexed buffer geometry
  40814. if ( Array.isArray( material ) ) {
  40815. for ( i = 0, il = groups.length; i < il; i ++ ) {
  40816. group = groups[ i ];
  40817. groupMaterial = material[ group.materialIndex ];
  40818. start = Math.max( group.start, drawRange.start );
  40819. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  40820. for ( j = start, jl = end; j < jl; j += 3 ) {
  40821. a = j;
  40822. b = j + 1;
  40823. c = j + 2;
  40824. _calculateMorphedAttributeData(
  40825. object,
  40826. groupMaterial,
  40827. positionAttribute,
  40828. morphPosition,
  40829. morphTargetsRelative,
  40830. a, b, c,
  40831. modifiedPosition
  40832. );
  40833. _calculateMorphedAttributeData(
  40834. object,
  40835. groupMaterial,
  40836. normalAttribute,
  40837. morphNormal,
  40838. morphTargetsRelative,
  40839. a, b, c,
  40840. modifiedNormal
  40841. );
  40842. }
  40843. }
  40844. } else {
  40845. start = Math.max( 0, drawRange.start );
  40846. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  40847. for ( i = start, il = end; i < il; i += 3 ) {
  40848. a = i;
  40849. b = i + 1;
  40850. c = i + 2;
  40851. _calculateMorphedAttributeData(
  40852. object,
  40853. material,
  40854. positionAttribute,
  40855. morphPosition,
  40856. morphTargetsRelative,
  40857. a, b, c,
  40858. modifiedPosition
  40859. );
  40860. _calculateMorphedAttributeData(
  40861. object,
  40862. material,
  40863. normalAttribute,
  40864. morphNormal,
  40865. morphTargetsRelative,
  40866. a, b, c,
  40867. modifiedNormal
  40868. );
  40869. }
  40870. }
  40871. }
  40872. var morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  40873. var morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  40874. return {
  40875. positionAttribute: positionAttribute,
  40876. normalAttribute: normalAttribute,
  40877. morphedPositionAttribute: morphedPositionAttribute,
  40878. morphedNormalAttribute: morphedNormalAttribute
  40879. };
  40880. }
  40881. };
  40882. },{}],63:[function(_dereq_,module,exports){
  40883. var createLayout = _dereq_('layout-bmfont-text')
  40884. var inherits = _dereq_('inherits')
  40885. var createIndices = _dereq_('quad-indices')
  40886. var buffer = _dereq_('three-buffer-vertex-data')
  40887. var assign = _dereq_('object-assign')
  40888. var vertices = _dereq_('./lib/vertices')
  40889. var utils = _dereq_('./lib/utils')
  40890. var Base = THREE.BufferGeometry
  40891. module.exports = function createTextGeometry (opt) {
  40892. return new TextGeometry(opt)
  40893. }
  40894. function TextGeometry (opt) {
  40895. Base.call(this)
  40896. if (typeof opt === 'string') {
  40897. opt = { text: opt }
  40898. }
  40899. // use these as default values for any subsequent
  40900. // calls to update()
  40901. this._opt = assign({}, opt)
  40902. // also do an initial setup...
  40903. if (opt) this.update(opt)
  40904. }
  40905. inherits(TextGeometry, Base)
  40906. TextGeometry.prototype.update = function (opt) {
  40907. if (typeof opt === 'string') {
  40908. opt = { text: opt }
  40909. }
  40910. // use constructor defaults
  40911. opt = assign({}, this._opt, opt)
  40912. if (!opt.font) {
  40913. throw new TypeError('must specify a { font } in options')
  40914. }
  40915. this.layout = createLayout(opt)
  40916. // get vec2 texcoords
  40917. var flipY = opt.flipY !== false
  40918. // the desired BMFont data
  40919. var font = opt.font
  40920. // determine texture size from font file
  40921. var texWidth = font.common.scaleW
  40922. var texHeight = font.common.scaleH
  40923. // get visible glyphs
  40924. var glyphs = this.layout.glyphs.filter(function (glyph) {
  40925. var bitmap = glyph.data
  40926. return bitmap.width * bitmap.height > 0
  40927. })
  40928. // provide visible glyphs for convenience
  40929. this.visibleGlyphs = glyphs
  40930. // get common vertex data
  40931. var positions = vertices.positions(glyphs)
  40932. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  40933. var indices = createIndices({
  40934. clockwise: true,
  40935. type: 'uint16',
  40936. count: glyphs.length
  40937. })
  40938. // update vertex data
  40939. buffer.index(this, indices, 1, 'uint16')
  40940. buffer.attr(this, 'position', positions, 2)
  40941. buffer.attr(this, 'uv', uvs, 2)
  40942. // update multipage data
  40943. if (!opt.multipage && 'page' in this.attributes) {
  40944. // disable multipage rendering
  40945. this.removeAttribute('page')
  40946. } else if (opt.multipage) {
  40947. var pages = vertices.pages(glyphs)
  40948. // enable multipage rendering
  40949. buffer.attr(this, 'page', pages, 1)
  40950. }
  40951. }
  40952. TextGeometry.prototype.computeBoundingSphere = function () {
  40953. if (this.boundingSphere === null) {
  40954. this.boundingSphere = new THREE.Sphere()
  40955. }
  40956. var positions = this.attributes.position.array
  40957. var itemSize = this.attributes.position.itemSize
  40958. if (!positions || !itemSize || positions.length < 2) {
  40959. this.boundingSphere.radius = 0
  40960. this.boundingSphere.center.set(0, 0, 0)
  40961. return
  40962. }
  40963. utils.computeSphere(positions, this.boundingSphere)
  40964. if (isNaN(this.boundingSphere.radius)) {
  40965. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  40966. 'Computed radius is NaN. The ' +
  40967. '"position" attribute is likely to have NaN values.')
  40968. }
  40969. }
  40970. TextGeometry.prototype.computeBoundingBox = function () {
  40971. if (this.boundingBox === null) {
  40972. this.boundingBox = new THREE.Box3()
  40973. }
  40974. var bbox = this.boundingBox
  40975. var positions = this.attributes.position.array
  40976. var itemSize = this.attributes.position.itemSize
  40977. if (!positions || !itemSize || positions.length < 2) {
  40978. bbox.makeEmpty()
  40979. return
  40980. }
  40981. utils.computeBox(positions, bbox)
  40982. }
  40983. },{"./lib/utils":64,"./lib/vertices":65,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":66}],64:[function(_dereq_,module,exports){
  40984. var itemSize = 2
  40985. var box = { min: [0, 0], max: [0, 0] }
  40986. function bounds (positions) {
  40987. var count = positions.length / itemSize
  40988. box.min[0] = positions[0]
  40989. box.min[1] = positions[1]
  40990. box.max[0] = positions[0]
  40991. box.max[1] = positions[1]
  40992. for (var i = 0; i < count; i++) {
  40993. var x = positions[i * itemSize + 0]
  40994. var y = positions[i * itemSize + 1]
  40995. box.min[0] = Math.min(x, box.min[0])
  40996. box.min[1] = Math.min(y, box.min[1])
  40997. box.max[0] = Math.max(x, box.max[0])
  40998. box.max[1] = Math.max(y, box.max[1])
  40999. }
  41000. }
  41001. module.exports.computeBox = function (positions, output) {
  41002. bounds(positions)
  41003. output.min.set(box.min[0], box.min[1], 0)
  41004. output.max.set(box.max[0], box.max[1], 0)
  41005. }
  41006. module.exports.computeSphere = function (positions, output) {
  41007. bounds(positions)
  41008. var minX = box.min[0]
  41009. var minY = box.min[1]
  41010. var maxX = box.max[0]
  41011. var maxY = box.max[1]
  41012. var width = maxX - minX
  41013. var height = maxY - minY
  41014. var length = Math.sqrt(width * width + height * height)
  41015. output.center.set(minX + width / 2, minY + height / 2, 0)
  41016. output.radius = length / 2
  41017. }
  41018. },{}],65:[function(_dereq_,module,exports){
  41019. module.exports.pages = function pages (glyphs) {
  41020. var pages = new Float32Array(glyphs.length * 4 * 1)
  41021. var i = 0
  41022. glyphs.forEach(function (glyph) {
  41023. var id = glyph.data.page || 0
  41024. pages[i++] = id
  41025. pages[i++] = id
  41026. pages[i++] = id
  41027. pages[i++] = id
  41028. })
  41029. return pages
  41030. }
  41031. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  41032. var uvs = new Float32Array(glyphs.length * 4 * 2)
  41033. var i = 0
  41034. glyphs.forEach(function (glyph) {
  41035. var bitmap = glyph.data
  41036. var bw = (bitmap.x + bitmap.width)
  41037. var bh = (bitmap.y + bitmap.height)
  41038. // top left position
  41039. var u0 = bitmap.x / texWidth
  41040. var v1 = bitmap.y / texHeight
  41041. var u1 = bw / texWidth
  41042. var v0 = bh / texHeight
  41043. if (flipY) {
  41044. v1 = (texHeight - bitmap.y) / texHeight
  41045. v0 = (texHeight - bh) / texHeight
  41046. }
  41047. // BL
  41048. uvs[i++] = u0
  41049. uvs[i++] = v1
  41050. // TL
  41051. uvs[i++] = u0
  41052. uvs[i++] = v0
  41053. // TR
  41054. uvs[i++] = u1
  41055. uvs[i++] = v0
  41056. // BR
  41057. uvs[i++] = u1
  41058. uvs[i++] = v1
  41059. })
  41060. return uvs
  41061. }
  41062. module.exports.positions = function positions (glyphs) {
  41063. var positions = new Float32Array(glyphs.length * 4 * 2)
  41064. var i = 0
  41065. glyphs.forEach(function (glyph) {
  41066. var bitmap = glyph.data
  41067. // bottom left position
  41068. var x = glyph.position[0] + bitmap.xoffset
  41069. var y = glyph.position[1] + bitmap.yoffset
  41070. // quad size
  41071. var w = bitmap.width
  41072. var h = bitmap.height
  41073. // BL
  41074. positions[i++] = x
  41075. positions[i++] = y
  41076. // TL
  41077. positions[i++] = x
  41078. positions[i++] = y + h
  41079. // TR
  41080. positions[i++] = x + w
  41081. positions[i++] = y + h
  41082. // BR
  41083. positions[i++] = x + w
  41084. positions[i++] = y
  41085. })
  41086. return positions
  41087. }
  41088. },{}],66:[function(_dereq_,module,exports){
  41089. var flatten = _dereq_('flatten-vertex-data')
  41090. var warned = false;
  41091. module.exports.attr = setAttribute
  41092. module.exports.index = setIndex
  41093. function setIndex (geometry, data, itemSize, dtype) {
  41094. if (typeof itemSize !== 'number') itemSize = 1
  41095. if (typeof dtype !== 'string') dtype = 'uint16'
  41096. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  41097. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  41098. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41099. if (newAttrib) {
  41100. if (isR69) geometry.addAttribute('index', newAttrib)
  41101. else geometry.index = newAttrib
  41102. }
  41103. }
  41104. function setAttribute (geometry, key, data, itemSize, dtype) {
  41105. if (typeof itemSize !== 'number') itemSize = 3
  41106. if (typeof dtype !== 'string') dtype = 'float32'
  41107. if (Array.isArray(data) &&
  41108. Array.isArray(data[0]) &&
  41109. data[0].length !== itemSize) {
  41110. throw new Error('Nested vertex array has unexpected size; expected ' +
  41111. itemSize + ' but found ' + data[0].length)
  41112. }
  41113. var attrib = geometry.getAttribute(key)
  41114. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41115. geometry.setAttribute(key, newAttrib)
  41116. }
  41117. function updateAttribute (attrib, data, itemSize, dtype) {
  41118. data = data || []
  41119. // create a new array with desired type
  41120. data = flatten(data, dtype)
  41121. attrib = new THREE.BufferAttribute(data, itemSize);
  41122. attrib.itemSize = itemSize;
  41123. attrib.needsUpdate = true;
  41124. return attrib
  41125. }
  41126. // Test whether the attribute needs to be re-created,
  41127. // returns false if we can re-use it as-is.
  41128. function rebuildAttribute (attrib, data, itemSize) {
  41129. if (attrib.itemSize !== itemSize) return true
  41130. if (!attrib.array) return true
  41131. var attribLength = attrib.array.length
  41132. if (Array.isArray(data) && Array.isArray(data[0])) {
  41133. // [ [ x, y, z ] ]
  41134. return attribLength !== data.length * itemSize
  41135. } else {
  41136. // [ x, y, z ]
  41137. return attribLength !== data.length
  41138. }
  41139. return false
  41140. }
  41141. },{"flatten-vertex-data":23}],67:[function(_dereq_,module,exports){
  41142. (function (setImmediate,clearImmediate){
  41143. var nextTick = _dereq_('process/browser.js').nextTick;
  41144. var apply = Function.prototype.apply;
  41145. var slice = Array.prototype.slice;
  41146. var immediateIds = {};
  41147. var nextImmediateId = 0;
  41148. // DOM APIs, for completeness
  41149. exports.setTimeout = function() {
  41150. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  41151. };
  41152. exports.setInterval = function() {
  41153. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  41154. };
  41155. exports.clearTimeout =
  41156. exports.clearInterval = function(timeout) { timeout.close(); };
  41157. function Timeout(id, clearFn) {
  41158. this._id = id;
  41159. this._clearFn = clearFn;
  41160. }
  41161. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  41162. Timeout.prototype.close = function() {
  41163. this._clearFn.call(window, this._id);
  41164. };
  41165. // Does not start the time, just sets up the members needed.
  41166. exports.enroll = function(item, msecs) {
  41167. clearTimeout(item._idleTimeoutId);
  41168. item._idleTimeout = msecs;
  41169. };
  41170. exports.unenroll = function(item) {
  41171. clearTimeout(item._idleTimeoutId);
  41172. item._idleTimeout = -1;
  41173. };
  41174. exports._unrefActive = exports.active = function(item) {
  41175. clearTimeout(item._idleTimeoutId);
  41176. var msecs = item._idleTimeout;
  41177. if (msecs >= 0) {
  41178. item._idleTimeoutId = setTimeout(function onTimeout() {
  41179. if (item._onTimeout)
  41180. item._onTimeout();
  41181. }, msecs);
  41182. }
  41183. };
  41184. // That's not how node.js implements it but the exposed api is the same.
  41185. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  41186. var id = nextImmediateId++;
  41187. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  41188. immediateIds[id] = true;
  41189. nextTick(function onNextTick() {
  41190. if (immediateIds[id]) {
  41191. // fn.call() is faster so we optimize for the common use-case
  41192. // @see http://jsperf.com/call-apply-segu
  41193. if (args) {
  41194. fn.apply(null, args);
  41195. } else {
  41196. fn.call(null);
  41197. }
  41198. // Prevent ids from leaking
  41199. exports.clearImmediate(id);
  41200. }
  41201. });
  41202. return id;
  41203. };
  41204. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  41205. delete immediateIds[id];
  41206. };
  41207. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  41208. },{"process/browser.js":49,"timers":67}],68:[function(_dereq_,module,exports){
  41209. (function (global){
  41210. /**
  41211. * @license
  41212. * webvr-polyfill
  41213. * Copyright (c) 2015-2017 Google
  41214. * Licensed under the Apache License, Version 2.0 (the "License");
  41215. * you may not use this file except in compliance with the License.
  41216. * You may obtain a copy of the License at
  41217. *
  41218. * http://www.apache.org/licenses/LICENSE-2.0
  41219. *
  41220. * Unless required by applicable law or agreed to in writing, software
  41221. * distributed under the License is distributed on an "AS IS" BASIS,
  41222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41223. * See the License for the specific language governing permissions and
  41224. * limitations under the License.
  41225. */
  41226. /**
  41227. * @license
  41228. * cardboard-vr-display
  41229. * Copyright (c) 2015-2017 Google
  41230. * Licensed under the Apache License, Version 2.0 (the "License");
  41231. * you may not use this file except in compliance with the License.
  41232. * You may obtain a copy of the License at
  41233. *
  41234. * http://www.apache.org/licenses/LICENSE-2.0
  41235. *
  41236. * Unless required by applicable law or agreed to in writing, software
  41237. * distributed under the License is distributed on an "AS IS" BASIS,
  41238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41239. * See the License for the specific language governing permissions and
  41240. * limitations under the License.
  41241. */
  41242. /**
  41243. * @license
  41244. * webvr-polyfill-dpdb
  41245. * Copyright (c) 2017 Google
  41246. * Licensed under the Apache License, Version 2.0 (the "License");
  41247. * you may not use this file except in compliance with the License.
  41248. * You may obtain a copy of the License at
  41249. *
  41250. * http://www.apache.org/licenses/LICENSE-2.0
  41251. *
  41252. * Unless required by applicable law or agreed to in writing, software
  41253. * distributed under the License is distributed on an "AS IS" BASIS,
  41254. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41255. * See the License for the specific language governing permissions and
  41256. * limitations under the License.
  41257. */
  41258. /**
  41259. * @license
  41260. * wglu-preserve-state
  41261. * Copyright (c) 2016, Brandon Jones.
  41262. *
  41263. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41264. * of this software and associated documentation files (the "Software"), to deal
  41265. * in the Software without restriction, including without limitation the rights
  41266. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41267. * copies of the Software, and to permit persons to whom the Software is
  41268. * furnished to do so, subject to the following conditions:
  41269. *
  41270. * The above copyright notice and this permission notice shall be included in
  41271. * all copies or substantial portions of the Software.
  41272. *
  41273. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41274. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41275. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41276. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41277. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41278. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41279. * THE SOFTWARE.
  41280. */
  41281. /**
  41282. * @license
  41283. * nosleep.js
  41284. * Copyright (c) 2017, Rich Tibbett
  41285. *
  41286. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41287. * of this software and associated documentation files (the "Software"), to deal
  41288. * in the Software without restriction, including without limitation the rights
  41289. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41290. * copies of the Software, and to permit persons to whom the Software is
  41291. * furnished to do so, subject to the following conditions:
  41292. *
  41293. * The above copyright notice and this permission notice shall be included in
  41294. * all copies or substantial portions of the Software.
  41295. *
  41296. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41297. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41298. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41299. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41300. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41301. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41302. * THE SOFTWARE.
  41303. */
  41304. (function (global, factory) {
  41305. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  41306. typeof define === 'function' && define.amd ? define(factory) :
  41307. (global.WebVRPolyfill = factory());
  41308. }(this, (function () { 'use strict';
  41309. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  41310. function unwrapExports (x) {
  41311. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  41312. }
  41313. function createCommonjsModule(fn, module) {
  41314. return module = { exports: {} }, fn(module, module.exports), module.exports;
  41315. }
  41316. var isMobile = function isMobile() {
  41317. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  41318. );
  41319. };
  41320. var copyArray = function copyArray(source, dest) {
  41321. for (var i = 0, n = source.length; i < n; i++) {
  41322. dest[i] = source[i];
  41323. }
  41324. };
  41325. var extend = function extend(dest, src) {
  41326. for (var key in src) {
  41327. if (src.hasOwnProperty(key)) {
  41328. dest[key] = src[key];
  41329. }
  41330. }
  41331. return dest;
  41332. };
  41333. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  41334. /**
  41335. * @license
  41336. * cardboard-vr-display
  41337. * Copyright (c) 2015-2017 Google
  41338. * Licensed under the Apache License, Version 2.0 (the "License");
  41339. * you may not use this file except in compliance with the License.
  41340. * You may obtain a copy of the License at
  41341. *
  41342. * http://www.apache.org/licenses/LICENSE-2.0
  41343. *
  41344. * Unless required by applicable law or agreed to in writing, software
  41345. * distributed under the License is distributed on an "AS IS" BASIS,
  41346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41347. * See the License for the specific language governing permissions and
  41348. * limitations under the License.
  41349. */
  41350. /**
  41351. * @license
  41352. * gl-preserve-state
  41353. * Copyright (c) 2016, Brandon Jones.
  41354. *
  41355. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41356. * of this software and associated documentation files (the "Software"), to deal
  41357. * in the Software without restriction, including without limitation the rights
  41358. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41359. * copies of the Software, and to permit persons to whom the Software is
  41360. * furnished to do so, subject to the following conditions:
  41361. *
  41362. * The above copyright notice and this permission notice shall be included in
  41363. * all copies or substantial portions of the Software.
  41364. *
  41365. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41366. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41367. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41368. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41369. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41370. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41371. * THE SOFTWARE.
  41372. */
  41373. /**
  41374. * @license
  41375. * webvr-polyfill-dpdb
  41376. * Copyright (c) 2015-2017 Google
  41377. * Licensed under the Apache License, Version 2.0 (the "License");
  41378. * you may not use this file except in compliance with the License.
  41379. * You may obtain a copy of the License at
  41380. *
  41381. * http://www.apache.org/licenses/LICENSE-2.0
  41382. *
  41383. * Unless required by applicable law or agreed to in writing, software
  41384. * distributed under the License is distributed on an "AS IS" BASIS,
  41385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41386. * See the License for the specific language governing permissions and
  41387. * limitations under the License.
  41388. */
  41389. /**
  41390. * @license
  41391. * nosleep.js
  41392. * Copyright (c) 2017, Rich Tibbett
  41393. *
  41394. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41395. * of this software and associated documentation files (the "Software"), to deal
  41396. * in the Software without restriction, including without limitation the rights
  41397. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41398. * copies of the Software, and to permit persons to whom the Software is
  41399. * furnished to do so, subject to the following conditions:
  41400. *
  41401. * The above copyright notice and this permission notice shall be included in
  41402. * all copies or substantial portions of the Software.
  41403. *
  41404. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41405. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41406. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41407. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41408. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41409. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41410. * THE SOFTWARE.
  41411. */
  41412. (function (global, factory) {
  41413. module.exports = factory();
  41414. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  41415. if (!(instance instanceof Constructor)) {
  41416. throw new TypeError("Cannot call a class as a function");
  41417. }
  41418. };
  41419. var createClass = function () {
  41420. function defineProperties(target, props) {
  41421. for (var i = 0; i < props.length; i++) {
  41422. var descriptor = props[i];
  41423. descriptor.enumerable = descriptor.enumerable || false;
  41424. descriptor.configurable = true;
  41425. if ("value" in descriptor) descriptor.writable = true;
  41426. Object.defineProperty(target, descriptor.key, descriptor);
  41427. }
  41428. }
  41429. return function (Constructor, protoProps, staticProps) {
  41430. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  41431. if (staticProps) defineProperties(Constructor, staticProps);
  41432. return Constructor;
  41433. };
  41434. }();
  41435. var slicedToArray = function () {
  41436. function sliceIterator(arr, i) {
  41437. var _arr = [];
  41438. var _n = true;
  41439. var _d = false;
  41440. var _e = undefined;
  41441. try {
  41442. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  41443. _arr.push(_s.value);
  41444. if (i && _arr.length === i) break;
  41445. }
  41446. } catch (err) {
  41447. _d = true;
  41448. _e = err;
  41449. } finally {
  41450. try {
  41451. if (!_n && _i["return"]) _i["return"]();
  41452. } finally {
  41453. if (_d) throw _e;
  41454. }
  41455. }
  41456. return _arr;
  41457. }
  41458. return function (arr, i) {
  41459. if (Array.isArray(arr)) {
  41460. return arr;
  41461. } else if (Symbol.iterator in Object(arr)) {
  41462. return sliceIterator(arr, i);
  41463. } else {
  41464. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  41465. }
  41466. };
  41467. }();
  41468. var MIN_TIMESTEP = 0.001;
  41469. var MAX_TIMESTEP = 1;
  41470. var dataUri = function dataUri(mimeType, svg) {
  41471. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  41472. };
  41473. var lerp = function lerp(a, b, t) {
  41474. return a + (b - a) * t;
  41475. };
  41476. var isIOS = function () {
  41477. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41478. return function () {
  41479. return isIOS;
  41480. };
  41481. }();
  41482. var isWebViewAndroid = function () {
  41483. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  41484. return function () {
  41485. return isWebViewAndroid;
  41486. };
  41487. }();
  41488. var isSafari = function () {
  41489. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41490. return function () {
  41491. return isSafari;
  41492. };
  41493. }();
  41494. var isFirefoxAndroid = function () {
  41495. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  41496. return function () {
  41497. return isFirefoxAndroid;
  41498. };
  41499. }();
  41500. var getChromeVersion = function () {
  41501. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  41502. var value = match ? parseInt(match[1], 10) : null;
  41503. return function () {
  41504. return value;
  41505. };
  41506. }();
  41507. var isSafariWithoutDeviceMotion = function () {
  41508. var value = false;
  41509. value = isIOS() && isSafari() && navigator.userAgent.indexOf('13_4') !== -1;
  41510. return function () {
  41511. return value;
  41512. };
  41513. }();
  41514. var isChromeWithoutDeviceMotion = function () {
  41515. var value = false;
  41516. if (getChromeVersion() === 65) {
  41517. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  41518. if (match) {
  41519. var _match$1$split = match[1].split('.'),
  41520. _match$1$split2 = slicedToArray(_match$1$split, 4),
  41521. major = _match$1$split2[0],
  41522. minor = _match$1$split2[1],
  41523. branch = _match$1$split2[2],
  41524. build = _match$1$split2[3];
  41525. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  41526. }
  41527. }
  41528. return function () {
  41529. return value;
  41530. };
  41531. }();
  41532. var isR7 = function () {
  41533. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  41534. return function () {
  41535. return isR7;
  41536. };
  41537. }();
  41538. var isLandscapeMode = function isLandscapeMode() {
  41539. var rtn = window.orientation == 90 || window.orientation == -90;
  41540. return isR7() ? !rtn : rtn;
  41541. };
  41542. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  41543. if (isNaN(timestampDeltaS)) {
  41544. return false;
  41545. }
  41546. if (timestampDeltaS <= MIN_TIMESTEP) {
  41547. return false;
  41548. }
  41549. if (timestampDeltaS > MAX_TIMESTEP) {
  41550. return false;
  41551. }
  41552. return true;
  41553. };
  41554. var getScreenWidth = function getScreenWidth() {
  41555. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41556. };
  41557. var getScreenHeight = function getScreenHeight() {
  41558. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41559. };
  41560. var requestFullscreen = function requestFullscreen(element) {
  41561. if (isWebViewAndroid()) {
  41562. return false;
  41563. }
  41564. if (element.requestFullscreen) {
  41565. element.requestFullscreen();
  41566. } else if (element.webkitRequestFullscreen) {
  41567. element.webkitRequestFullscreen();
  41568. } else if (element.mozRequestFullScreen) {
  41569. element.mozRequestFullScreen();
  41570. } else if (element.msRequestFullscreen) {
  41571. element.msRequestFullscreen();
  41572. } else {
  41573. return false;
  41574. }
  41575. return true;
  41576. };
  41577. var exitFullscreen = function exitFullscreen() {
  41578. if (document.exitFullscreen) {
  41579. document.exitFullscreen();
  41580. } else if (document.webkitExitFullscreen) {
  41581. document.webkitExitFullscreen();
  41582. } else if (document.mozCancelFullScreen) {
  41583. document.mozCancelFullScreen();
  41584. } else if (document.msExitFullscreen) {
  41585. document.msExitFullscreen();
  41586. } else {
  41587. return false;
  41588. }
  41589. return true;
  41590. };
  41591. var getFullscreenElement = function getFullscreenElement() {
  41592. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  41593. };
  41594. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  41595. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41596. gl.shaderSource(vertexShader, vertexSource);
  41597. gl.compileShader(vertexShader);
  41598. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41599. gl.shaderSource(fragmentShader, fragmentSource);
  41600. gl.compileShader(fragmentShader);
  41601. var program = gl.createProgram();
  41602. gl.attachShader(program, vertexShader);
  41603. gl.attachShader(program, fragmentShader);
  41604. for (var attribName in attribLocationMap) {
  41605. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41606. }gl.linkProgram(program);
  41607. gl.deleteShader(vertexShader);
  41608. gl.deleteShader(fragmentShader);
  41609. return program;
  41610. };
  41611. var getProgramUniforms = function getProgramUniforms(gl, program) {
  41612. var uniforms = {};
  41613. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41614. var uniformName = '';
  41615. for (var i = 0; i < uniformCount; i++) {
  41616. var uniformInfo = gl.getActiveUniform(program, i);
  41617. uniformName = uniformInfo.name.replace('[0]', '');
  41618. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41619. }
  41620. return uniforms;
  41621. };
  41622. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  41623. var lr = 1 / (left - right),
  41624. bt = 1 / (bottom - top),
  41625. nf = 1 / (near - far);
  41626. out[0] = -2 * lr;
  41627. out[1] = 0;
  41628. out[2] = 0;
  41629. out[3] = 0;
  41630. out[4] = 0;
  41631. out[5] = -2 * bt;
  41632. out[6] = 0;
  41633. out[7] = 0;
  41634. out[8] = 0;
  41635. out[9] = 0;
  41636. out[10] = 2 * nf;
  41637. out[11] = 0;
  41638. out[12] = (left + right) * lr;
  41639. out[13] = (top + bottom) * bt;
  41640. out[14] = (far + near) * nf;
  41641. out[15] = 1;
  41642. return out;
  41643. };
  41644. var isMobile = function isMobile() {
  41645. var check = false;
  41646. (function (a) {
  41647. 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;
  41648. })(navigator.userAgent || navigator.vendor || window.opera);
  41649. return check;
  41650. };
  41651. var extend = function extend(dest, src) {
  41652. for (var key in src) {
  41653. if (src.hasOwnProperty(key)) {
  41654. dest[key] = src[key];
  41655. }
  41656. }
  41657. return dest;
  41658. };
  41659. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  41660. if (isIOS()) {
  41661. var width = canvas.style.width;
  41662. var height = canvas.style.height;
  41663. canvas.style.width = parseInt(width) + 1 + 'px';
  41664. canvas.style.height = parseInt(height) + 'px';
  41665. setTimeout(function () {
  41666. canvas.style.width = width;
  41667. canvas.style.height = height;
  41668. }, 100);
  41669. }
  41670. window.canvas = canvas;
  41671. };
  41672. var frameDataFromPose = function () {
  41673. var piOver180 = Math.PI / 180.0;
  41674. var rad45 = Math.PI * 0.25;
  41675. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41676. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  41677. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  41678. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  41679. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  41680. xScale = 2.0 / (leftTan + rightTan),
  41681. yScale = 2.0 / (upTan + downTan);
  41682. out[0] = xScale;
  41683. out[1] = 0.0;
  41684. out[2] = 0.0;
  41685. out[3] = 0.0;
  41686. out[4] = 0.0;
  41687. out[5] = yScale;
  41688. out[6] = 0.0;
  41689. out[7] = 0.0;
  41690. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41691. out[9] = (upTan - downTan) * yScale * 0.5;
  41692. out[10] = far / (near - far);
  41693. out[11] = -1.0;
  41694. out[12] = 0.0;
  41695. out[13] = 0.0;
  41696. out[14] = far * near / (near - far);
  41697. out[15] = 0.0;
  41698. return out;
  41699. }
  41700. function mat4_fromRotationTranslation(out, q, v) {
  41701. var x = q[0],
  41702. y = q[1],
  41703. z = q[2],
  41704. w = q[3],
  41705. x2 = x + x,
  41706. y2 = y + y,
  41707. z2 = z + z,
  41708. xx = x * x2,
  41709. xy = x * y2,
  41710. xz = x * z2,
  41711. yy = y * y2,
  41712. yz = y * z2,
  41713. zz = z * z2,
  41714. wx = w * x2,
  41715. wy = w * y2,
  41716. wz = w * z2;
  41717. out[0] = 1 - (yy + zz);
  41718. out[1] = xy + wz;
  41719. out[2] = xz - wy;
  41720. out[3] = 0;
  41721. out[4] = xy - wz;
  41722. out[5] = 1 - (xx + zz);
  41723. out[6] = yz + wx;
  41724. out[7] = 0;
  41725. out[8] = xz + wy;
  41726. out[9] = yz - wx;
  41727. out[10] = 1 - (xx + yy);
  41728. out[11] = 0;
  41729. out[12] = v[0];
  41730. out[13] = v[1];
  41731. out[14] = v[2];
  41732. out[15] = 1;
  41733. return out;
  41734. }
  41735. function mat4_translate(out, a, v) {
  41736. var x = v[0],
  41737. y = v[1],
  41738. z = v[2],
  41739. a00,
  41740. a01,
  41741. a02,
  41742. a03,
  41743. a10,
  41744. a11,
  41745. a12,
  41746. a13,
  41747. a20,
  41748. a21,
  41749. a22,
  41750. a23;
  41751. if (a === out) {
  41752. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41753. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41754. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41755. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41756. } else {
  41757. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  41758. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  41759. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  41760. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  41761. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  41762. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  41763. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41764. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41765. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41766. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41767. }
  41768. return out;
  41769. }
  41770. function mat4_invert(out, a) {
  41771. var a00 = a[0],
  41772. a01 = a[1],
  41773. a02 = a[2],
  41774. a03 = a[3],
  41775. a10 = a[4],
  41776. a11 = a[5],
  41777. a12 = a[6],
  41778. a13 = a[7],
  41779. a20 = a[8],
  41780. a21 = a[9],
  41781. a22 = a[10],
  41782. a23 = a[11],
  41783. a30 = a[12],
  41784. a31 = a[13],
  41785. a32 = a[14],
  41786. a33 = a[15],
  41787. b00 = a00 * a11 - a01 * a10,
  41788. b01 = a00 * a12 - a02 * a10,
  41789. b02 = a00 * a13 - a03 * a10,
  41790. b03 = a01 * a12 - a02 * a11,
  41791. b04 = a01 * a13 - a03 * a11,
  41792. b05 = a02 * a13 - a03 * a12,
  41793. b06 = a20 * a31 - a21 * a30,
  41794. b07 = a20 * a32 - a22 * a30,
  41795. b08 = a20 * a33 - a23 * a30,
  41796. b09 = a21 * a32 - a22 * a31,
  41797. b10 = a21 * a33 - a23 * a31,
  41798. b11 = a22 * a33 - a23 * a32,
  41799. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41800. if (!det) {
  41801. return null;
  41802. }
  41803. det = 1.0 / det;
  41804. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41805. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41806. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41807. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41808. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41809. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41810. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41811. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41812. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41813. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41814. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41815. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41816. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41817. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41818. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41819. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41820. return out;
  41821. }
  41822. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41823. var defaultPosition = new Float32Array([0, 0, 0]);
  41824. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  41825. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  41826. var orientation = pose.orientation || defaultOrientation;
  41827. var position = pose.position || defaultPosition;
  41828. mat4_fromRotationTranslation(view, orientation, position);
  41829. if (offset) mat4_translate(view, view, offset);
  41830. mat4_invert(view, view);
  41831. }
  41832. return function (frameData, pose, vrDisplay) {
  41833. if (!frameData || !pose) return false;
  41834. frameData.pose = pose;
  41835. frameData.timestamp = pose.timestamp;
  41836. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  41837. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  41838. return true;
  41839. };
  41840. }();
  41841. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  41842. var isFramed = window.self !== window.top;
  41843. var refOrigin = getOriginFromUrl(document.referrer);
  41844. var thisOrigin = getOriginFromUrl(window.location.href);
  41845. return isFramed && refOrigin !== thisOrigin;
  41846. };
  41847. var getOriginFromUrl = function getOriginFromUrl(url) {
  41848. var domainIdx;
  41849. var protoSepIdx = url.indexOf("://");
  41850. if (protoSepIdx !== -1) {
  41851. domainIdx = protoSepIdx + 3;
  41852. } else {
  41853. domainIdx = 0;
  41854. }
  41855. var domainEndIdx = url.indexOf('/', domainIdx);
  41856. if (domainEndIdx === -1) {
  41857. domainEndIdx = url.length;
  41858. }
  41859. return url.substring(0, domainEndIdx);
  41860. };
  41861. var getQuaternionAngle = function getQuaternionAngle(quat) {
  41862. if (quat.w > 1) {
  41863. console.warn('getQuaternionAngle: w > 1');
  41864. return 0;
  41865. }
  41866. var angle = 2 * Math.acos(quat.w);
  41867. return angle;
  41868. };
  41869. var warnOnce = function () {
  41870. var observedWarnings = {};
  41871. return function (key, message) {
  41872. if (observedWarnings[key] === undefined) {
  41873. console.warn('webvr-polyfill: ' + message);
  41874. observedWarnings[key] = true;
  41875. }
  41876. };
  41877. }();
  41878. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  41879. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  41880. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  41881. };
  41882. function WGLUPreserveGLState(gl, bindings, callback) {
  41883. if (!bindings) {
  41884. callback(gl);
  41885. return;
  41886. }
  41887. var boundValues = [];
  41888. var activeTexture = null;
  41889. for (var i = 0; i < bindings.length; ++i) {
  41890. var binding = bindings[i];
  41891. switch (binding) {
  41892. case gl.TEXTURE_BINDING_2D:
  41893. case gl.TEXTURE_BINDING_CUBE_MAP:
  41894. var textureUnit = bindings[++i];
  41895. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  41896. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  41897. boundValues.push(null, null);
  41898. break;
  41899. }
  41900. if (!activeTexture) {
  41901. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41902. }
  41903. gl.activeTexture(textureUnit);
  41904. boundValues.push(gl.getParameter(binding), null);
  41905. break;
  41906. case gl.ACTIVE_TEXTURE:
  41907. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41908. boundValues.push(null);
  41909. break;
  41910. default:
  41911. boundValues.push(gl.getParameter(binding));
  41912. break;
  41913. }
  41914. }
  41915. callback(gl);
  41916. for (var i = 0; i < bindings.length; ++i) {
  41917. var binding = bindings[i];
  41918. var boundValue = boundValues[i];
  41919. switch (binding) {
  41920. case gl.ACTIVE_TEXTURE:
  41921. break;
  41922. case gl.ARRAY_BUFFER_BINDING:
  41923. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  41924. break;
  41925. case gl.COLOR_CLEAR_VALUE:
  41926. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41927. break;
  41928. case gl.COLOR_WRITEMASK:
  41929. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41930. break;
  41931. case gl.CURRENT_PROGRAM:
  41932. gl.useProgram(boundValue);
  41933. break;
  41934. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  41935. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  41936. break;
  41937. case gl.FRAMEBUFFER_BINDING:
  41938. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  41939. break;
  41940. case gl.RENDERBUFFER_BINDING:
  41941. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  41942. break;
  41943. case gl.TEXTURE_BINDING_2D:
  41944. var textureUnit = bindings[++i];
  41945. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  41946. break;
  41947. gl.activeTexture(textureUnit);
  41948. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  41949. break;
  41950. case gl.TEXTURE_BINDING_CUBE_MAP:
  41951. var textureUnit = bindings[++i];
  41952. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  41953. break;
  41954. gl.activeTexture(textureUnit);
  41955. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  41956. break;
  41957. case gl.VIEWPORT:
  41958. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41959. break;
  41960. case gl.BLEND:
  41961. case gl.CULL_FACE:
  41962. case gl.DEPTH_TEST:
  41963. case gl.SCISSOR_TEST:
  41964. case gl.STENCIL_TEST:
  41965. if (boundValue) {
  41966. gl.enable(binding);
  41967. } else {
  41968. gl.disable(binding);
  41969. }
  41970. break;
  41971. default:
  41972. console.log("No GL restore behavior for 0x" + binding.toString(16));
  41973. break;
  41974. }
  41975. if (activeTexture) {
  41976. gl.activeTexture(activeTexture);
  41977. }
  41978. }
  41979. }
  41980. var glPreserveState = WGLUPreserveGLState;
  41981. 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');
  41982. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  41983. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  41984. this.gl = gl;
  41985. this.cardboardUI = cardboardUI;
  41986. this.bufferScale = bufferScale;
  41987. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  41988. this.ctxAttribs = gl.getContextAttributes();
  41989. this.instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  41990. this.meshWidth = 20;
  41991. this.meshHeight = 20;
  41992. this.bufferWidth = gl.drawingBufferWidth;
  41993. this.bufferHeight = gl.drawingBufferHeight;
  41994. this.realBindFramebuffer = gl.bindFramebuffer;
  41995. this.realEnable = gl.enable;
  41996. this.realDisable = gl.disable;
  41997. this.realColorMask = gl.colorMask;
  41998. this.realClearColor = gl.clearColor;
  41999. this.realViewport = gl.viewport;
  42000. if (!isIOS()) {
  42001. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  42002. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  42003. }
  42004. this.isPatched = false;
  42005. this.lastBoundFramebuffer = null;
  42006. this.cullFace = false;
  42007. this.depthTest = false;
  42008. this.blend = false;
  42009. this.scissorTest = false;
  42010. this.stencilTest = false;
  42011. this.viewport = [0, 0, 0, 0];
  42012. this.colorMask = [true, true, true, true];
  42013. this.clearColor = [0, 0, 0, 0];
  42014. this.attribs = {
  42015. position: 0,
  42016. texCoord: 1
  42017. };
  42018. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  42019. this.uniforms = getProgramUniforms(gl, this.program);
  42020. this.viewportOffsetScale = new Float32Array(8);
  42021. this.setTextureBounds();
  42022. this.vertexBuffer = gl.createBuffer();
  42023. this.indexBuffer = gl.createBuffer();
  42024. this.indexCount = 0;
  42025. this.renderTarget = gl.createTexture();
  42026. this.framebuffer = gl.createFramebuffer();
  42027. this.depthStencilBuffer = null;
  42028. this.depthBuffer = null;
  42029. this.stencilBuffer = null;
  42030. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  42031. this.depthStencilBuffer = gl.createRenderbuffer();
  42032. } else if (this.ctxAttribs.depth) {
  42033. this.depthBuffer = gl.createRenderbuffer();
  42034. } else if (this.ctxAttribs.stencil) {
  42035. this.stencilBuffer = gl.createRenderbuffer();
  42036. }
  42037. this.patch();
  42038. this.onResize();
  42039. }
  42040. CardboardDistorter.prototype.destroy = function () {
  42041. var gl = this.gl;
  42042. this.unpatch();
  42043. gl.deleteProgram(this.program);
  42044. gl.deleteBuffer(this.vertexBuffer);
  42045. gl.deleteBuffer(this.indexBuffer);
  42046. gl.deleteTexture(this.renderTarget);
  42047. gl.deleteFramebuffer(this.framebuffer);
  42048. if (this.depthStencilBuffer) {
  42049. gl.deleteRenderbuffer(this.depthStencilBuffer);
  42050. }
  42051. if (this.depthBuffer) {
  42052. gl.deleteRenderbuffer(this.depthBuffer);
  42053. }
  42054. if (this.stencilBuffer) {
  42055. gl.deleteRenderbuffer(this.stencilBuffer);
  42056. }
  42057. if (this.cardboardUI) {
  42058. this.cardboardUI.destroy();
  42059. }
  42060. };
  42061. CardboardDistorter.prototype.onResize = function () {
  42062. var gl = this.gl;
  42063. var self = this;
  42064. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  42065. glPreserveState(gl, glState, function (gl) {
  42066. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42067. if (self.scissorTest) {
  42068. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42069. }
  42070. self.realColorMask.call(gl, true, true, true, true);
  42071. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42072. self.realClearColor.call(gl, 0, 0, 0, 1);
  42073. gl.clear(gl.COLOR_BUFFER_BIT);
  42074. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  42075. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42076. 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);
  42077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  42078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  42079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  42080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  42081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  42082. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  42083. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  42084. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  42085. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  42086. } else if (self.ctxAttribs.depth) {
  42087. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  42088. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  42089. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  42090. } else if (self.ctxAttribs.stencil) {
  42091. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  42092. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  42093. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  42094. }
  42095. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  42096. console.error('Framebuffer incomplete!');
  42097. }
  42098. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42099. if (self.scissorTest) {
  42100. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42101. }
  42102. self.realColorMask.apply(gl, self.colorMask);
  42103. self.realViewport.apply(gl, self.viewport);
  42104. self.realClearColor.apply(gl, self.clearColor);
  42105. });
  42106. if (this.cardboardUI) {
  42107. this.cardboardUI.onResize();
  42108. }
  42109. };
  42110. CardboardDistorter.prototype.patch = function () {
  42111. if (this.isPatched) {
  42112. return;
  42113. }
  42114. var self = this;
  42115. var canvas = this.gl.canvas;
  42116. var gl = this.gl;
  42117. if (!isIOS()) {
  42118. canvas.width = getScreenWidth() * this.bufferScale;
  42119. canvas.height = getScreenHeight() * this.bufferScale;
  42120. Object.defineProperty(canvas, 'width', {
  42121. configurable: true,
  42122. enumerable: true,
  42123. get: function get() {
  42124. return self.bufferWidth;
  42125. },
  42126. set: function set(value) {
  42127. self.bufferWidth = value;
  42128. self.realCanvasWidth.set.call(canvas, value);
  42129. self.onResize();
  42130. }
  42131. });
  42132. Object.defineProperty(canvas, 'height', {
  42133. configurable: true,
  42134. enumerable: true,
  42135. get: function get() {
  42136. return self.bufferHeight;
  42137. },
  42138. set: function set(value) {
  42139. self.bufferHeight = value;
  42140. self.realCanvasHeight.set.call(canvas, value);
  42141. self.onResize();
  42142. }
  42143. });
  42144. }
  42145. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  42146. if (this.lastBoundFramebuffer == null) {
  42147. this.lastBoundFramebuffer = this.framebuffer;
  42148. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  42149. }
  42150. this.gl.bindFramebuffer = function (target, framebuffer) {
  42151. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  42152. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  42153. };
  42154. this.cullFace = gl.getParameter(gl.CULL_FACE);
  42155. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  42156. this.blend = gl.getParameter(gl.BLEND);
  42157. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  42158. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  42159. gl.enable = function (pname) {
  42160. switch (pname) {
  42161. case gl.CULL_FACE:
  42162. self.cullFace = true;break;
  42163. case gl.DEPTH_TEST:
  42164. self.depthTest = true;break;
  42165. case gl.BLEND:
  42166. self.blend = true;break;
  42167. case gl.SCISSOR_TEST:
  42168. self.scissorTest = true;break;
  42169. case gl.STENCIL_TEST:
  42170. self.stencilTest = true;break;
  42171. }
  42172. self.realEnable.call(gl, pname);
  42173. };
  42174. gl.disable = function (pname) {
  42175. switch (pname) {
  42176. case gl.CULL_FACE:
  42177. self.cullFace = false;break;
  42178. case gl.DEPTH_TEST:
  42179. self.depthTest = false;break;
  42180. case gl.BLEND:
  42181. self.blend = false;break;
  42182. case gl.SCISSOR_TEST:
  42183. self.scissorTest = false;break;
  42184. case gl.STENCIL_TEST:
  42185. self.stencilTest = false;break;
  42186. }
  42187. self.realDisable.call(gl, pname);
  42188. };
  42189. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  42190. gl.colorMask = function (r, g, b, a) {
  42191. self.colorMask[0] = r;
  42192. self.colorMask[1] = g;
  42193. self.colorMask[2] = b;
  42194. self.colorMask[3] = a;
  42195. self.realColorMask.call(gl, r, g, b, a);
  42196. };
  42197. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  42198. gl.clearColor = function (r, g, b, a) {
  42199. self.clearColor[0] = r;
  42200. self.clearColor[1] = g;
  42201. self.clearColor[2] = b;
  42202. self.clearColor[3] = a;
  42203. self.realClearColor.call(gl, r, g, b, a);
  42204. };
  42205. this.viewport = gl.getParameter(gl.VIEWPORT);
  42206. gl.viewport = function (x, y, w, h) {
  42207. self.viewport[0] = x;
  42208. self.viewport[1] = y;
  42209. self.viewport[2] = w;
  42210. self.viewport[3] = h;
  42211. self.realViewport.call(gl, x, y, w, h);
  42212. };
  42213. this.isPatched = true;
  42214. safariCssSizeWorkaround(canvas);
  42215. };
  42216. CardboardDistorter.prototype.unpatch = function () {
  42217. if (!this.isPatched) {
  42218. return;
  42219. }
  42220. var gl = this.gl;
  42221. var canvas = this.gl.canvas;
  42222. if (!isIOS()) {
  42223. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  42224. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  42225. }
  42226. canvas.width = this.bufferWidth;
  42227. canvas.height = this.bufferHeight;
  42228. gl.bindFramebuffer = this.realBindFramebuffer;
  42229. gl.enable = this.realEnable;
  42230. gl.disable = this.realDisable;
  42231. gl.colorMask = this.realColorMask;
  42232. gl.clearColor = this.realClearColor;
  42233. gl.viewport = this.realViewport;
  42234. if (this.lastBoundFramebuffer == this.framebuffer) {
  42235. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  42236. }
  42237. this.isPatched = false;
  42238. setTimeout(function () {
  42239. safariCssSizeWorkaround(canvas);
  42240. }, 1);
  42241. };
  42242. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  42243. if (!leftBounds) {
  42244. leftBounds = [0, 0, 0.5, 1];
  42245. }
  42246. if (!rightBounds) {
  42247. rightBounds = [0.5, 0, 0.5, 1];
  42248. }
  42249. this.viewportOffsetScale[0] = leftBounds[0];
  42250. this.viewportOffsetScale[1] = leftBounds[1];
  42251. this.viewportOffsetScale[2] = leftBounds[2];
  42252. this.viewportOffsetScale[3] = leftBounds[3];
  42253. this.viewportOffsetScale[4] = rightBounds[0];
  42254. this.viewportOffsetScale[5] = rightBounds[1];
  42255. this.viewportOffsetScale[6] = rightBounds[2];
  42256. this.viewportOffsetScale[7] = rightBounds[3];
  42257. };
  42258. CardboardDistorter.prototype.submitFrame = function () {
  42259. var gl = this.gl;
  42260. var self = this;
  42261. var glState = [];
  42262. if (!this.dirtySubmitFrameBindings) {
  42263. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  42264. }
  42265. glPreserveState(gl, glState, function (gl) {
  42266. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42267. var positionDivisor = 0;
  42268. var texCoordDivisor = 0;
  42269. if (self.instanceExt) {
  42270. positionDivisor = gl.getVertexAttrib(self.attribs.position, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42271. texCoordDivisor = gl.getVertexAttrib(self.attribs.texCoord, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42272. }
  42273. if (self.cullFace) {
  42274. self.realDisable.call(gl, gl.CULL_FACE);
  42275. }
  42276. if (self.depthTest) {
  42277. self.realDisable.call(gl, gl.DEPTH_TEST);
  42278. }
  42279. if (self.blend) {
  42280. self.realDisable.call(gl, gl.BLEND);
  42281. }
  42282. if (self.scissorTest) {
  42283. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42284. }
  42285. if (self.stencilTest) {
  42286. self.realDisable.call(gl, gl.STENCIL_TEST);
  42287. }
  42288. self.realColorMask.call(gl, true, true, true, true);
  42289. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42290. if (self.ctxAttribs.alpha || isIOS()) {
  42291. self.realClearColor.call(gl, 0, 0, 0, 1);
  42292. gl.clear(gl.COLOR_BUFFER_BIT);
  42293. }
  42294. gl.useProgram(self.program);
  42295. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42296. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42297. gl.enableVertexAttribArray(self.attribs.position);
  42298. gl.enableVertexAttribArray(self.attribs.texCoord);
  42299. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  42300. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  42301. if (self.instanceExt) {
  42302. if (positionDivisor != 0) {
  42303. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, 0);
  42304. }
  42305. if (texCoordDivisor != 0) {
  42306. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, 0);
  42307. }
  42308. }
  42309. gl.activeTexture(gl.TEXTURE0);
  42310. gl.uniform1i(self.uniforms.diffuse, 0);
  42311. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42312. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  42313. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  42314. if (self.cardboardUI) {
  42315. self.cardboardUI.renderNoState();
  42316. }
  42317. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  42318. if (!self.ctxAttribs.preserveDrawingBuffer) {
  42319. self.realClearColor.call(gl, 0, 0, 0, 0);
  42320. gl.clear(gl.COLOR_BUFFER_BIT);
  42321. }
  42322. if (!self.dirtySubmitFrameBindings) {
  42323. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42324. }
  42325. if (self.cullFace) {
  42326. self.realEnable.call(gl, gl.CULL_FACE);
  42327. }
  42328. if (self.depthTest) {
  42329. self.realEnable.call(gl, gl.DEPTH_TEST);
  42330. }
  42331. if (self.blend) {
  42332. self.realEnable.call(gl, gl.BLEND);
  42333. }
  42334. if (self.scissorTest) {
  42335. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42336. }
  42337. if (self.stencilTest) {
  42338. self.realEnable.call(gl, gl.STENCIL_TEST);
  42339. }
  42340. self.realColorMask.apply(gl, self.colorMask);
  42341. self.realViewport.apply(gl, self.viewport);
  42342. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  42343. self.realClearColor.apply(gl, self.clearColor);
  42344. }
  42345. if (self.instanceExt) {
  42346. if (positionDivisor != 0) {
  42347. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, positionDivisor);
  42348. }
  42349. if (texCoordDivisor != 0) {
  42350. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, texCoordDivisor);
  42351. }
  42352. }
  42353. });
  42354. if (isIOS()) {
  42355. var canvas = gl.canvas;
  42356. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  42357. self.bufferWidth = canvas.width;
  42358. self.bufferHeight = canvas.height;
  42359. self.onResize();
  42360. }
  42361. }
  42362. };
  42363. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  42364. var gl = this.gl;
  42365. var self = this;
  42366. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  42367. glPreserveState(gl, glState, function (gl) {
  42368. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  42369. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42370. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  42371. if (!self.indexCount) {
  42372. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  42373. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42374. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  42375. self.indexCount = indices.length;
  42376. }
  42377. });
  42378. };
  42379. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  42380. var vertices = new Float32Array(2 * width * height * 5);
  42381. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  42382. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  42383. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  42384. var vidx = 0;
  42385. for (var e = 0; e < 2; e++) {
  42386. for (var j = 0; j < height; j++) {
  42387. for (var i = 0; i < width; i++, vidx++) {
  42388. var u = i / (width - 1);
  42389. var v = j / (height - 1);
  42390. var s = u;
  42391. var t = v;
  42392. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  42393. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  42394. var d = Math.sqrt(x * x + y * y);
  42395. var r = deviceInfo.distortion.distortInverse(d);
  42396. var p = x * r / d;
  42397. var q = y * r / d;
  42398. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  42399. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  42400. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  42401. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  42402. vertices[vidx * 5 + 0] = u;
  42403. vertices[vidx * 5 + 1] = v;
  42404. vertices[vidx * 5 + 2] = s;
  42405. vertices[vidx * 5 + 3] = t;
  42406. vertices[vidx * 5 + 4] = e;
  42407. }
  42408. }
  42409. var w = lensFrustum[2] - lensFrustum[0];
  42410. lensFrustum[0] = -(w + lensFrustum[0]);
  42411. lensFrustum[2] = w - lensFrustum[2];
  42412. w = noLensFrustum[2] - noLensFrustum[0];
  42413. noLensFrustum[0] = -(w + noLensFrustum[0]);
  42414. noLensFrustum[2] = w - noLensFrustum[2];
  42415. viewport.x = 1 - (viewport.x + viewport.width);
  42416. }
  42417. return vertices;
  42418. };
  42419. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  42420. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  42421. var halfwidth = width / 2;
  42422. var halfheight = height / 2;
  42423. var vidx = 0;
  42424. var iidx = 0;
  42425. for (var e = 0; e < 2; e++) {
  42426. for (var j = 0; j < height; j++) {
  42427. for (var i = 0; i < width; i++, vidx++) {
  42428. if (i == 0 || j == 0) continue;
  42429. if (i <= halfwidth == j <= halfheight) {
  42430. indices[iidx++] = vidx;
  42431. indices[iidx++] = vidx - width - 1;
  42432. indices[iidx++] = vidx - width;
  42433. indices[iidx++] = vidx - width - 1;
  42434. indices[iidx++] = vidx;
  42435. indices[iidx++] = vidx - 1;
  42436. } else {
  42437. indices[iidx++] = vidx - 1;
  42438. indices[iidx++] = vidx - width;
  42439. indices[iidx++] = vidx;
  42440. indices[iidx++] = vidx - width;
  42441. indices[iidx++] = vidx - 1;
  42442. indices[iidx++] = vidx - width - 1;
  42443. }
  42444. }
  42445. }
  42446. }
  42447. return indices;
  42448. };
  42449. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  42450. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  42451. if (descriptor.get === undefined || descriptor.set === undefined) {
  42452. descriptor.configurable = true;
  42453. descriptor.enumerable = true;
  42454. descriptor.get = function () {
  42455. return this.getAttribute(attrName);
  42456. };
  42457. descriptor.set = function (val) {
  42458. this.setAttribute(attrName, val);
  42459. };
  42460. }
  42461. return descriptor;
  42462. };
  42463. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  42464. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  42465. var DEG2RAD = Math.PI / 180.0;
  42466. var kAnglePerGearSection = 60;
  42467. var kOuterRimEndAngle = 12;
  42468. var kInnerRimBeginAngle = 20;
  42469. var kOuterRadius = 1;
  42470. var kMiddleRadius = 0.75;
  42471. var kInnerRadius = 0.3125;
  42472. var kCenterLineThicknessDp = 4;
  42473. var kButtonWidthDp = 28;
  42474. var kTouchSlopFactor = 1.5;
  42475. function CardboardUI(gl) {
  42476. this.gl = gl;
  42477. this.attribs = {
  42478. position: 0
  42479. };
  42480. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  42481. this.uniforms = getProgramUniforms(gl, this.program);
  42482. this.vertexBuffer = gl.createBuffer();
  42483. this.gearOffset = 0;
  42484. this.gearVertexCount = 0;
  42485. this.arrowOffset = 0;
  42486. this.arrowVertexCount = 0;
  42487. this.projMat = new Float32Array(16);
  42488. this.listener = null;
  42489. this.onResize();
  42490. }
  42491. CardboardUI.prototype.destroy = function () {
  42492. var gl = this.gl;
  42493. if (this.listener) {
  42494. gl.canvas.removeEventListener('click', this.listener, false);
  42495. }
  42496. gl.deleteProgram(this.program);
  42497. gl.deleteBuffer(this.vertexBuffer);
  42498. };
  42499. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  42500. var canvas = this.gl.canvas;
  42501. this.listener = function (event) {
  42502. var midline = canvas.clientWidth / 2;
  42503. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  42504. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  42505. optionsCallback(event);
  42506. }
  42507. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  42508. backCallback(event);
  42509. }
  42510. };
  42511. canvas.addEventListener('click', this.listener, false);
  42512. };
  42513. CardboardUI.prototype.onResize = function () {
  42514. var gl = this.gl;
  42515. var self = this;
  42516. var glState = [gl.ARRAY_BUFFER_BINDING];
  42517. glPreserveState(gl, glState, function (gl) {
  42518. var vertices = [];
  42519. var midline = gl.drawingBufferWidth / 2;
  42520. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  42521. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  42522. var dps = scalingRatio * window.devicePixelRatio;
  42523. var lineWidth = kCenterLineThicknessDp * dps / 2;
  42524. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  42525. var buttonScale = kButtonWidthDp * dps / 2;
  42526. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  42527. vertices.push(midline - lineWidth, buttonSize);
  42528. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  42529. vertices.push(midline + lineWidth, buttonSize);
  42530. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  42531. self.gearOffset = vertices.length / 2;
  42532. function addGearSegment(theta, r) {
  42533. var angle = (90 - theta) * DEG2RAD;
  42534. var x = Math.cos(angle);
  42535. var y = Math.sin(angle);
  42536. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  42537. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  42538. }
  42539. for (var i = 0; i <= 6; i++) {
  42540. var segmentTheta = i * kAnglePerGearSection;
  42541. addGearSegment(segmentTheta, kOuterRadius);
  42542. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  42543. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  42544. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  42545. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  42546. }
  42547. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  42548. self.arrowOffset = vertices.length / 2;
  42549. function addArrowVertex(x, y) {
  42550. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  42551. }
  42552. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  42553. addArrowVertex(0, buttonScale);
  42554. addArrowVertex(buttonScale, 0);
  42555. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  42556. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  42557. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42558. addArrowVertex(0, buttonScale);
  42559. addArrowVertex(buttonScale, buttonScale * 2);
  42560. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  42561. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42562. addArrowVertex(0, buttonScale);
  42563. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  42564. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  42565. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  42566. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  42567. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  42568. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42569. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  42570. });
  42571. };
  42572. CardboardUI.prototype.render = function () {
  42573. var gl = this.gl;
  42574. var self = this;
  42575. 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];
  42576. glPreserveState(gl, glState, function (gl) {
  42577. gl.disable(gl.CULL_FACE);
  42578. gl.disable(gl.DEPTH_TEST);
  42579. gl.disable(gl.BLEND);
  42580. gl.disable(gl.SCISSOR_TEST);
  42581. gl.disable(gl.STENCIL_TEST);
  42582. gl.colorMask(true, true, true, true);
  42583. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42584. self.renderNoState();
  42585. });
  42586. };
  42587. CardboardUI.prototype.renderNoState = function () {
  42588. var gl = this.gl;
  42589. gl.useProgram(this.program);
  42590. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  42591. gl.enableVertexAttribArray(this.attribs.position);
  42592. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  42593. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  42594. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  42595. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  42596. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  42597. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  42598. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  42599. };
  42600. function Distortion(coefficients) {
  42601. this.coefficients = coefficients;
  42602. }
  42603. Distortion.prototype.distortInverse = function (radius) {
  42604. var r0 = 0;
  42605. var r1 = 1;
  42606. var dr0 = radius - this.distort(r0);
  42607. while (Math.abs(r1 - r0) > 0.0001 ) {
  42608. var dr1 = radius - this.distort(r1);
  42609. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  42610. r0 = r1;
  42611. r1 = r2;
  42612. dr0 = dr1;
  42613. }
  42614. return r1;
  42615. };
  42616. Distortion.prototype.distort = function (radius) {
  42617. var r2 = radius * radius;
  42618. var ret = 0;
  42619. for (var i = 0; i < this.coefficients.length; i++) {
  42620. ret = r2 * (ret + this.coefficients[i]);
  42621. }
  42622. return (ret + 1) * radius;
  42623. };
  42624. var degToRad = Math.PI / 180;
  42625. var radToDeg = 180 / Math.PI;
  42626. var Vector3 = function Vector3(x, y, z) {
  42627. this.x = x || 0;
  42628. this.y = y || 0;
  42629. this.z = z || 0;
  42630. };
  42631. Vector3.prototype = {
  42632. constructor: Vector3,
  42633. set: function set(x, y, z) {
  42634. this.x = x;
  42635. this.y = y;
  42636. this.z = z;
  42637. return this;
  42638. },
  42639. copy: function copy(v) {
  42640. this.x = v.x;
  42641. this.y = v.y;
  42642. this.z = v.z;
  42643. return this;
  42644. },
  42645. length: function length() {
  42646. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  42647. },
  42648. normalize: function normalize() {
  42649. var scalar = this.length();
  42650. if (scalar !== 0) {
  42651. var invScalar = 1 / scalar;
  42652. this.multiplyScalar(invScalar);
  42653. } else {
  42654. this.x = 0;
  42655. this.y = 0;
  42656. this.z = 0;
  42657. }
  42658. return this;
  42659. },
  42660. multiplyScalar: function multiplyScalar(scalar) {
  42661. this.x *= scalar;
  42662. this.y *= scalar;
  42663. this.z *= scalar;
  42664. },
  42665. applyQuaternion: function applyQuaternion(q) {
  42666. var x = this.x;
  42667. var y = this.y;
  42668. var z = this.z;
  42669. var qx = q.x;
  42670. var qy = q.y;
  42671. var qz = q.z;
  42672. var qw = q.w;
  42673. var ix = qw * x + qy * z - qz * y;
  42674. var iy = qw * y + qz * x - qx * z;
  42675. var iz = qw * z + qx * y - qy * x;
  42676. var iw = -qx * x - qy * y - qz * z;
  42677. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  42678. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  42679. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  42680. return this;
  42681. },
  42682. dot: function dot(v) {
  42683. return this.x * v.x + this.y * v.y + this.z * v.z;
  42684. },
  42685. crossVectors: function crossVectors(a, b) {
  42686. var ax = a.x,
  42687. ay = a.y,
  42688. az = a.z;
  42689. var bx = b.x,
  42690. by = b.y,
  42691. bz = b.z;
  42692. this.x = ay * bz - az * by;
  42693. this.y = az * bx - ax * bz;
  42694. this.z = ax * by - ay * bx;
  42695. return this;
  42696. }
  42697. };
  42698. var Quaternion = function Quaternion(x, y, z, w) {
  42699. this.x = x || 0;
  42700. this.y = y || 0;
  42701. this.z = z || 0;
  42702. this.w = w !== undefined ? w : 1;
  42703. };
  42704. Quaternion.prototype = {
  42705. constructor: Quaternion,
  42706. set: function set(x, y, z, w) {
  42707. this.x = x;
  42708. this.y = y;
  42709. this.z = z;
  42710. this.w = w;
  42711. return this;
  42712. },
  42713. copy: function copy(quaternion) {
  42714. this.x = quaternion.x;
  42715. this.y = quaternion.y;
  42716. this.z = quaternion.z;
  42717. this.w = quaternion.w;
  42718. return this;
  42719. },
  42720. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  42721. var c1 = Math.cos(x / 2);
  42722. var c2 = Math.cos(y / 2);
  42723. var c3 = Math.cos(z / 2);
  42724. var s1 = Math.sin(x / 2);
  42725. var s2 = Math.sin(y / 2);
  42726. var s3 = Math.sin(z / 2);
  42727. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42728. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42729. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  42730. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  42731. return this;
  42732. },
  42733. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  42734. var c1 = Math.cos(x / 2);
  42735. var c2 = Math.cos(y / 2);
  42736. var c3 = Math.cos(z / 2);
  42737. var s1 = Math.sin(x / 2);
  42738. var s2 = Math.sin(y / 2);
  42739. var s3 = Math.sin(z / 2);
  42740. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42741. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42742. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  42743. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  42744. return this;
  42745. },
  42746. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  42747. var halfAngle = angle / 2,
  42748. s = Math.sin(halfAngle);
  42749. this.x = axis.x * s;
  42750. this.y = axis.y * s;
  42751. this.z = axis.z * s;
  42752. this.w = Math.cos(halfAngle);
  42753. return this;
  42754. },
  42755. multiply: function multiply(q) {
  42756. return this.multiplyQuaternions(this, q);
  42757. },
  42758. multiplyQuaternions: function multiplyQuaternions(a, b) {
  42759. var qax = a.x,
  42760. qay = a.y,
  42761. qaz = a.z,
  42762. qaw = a.w;
  42763. var qbx = b.x,
  42764. qby = b.y,
  42765. qbz = b.z,
  42766. qbw = b.w;
  42767. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  42768. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  42769. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  42770. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  42771. return this;
  42772. },
  42773. inverse: function inverse() {
  42774. this.x *= -1;
  42775. this.y *= -1;
  42776. this.z *= -1;
  42777. this.normalize();
  42778. return this;
  42779. },
  42780. normalize: function normalize() {
  42781. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  42782. if (l === 0) {
  42783. this.x = 0;
  42784. this.y = 0;
  42785. this.z = 0;
  42786. this.w = 1;
  42787. } else {
  42788. l = 1 / l;
  42789. this.x = this.x * l;
  42790. this.y = this.y * l;
  42791. this.z = this.z * l;
  42792. this.w = this.w * l;
  42793. }
  42794. return this;
  42795. },
  42796. slerp: function slerp(qb, t) {
  42797. if (t === 0) return this;
  42798. if (t === 1) return this.copy(qb);
  42799. var x = this.x,
  42800. y = this.y,
  42801. z = this.z,
  42802. w = this.w;
  42803. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  42804. if (cosHalfTheta < 0) {
  42805. this.w = -qb.w;
  42806. this.x = -qb.x;
  42807. this.y = -qb.y;
  42808. this.z = -qb.z;
  42809. cosHalfTheta = -cosHalfTheta;
  42810. } else {
  42811. this.copy(qb);
  42812. }
  42813. if (cosHalfTheta >= 1.0) {
  42814. this.w = w;
  42815. this.x = x;
  42816. this.y = y;
  42817. this.z = z;
  42818. return this;
  42819. }
  42820. var halfTheta = Math.acos(cosHalfTheta);
  42821. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  42822. if (Math.abs(sinHalfTheta) < 0.001) {
  42823. this.w = 0.5 * (w + this.w);
  42824. this.x = 0.5 * (x + this.x);
  42825. this.y = 0.5 * (y + this.y);
  42826. this.z = 0.5 * (z + this.z);
  42827. return this;
  42828. }
  42829. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  42830. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  42831. this.w = w * ratioA + this.w * ratioB;
  42832. this.x = x * ratioA + this.x * ratioB;
  42833. this.y = y * ratioA + this.y * ratioB;
  42834. this.z = z * ratioA + this.z * ratioB;
  42835. return this;
  42836. },
  42837. setFromUnitVectors: function () {
  42838. var v1, r;
  42839. var EPS = 0.000001;
  42840. return function (vFrom, vTo) {
  42841. if (v1 === undefined) v1 = new Vector3();
  42842. r = vFrom.dot(vTo) + 1;
  42843. if (r < EPS) {
  42844. r = 0;
  42845. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  42846. v1.set(-vFrom.y, vFrom.x, 0);
  42847. } else {
  42848. v1.set(0, -vFrom.z, vFrom.y);
  42849. }
  42850. } else {
  42851. v1.crossVectors(vFrom, vTo);
  42852. }
  42853. this.x = v1.x;
  42854. this.y = v1.y;
  42855. this.z = v1.z;
  42856. this.w = r;
  42857. this.normalize();
  42858. return this;
  42859. };
  42860. }()
  42861. };
  42862. function Device(params) {
  42863. this.width = params.width || getScreenWidth();
  42864. this.height = params.height || getScreenHeight();
  42865. this.widthMeters = params.widthMeters;
  42866. this.heightMeters = params.heightMeters;
  42867. this.bevelMeters = params.bevelMeters;
  42868. }
  42869. var DEFAULT_ANDROID = new Device({
  42870. widthMeters: 0.110,
  42871. heightMeters: 0.062,
  42872. bevelMeters: 0.004
  42873. });
  42874. var DEFAULT_IOS = new Device({
  42875. widthMeters: 0.1038,
  42876. heightMeters: 0.0584,
  42877. bevelMeters: 0.004
  42878. });
  42879. var Viewers = {
  42880. CardboardV1: new CardboardViewer({
  42881. id: 'CardboardV1',
  42882. label: 'Cardboard I/O 2014',
  42883. fov: 40,
  42884. interLensDistance: 0.060,
  42885. baselineLensDistance: 0.035,
  42886. screenLensDistance: 0.042,
  42887. distortionCoefficients: [0.441, 0.156],
  42888. 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]
  42889. }),
  42890. CardboardV2: new CardboardViewer({
  42891. id: 'CardboardV2',
  42892. label: 'Cardboard I/O 2015',
  42893. fov: 60,
  42894. interLensDistance: 0.064,
  42895. baselineLensDistance: 0.035,
  42896. screenLensDistance: 0.039,
  42897. distortionCoefficients: [0.34, 0.55],
  42898. 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]
  42899. })
  42900. };
  42901. function DeviceInfo(deviceParams, additionalViewers) {
  42902. this.viewer = Viewers.CardboardV2;
  42903. this.updateDeviceParams(deviceParams);
  42904. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42905. for (var i = 0; i < additionalViewers.length; i++) {
  42906. var viewer = additionalViewers[i];
  42907. Viewers[viewer.id] = new CardboardViewer(viewer);
  42908. }
  42909. }
  42910. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  42911. this.device = this.determineDevice_(deviceParams) || this.device;
  42912. };
  42913. DeviceInfo.prototype.getDevice = function () {
  42914. return this.device;
  42915. };
  42916. DeviceInfo.prototype.setViewer = function (viewer) {
  42917. this.viewer = viewer;
  42918. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42919. };
  42920. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  42921. if (!deviceParams) {
  42922. if (isIOS()) {
  42923. console.warn('Using fallback iOS device measurements.');
  42924. return DEFAULT_IOS;
  42925. } else {
  42926. console.warn('Using fallback Android device measurements.');
  42927. return DEFAULT_ANDROID;
  42928. }
  42929. }
  42930. var METERS_PER_INCH = 0.0254;
  42931. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  42932. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  42933. var width = getScreenWidth();
  42934. var height = getScreenHeight();
  42935. return new Device({
  42936. widthMeters: metersPerPixelX * width,
  42937. heightMeters: metersPerPixelY * height,
  42938. bevelMeters: deviceParams.bevelMm * 0.001
  42939. });
  42940. };
  42941. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  42942. var viewer = this.viewer;
  42943. var device = this.device;
  42944. var distortion = this.distortion;
  42945. var eyeToScreenDistance = viewer.screenLensDistance;
  42946. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  42947. var innerDist = viewer.interLensDistance / 2;
  42948. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  42949. var topDist = device.heightMeters - bottomDist;
  42950. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  42951. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  42952. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  42953. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  42954. return {
  42955. leftDegrees: Math.min(outerAngle, viewer.fov),
  42956. rightDegrees: Math.min(innerAngle, viewer.fov),
  42957. downDegrees: Math.min(bottomAngle, viewer.fov),
  42958. upDegrees: Math.min(topAngle, viewer.fov)
  42959. };
  42960. };
  42961. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  42962. var viewer = this.viewer;
  42963. var device = this.device;
  42964. var distortion = this.distortion;
  42965. var fovLeft = Math.tan(-degToRad * viewer.fov);
  42966. var fovTop = Math.tan(degToRad * viewer.fov);
  42967. var fovRight = Math.tan(degToRad * viewer.fov);
  42968. var fovBottom = Math.tan(-degToRad * viewer.fov);
  42969. var halfWidth = device.widthMeters / 4;
  42970. var halfHeight = device.heightMeters / 2;
  42971. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  42972. var centerX = viewer.interLensDistance / 2 - halfWidth;
  42973. var centerY = -verticalLensOffset;
  42974. var centerZ = viewer.screenLensDistance;
  42975. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  42976. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  42977. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  42978. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  42979. var result = new Float32Array(4);
  42980. result[0] = Math.max(fovLeft, screenLeft);
  42981. result[1] = Math.min(fovTop, screenTop);
  42982. result[2] = Math.min(fovRight, screenRight);
  42983. result[3] = Math.max(fovBottom, screenBottom);
  42984. return result;
  42985. };
  42986. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  42987. var viewer = this.viewer;
  42988. var device = this.device;
  42989. var distortion = this.distortion;
  42990. var result = new Float32Array(4);
  42991. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42992. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42993. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42994. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42995. var halfWidth = device.widthMeters / 4;
  42996. var halfHeight = device.heightMeters / 2;
  42997. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  42998. var centerX = viewer.interLensDistance / 2 - halfWidth;
  42999. var centerY = -verticalLensOffset;
  43000. var centerZ = viewer.screenLensDistance;
  43001. var screenLeft = (centerX - halfWidth) / centerZ;
  43002. var screenTop = (centerY + halfHeight) / centerZ;
  43003. var screenRight = (centerX + halfWidth) / centerZ;
  43004. var screenBottom = (centerY - halfHeight) / centerZ;
  43005. result[0] = Math.max(fovLeft, screenLeft);
  43006. result[1] = Math.min(fovTop, screenTop);
  43007. result[2] = Math.min(fovRight, screenRight);
  43008. result[3] = Math.max(fovBottom, screenBottom);
  43009. return result;
  43010. };
  43011. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  43012. var viewer = this.viewer;
  43013. var device = this.device;
  43014. var dist = viewer.screenLensDistance;
  43015. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  43016. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  43017. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  43018. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  43019. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  43020. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  43021. return {
  43022. x: left,
  43023. y: bottom,
  43024. width: right - left,
  43025. height: top - bottom
  43026. };
  43027. };
  43028. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  43029. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  43030. };
  43031. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  43032. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  43033. return {
  43034. leftDegrees: fov.rightDegrees,
  43035. rightDegrees: fov.leftDegrees,
  43036. upDegrees: fov.upDegrees,
  43037. downDegrees: fov.downDegrees
  43038. };
  43039. };
  43040. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  43041. var p = this.getUndistortedParams_();
  43042. return {
  43043. leftDegrees: radToDeg * Math.atan(p.outerDist),
  43044. rightDegrees: radToDeg * Math.atan(p.innerDist),
  43045. downDegrees: radToDeg * Math.atan(p.bottomDist),
  43046. upDegrees: radToDeg * Math.atan(p.topDist)
  43047. };
  43048. };
  43049. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  43050. var p = this.getUndistortedParams_();
  43051. var viewer = this.viewer;
  43052. var device = this.device;
  43053. var eyeToScreenDistance = viewer.screenLensDistance;
  43054. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43055. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43056. var xPxPerTanAngle = device.width / screenWidth;
  43057. var yPxPerTanAngle = device.height / screenHeight;
  43058. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  43059. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  43060. return {
  43061. x: x,
  43062. y: y,
  43063. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  43064. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  43065. };
  43066. };
  43067. DeviceInfo.prototype.getUndistortedParams_ = function () {
  43068. var viewer = this.viewer;
  43069. var device = this.device;
  43070. var distortion = this.distortion;
  43071. var eyeToScreenDistance = viewer.screenLensDistance;
  43072. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  43073. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43074. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43075. var eyePosX = screenWidth / 2 - halfLensDistance;
  43076. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  43077. var maxFov = viewer.fov;
  43078. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  43079. var outerDist = Math.min(eyePosX, viewerMax);
  43080. var innerDist = Math.min(halfLensDistance, viewerMax);
  43081. var bottomDist = Math.min(eyePosY, viewerMax);
  43082. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  43083. return {
  43084. outerDist: outerDist,
  43085. innerDist: innerDist,
  43086. topDist: topDist,
  43087. bottomDist: bottomDist,
  43088. eyePosX: eyePosX,
  43089. eyePosY: eyePosY
  43090. };
  43091. };
  43092. function CardboardViewer(params) {
  43093. this.id = params.id;
  43094. this.label = params.label;
  43095. this.fov = params.fov;
  43096. this.interLensDistance = params.interLensDistance;
  43097. this.baselineLensDistance = params.baselineLensDistance;
  43098. this.screenLensDistance = params.screenLensDistance;
  43099. this.distortionCoefficients = params.distortionCoefficients;
  43100. this.inverseCoefficients = params.inverseCoefficients;
  43101. }
  43102. DeviceInfo.Viewers = Viewers;
  43103. var format = 1;
  43104. var last_updated = "2019-11-09T17:36:14Z";
  43105. 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}];
  43106. var DPDB_CACHE = {
  43107. format: format,
  43108. last_updated: last_updated,
  43109. devices: devices
  43110. };
  43111. function Dpdb(url, onDeviceParamsUpdated) {
  43112. this.dpdb = DPDB_CACHE;
  43113. this.recalculateDeviceParams_();
  43114. if (url) {
  43115. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  43116. var xhr = new XMLHttpRequest();
  43117. var obj = this;
  43118. xhr.open('GET', url, true);
  43119. xhr.addEventListener('load', function () {
  43120. obj.loading = false;
  43121. if (xhr.status >= 200 && xhr.status <= 299) {
  43122. obj.dpdb = JSON.parse(xhr.response);
  43123. obj.recalculateDeviceParams_();
  43124. } else {
  43125. console.error('Error loading online DPDB!');
  43126. }
  43127. });
  43128. xhr.send();
  43129. }
  43130. }
  43131. Dpdb.prototype.getDeviceParams = function () {
  43132. return this.deviceParams;
  43133. };
  43134. Dpdb.prototype.recalculateDeviceParams_ = function () {
  43135. var newDeviceParams = this.calcDeviceParams_();
  43136. if (newDeviceParams) {
  43137. this.deviceParams = newDeviceParams;
  43138. if (this.onDeviceParamsUpdated) {
  43139. this.onDeviceParamsUpdated(this.deviceParams);
  43140. }
  43141. } else {
  43142. console.error('Failed to recalculate device parameters.');
  43143. }
  43144. };
  43145. Dpdb.prototype.calcDeviceParams_ = function () {
  43146. var db = this.dpdb;
  43147. if (!db) {
  43148. console.error('DPDB not available.');
  43149. return null;
  43150. }
  43151. if (db.format != 1) {
  43152. console.error('DPDB has unexpected format version.');
  43153. return null;
  43154. }
  43155. if (!db.devices || !db.devices.length) {
  43156. console.error('DPDB does not have a devices section.');
  43157. return null;
  43158. }
  43159. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  43160. var width = getScreenWidth();
  43161. var height = getScreenHeight();
  43162. if (!db.devices) {
  43163. console.error('DPDB has no devices section.');
  43164. return null;
  43165. }
  43166. for (var i = 0; i < db.devices.length; i++) {
  43167. var device = db.devices[i];
  43168. if (!device.rules) {
  43169. console.warn('Device[' + i + '] has no rules section.');
  43170. continue;
  43171. }
  43172. if (device.type != 'ios' && device.type != 'android') {
  43173. console.warn('Device[' + i + '] has invalid type.');
  43174. continue;
  43175. }
  43176. if (isIOS() != (device.type == 'ios')) continue;
  43177. var matched = false;
  43178. for (var j = 0; j < device.rules.length; j++) {
  43179. var rule = device.rules[j];
  43180. if (this.ruleMatches_(rule, userAgent, width, height)) {
  43181. matched = true;
  43182. break;
  43183. }
  43184. }
  43185. if (!matched) continue;
  43186. var xdpi = device.dpi[0] || device.dpi;
  43187. var ydpi = device.dpi[1] || device.dpi;
  43188. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  43189. }
  43190. console.warn('No DPDB device match.');
  43191. return null;
  43192. };
  43193. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  43194. if (!rule.ua && !rule.res) return false;
  43195. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  43196. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  43197. if (rule.res) {
  43198. if (!rule.res[0] || !rule.res[1]) return false;
  43199. var resX = rule.res[0];
  43200. var resY = rule.res[1];
  43201. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  43202. return false;
  43203. }
  43204. }
  43205. return true;
  43206. };
  43207. function DeviceParams(params) {
  43208. this.xdpi = params.xdpi;
  43209. this.ydpi = params.ydpi;
  43210. this.bevelMm = params.bevelMm;
  43211. }
  43212. function SensorSample(sample, timestampS) {
  43213. this.set(sample, timestampS);
  43214. }
  43215. SensorSample.prototype.set = function (sample, timestampS) {
  43216. this.sample = sample;
  43217. this.timestampS = timestampS;
  43218. };
  43219. SensorSample.prototype.copy = function (sensorSample) {
  43220. this.set(sensorSample.sample, sensorSample.timestampS);
  43221. };
  43222. function ComplementaryFilter(kFilter, isDebug) {
  43223. this.kFilter = kFilter;
  43224. this.isDebug = isDebug;
  43225. this.currentAccelMeasurement = new SensorSample();
  43226. this.currentGyroMeasurement = new SensorSample();
  43227. this.previousGyroMeasurement = new SensorSample();
  43228. if (isIOS()) {
  43229. this.filterQ = new Quaternion(-1, 0, 0, 1);
  43230. } else {
  43231. this.filterQ = new Quaternion(1, 0, 0, 1);
  43232. }
  43233. this.previousFilterQ = new Quaternion();
  43234. this.previousFilterQ.copy(this.filterQ);
  43235. this.accelQ = new Quaternion();
  43236. this.isOrientationInitialized = false;
  43237. this.estimatedGravity = new Vector3();
  43238. this.measuredGravity = new Vector3();
  43239. this.gyroIntegralQ = new Quaternion();
  43240. }
  43241. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  43242. this.currentAccelMeasurement.set(vector, timestampS);
  43243. };
  43244. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  43245. this.currentGyroMeasurement.set(vector, timestampS);
  43246. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  43247. if (isTimestampDeltaValid(deltaT)) {
  43248. this.run_();
  43249. }
  43250. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  43251. };
  43252. ComplementaryFilter.prototype.run_ = function () {
  43253. if (!this.isOrientationInitialized) {
  43254. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  43255. this.previousFilterQ.copy(this.accelQ);
  43256. this.isOrientationInitialized = true;
  43257. return;
  43258. }
  43259. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  43260. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  43261. this.gyroIntegralQ.multiply(gyroDeltaQ);
  43262. this.filterQ.copy(this.previousFilterQ);
  43263. this.filterQ.multiply(gyroDeltaQ);
  43264. var invFilterQ = new Quaternion();
  43265. invFilterQ.copy(this.filterQ);
  43266. invFilterQ.inverse();
  43267. this.estimatedGravity.set(0, 0, -1);
  43268. this.estimatedGravity.applyQuaternion(invFilterQ);
  43269. this.estimatedGravity.normalize();
  43270. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  43271. this.measuredGravity.normalize();
  43272. var deltaQ = new Quaternion();
  43273. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  43274. deltaQ.inverse();
  43275. if (this.isDebug) {
  43276. 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));
  43277. }
  43278. var targetQ = new Quaternion();
  43279. targetQ.copy(this.filterQ);
  43280. targetQ.multiply(deltaQ);
  43281. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  43282. this.previousFilterQ.copy(this.filterQ);
  43283. };
  43284. ComplementaryFilter.prototype.getOrientation = function () {
  43285. return this.filterQ;
  43286. };
  43287. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  43288. var normAccel = new Vector3();
  43289. normAccel.copy(accel);
  43290. normAccel.normalize();
  43291. var quat = new Quaternion();
  43292. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  43293. quat.inverse();
  43294. return quat;
  43295. };
  43296. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  43297. var quat = new Quaternion();
  43298. var axis = new Vector3();
  43299. axis.copy(gyro);
  43300. axis.normalize();
  43301. quat.setFromAxisAngle(axis, gyro.length() * dt);
  43302. return quat;
  43303. };
  43304. function PosePredictor(predictionTimeS, isDebug) {
  43305. this.predictionTimeS = predictionTimeS;
  43306. this.isDebug = isDebug;
  43307. this.previousQ = new Quaternion();
  43308. this.previousTimestampS = null;
  43309. this.deltaQ = new Quaternion();
  43310. this.outQ = new Quaternion();
  43311. }
  43312. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  43313. if (!this.previousTimestampS) {
  43314. this.previousQ.copy(currentQ);
  43315. this.previousTimestampS = timestampS;
  43316. return currentQ;
  43317. }
  43318. var axis = new Vector3();
  43319. axis.copy(gyro);
  43320. axis.normalize();
  43321. var angularSpeed = gyro.length();
  43322. if (angularSpeed < degToRad * 20) {
  43323. if (this.isDebug) {
  43324. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  43325. }
  43326. this.outQ.copy(currentQ);
  43327. this.previousQ.copy(currentQ);
  43328. return this.outQ;
  43329. }
  43330. var predictAngle = angularSpeed * this.predictionTimeS;
  43331. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  43332. this.outQ.copy(this.previousQ);
  43333. this.outQ.multiply(this.deltaQ);
  43334. this.previousQ.copy(currentQ);
  43335. this.previousTimestampS = timestampS;
  43336. return this.outQ;
  43337. };
  43338. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  43339. this.yawOnly = yawOnly;
  43340. this.accelerometer = new Vector3();
  43341. this.gyroscope = new Vector3();
  43342. this.filter = new ComplementaryFilter(kFilter, isDebug);
  43343. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  43344. this.isFirefoxAndroid = isFirefoxAndroid();
  43345. this.isIOS = isIOS();
  43346. var chromeVersion = getChromeVersion();
  43347. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  43348. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion() || isSafariWithoutDeviceMotion();
  43349. this.filterToWorldQ = new Quaternion();
  43350. if (isIOS()) {
  43351. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  43352. } else {
  43353. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43354. }
  43355. this.inverseWorldToScreenQ = new Quaternion();
  43356. this.worldToScreenQ = new Quaternion();
  43357. this.originalPoseAdjustQ = new Quaternion();
  43358. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  43359. this.setScreenTransform_();
  43360. if (isLandscapeMode()) {
  43361. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  43362. }
  43363. this.resetQ = new Quaternion();
  43364. this.orientationOut_ = new Float32Array(4);
  43365. this.start();
  43366. }
  43367. FusionPoseSensor.prototype.getPosition = function () {
  43368. return null;
  43369. };
  43370. FusionPoseSensor.prototype.getOrientation = function () {
  43371. var orientation = void 0;
  43372. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  43373. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  43374. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  43375. var y = new Quaternion();
  43376. if (window.orientation === -90) {
  43377. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  43378. } else {
  43379. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  43380. }
  43381. return z.multiply(y);
  43382. }();
  43383. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  43384. var q = new Quaternion();
  43385. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43386. return q;
  43387. }();
  43388. orientation = this._deviceOrientationQ;
  43389. var out = new Quaternion();
  43390. out.copy(orientation);
  43391. out.multiply(this.deviceOrientationFilterToWorldQ);
  43392. out.multiply(this.resetQ);
  43393. out.multiply(this.worldToScreenQ);
  43394. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  43395. if (this.yawOnly) {
  43396. out.x = 0;
  43397. out.z = 0;
  43398. out.normalize();
  43399. }
  43400. this.orientationOut_[0] = out.x;
  43401. this.orientationOut_[1] = out.y;
  43402. this.orientationOut_[2] = out.z;
  43403. this.orientationOut_[3] = out.w;
  43404. return this.orientationOut_;
  43405. } else {
  43406. var filterOrientation = this.filter.getOrientation();
  43407. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  43408. }
  43409. var out = new Quaternion();
  43410. out.copy(this.filterToWorldQ);
  43411. out.multiply(this.resetQ);
  43412. out.multiply(orientation);
  43413. out.multiply(this.worldToScreenQ);
  43414. if (this.yawOnly) {
  43415. out.x = 0;
  43416. out.z = 0;
  43417. out.normalize();
  43418. }
  43419. this.orientationOut_[0] = out.x;
  43420. this.orientationOut_[1] = out.y;
  43421. this.orientationOut_[2] = out.z;
  43422. this.orientationOut_[3] = out.w;
  43423. return this.orientationOut_;
  43424. };
  43425. FusionPoseSensor.prototype.resetPose = function () {
  43426. this.resetQ.copy(this.filter.getOrientation());
  43427. this.resetQ.x = 0;
  43428. this.resetQ.y = 0;
  43429. this.resetQ.z *= -1;
  43430. this.resetQ.normalize();
  43431. if (isLandscapeMode()) {
  43432. this.resetQ.multiply(this.inverseWorldToScreenQ);
  43433. }
  43434. this.resetQ.multiply(this.originalPoseAdjustQ);
  43435. };
  43436. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  43437. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  43438. var alpha = e.alpha,
  43439. beta = e.beta,
  43440. gamma = e.gamma;
  43441. alpha = (alpha || 0) * Math.PI / 180;
  43442. beta = (beta || 0) * Math.PI / 180;
  43443. gamma = (gamma || 0) * Math.PI / 180;
  43444. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  43445. };
  43446. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  43447. this.updateDeviceMotion_(deviceMotion);
  43448. };
  43449. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  43450. var accGravity = deviceMotion.accelerationIncludingGravity;
  43451. var rotRate = deviceMotion.rotationRate;
  43452. var timestampS = deviceMotion.timeStamp / 1000;
  43453. var deltaS = timestampS - this.previousTimestampS;
  43454. if (deltaS < 0) {
  43455. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  43456. this.previousTimestampS = timestampS;
  43457. return;
  43458. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  43459. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  43460. this.previousTimestampS = timestampS;
  43461. return;
  43462. }
  43463. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  43464. if (rotRate) {
  43465. if (isR7()) {
  43466. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  43467. } else {
  43468. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  43469. }
  43470. if (!this.isDeviceMotionInRadians) {
  43471. this.gyroscope.multiplyScalar(Math.PI / 180);
  43472. }
  43473. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  43474. }
  43475. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  43476. this.previousTimestampS = timestampS;
  43477. };
  43478. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  43479. this.setScreenTransform_();
  43480. };
  43481. FusionPoseSensor.prototype.onMessage_ = function (event) {
  43482. var message = event.data;
  43483. if (!message || !message.type) {
  43484. return;
  43485. }
  43486. var type = message.type.toLowerCase();
  43487. if (type !== 'devicemotion') {
  43488. return;
  43489. }
  43490. this.updateDeviceMotion_(message.deviceMotionEvent);
  43491. };
  43492. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  43493. this.worldToScreenQ.set(0, 0, 0, 1);
  43494. switch (window.orientation) {
  43495. case 0:
  43496. break;
  43497. case 90:
  43498. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  43499. break;
  43500. case -90:
  43501. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  43502. break;
  43503. case 180:
  43504. break;
  43505. }
  43506. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  43507. this.inverseWorldToScreenQ.inverse();
  43508. };
  43509. FusionPoseSensor.prototype.start = function () {
  43510. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  43511. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  43512. this.onMessageCallback_ = this.onMessage_.bind(this);
  43513. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  43514. if (isIOS() && isInsideCrossOriginIFrame()) {
  43515. window.addEventListener('message', this.onMessageCallback_);
  43516. }
  43517. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  43518. if (this.isWithoutDeviceMotion) {
  43519. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43520. } else {
  43521. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  43522. }
  43523. };
  43524. FusionPoseSensor.prototype.stop = function () {
  43525. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  43526. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43527. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  43528. window.removeEventListener('message', this.onMessageCallback_);
  43529. };
  43530. var SENSOR_FREQUENCY = 60;
  43531. var X_AXIS = new Vector3(1, 0, 0);
  43532. var Z_AXIS = new Vector3(0, 0, 1);
  43533. var SENSOR_TO_VR = new Quaternion();
  43534. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  43535. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  43536. var PoseSensor = function () {
  43537. function PoseSensor(config) {
  43538. classCallCheck(this, PoseSensor);
  43539. this.config = config;
  43540. this.sensor = null;
  43541. this.fusionSensor = null;
  43542. this._out = new Float32Array(4);
  43543. this.api = null;
  43544. this.errors = [];
  43545. this._sensorQ = new Quaternion();
  43546. this._outQ = new Quaternion();
  43547. this._onSensorRead = this._onSensorRead.bind(this);
  43548. this._onSensorError = this._onSensorError.bind(this);
  43549. this.init();
  43550. }
  43551. createClass(PoseSensor, [{
  43552. key: 'init',
  43553. value: function init() {
  43554. var sensor = null;
  43555. try {
  43556. sensor = new RelativeOrientationSensor({
  43557. frequency: SENSOR_FREQUENCY,
  43558. referenceFrame: 'screen'
  43559. });
  43560. sensor.addEventListener('error', this._onSensorError);
  43561. } catch (error) {
  43562. this.errors.push(error);
  43563. if (error.name === 'SecurityError') {
  43564. console.error('Cannot construct sensors due to the Feature Policy');
  43565. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  43566. this.useDeviceMotion();
  43567. } else if (error.name === 'ReferenceError') {
  43568. this.useDeviceMotion();
  43569. } else {
  43570. console.error(error);
  43571. }
  43572. }
  43573. if (sensor) {
  43574. this.api = 'sensor';
  43575. this.sensor = sensor;
  43576. this.sensor.addEventListener('reading', this._onSensorRead);
  43577. this.sensor.start();
  43578. }
  43579. }
  43580. }, {
  43581. key: 'useDeviceMotion',
  43582. value: function useDeviceMotion() {
  43583. this.api = 'devicemotion';
  43584. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  43585. if (this.sensor) {
  43586. this.sensor.removeEventListener('reading', this._onSensorRead);
  43587. this.sensor.removeEventListener('error', this._onSensorError);
  43588. this.sensor = null;
  43589. }
  43590. }
  43591. }, {
  43592. key: 'getOrientation',
  43593. value: function getOrientation() {
  43594. if (this.fusionSensor) {
  43595. return this.fusionSensor.getOrientation();
  43596. }
  43597. if (!this.sensor || !this.sensor.quaternion) {
  43598. this._out[0] = this._out[1] = this._out[2] = 0;
  43599. this._out[3] = 1;
  43600. return this._out;
  43601. }
  43602. var q = this.sensor.quaternion;
  43603. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  43604. var out = this._outQ;
  43605. out.copy(SENSOR_TO_VR);
  43606. out.multiply(this._sensorQ);
  43607. if (this.config.YAW_ONLY) {
  43608. out.x = out.z = 0;
  43609. out.normalize();
  43610. }
  43611. this._out[0] = out.x;
  43612. this._out[1] = out.y;
  43613. this._out[2] = out.z;
  43614. this._out[3] = out.w;
  43615. return this._out;
  43616. }
  43617. }, {
  43618. key: '_onSensorError',
  43619. value: function _onSensorError(event) {
  43620. this.errors.push(event.error);
  43621. if (event.error.name === 'NotAllowedError') {
  43622. console.error('Permission to access sensor was denied');
  43623. } else if (event.error.name === 'NotReadableError') {
  43624. console.error('Sensor could not be read');
  43625. } else {
  43626. console.error(event.error);
  43627. }
  43628. this.useDeviceMotion();
  43629. }
  43630. }, {
  43631. key: '_onSensorRead',
  43632. value: function _onSensorRead() {}
  43633. }]);
  43634. return PoseSensor;
  43635. }();
  43636. 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>";
  43637. function RotateInstructions() {
  43638. this.loadIcon_();
  43639. var overlay = document.createElement('div');
  43640. var s = overlay.style;
  43641. s.position = 'fixed';
  43642. s.top = 0;
  43643. s.right = 0;
  43644. s.bottom = 0;
  43645. s.left = 0;
  43646. s.backgroundColor = 'gray';
  43647. s.fontFamily = 'sans-serif';
  43648. s.zIndex = 1000000;
  43649. var img = document.createElement('img');
  43650. img.src = this.icon;
  43651. var s = img.style;
  43652. s.marginLeft = '25%';
  43653. s.marginTop = '25%';
  43654. s.width = '50%';
  43655. overlay.appendChild(img);
  43656. var text = document.createElement('div');
  43657. var s = text.style;
  43658. s.textAlign = 'center';
  43659. s.fontSize = '16px';
  43660. s.lineHeight = '24px';
  43661. s.margin = '24px 25%';
  43662. s.width = '50%';
  43663. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  43664. overlay.appendChild(text);
  43665. var snackbar = document.createElement('div');
  43666. var s = snackbar.style;
  43667. s.backgroundColor = '#CFD8DC';
  43668. s.position = 'fixed';
  43669. s.bottom = 0;
  43670. s.width = '100%';
  43671. s.height = '48px';
  43672. s.padding = '14px 24px';
  43673. s.boxSizing = 'border-box';
  43674. s.color = '#656A6B';
  43675. overlay.appendChild(snackbar);
  43676. var snackbarText = document.createElement('div');
  43677. snackbarText.style.float = 'left';
  43678. snackbarText.innerHTML = 'No Cardboard viewer?';
  43679. var snackbarButton = document.createElement('a');
  43680. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  43681. snackbarButton.innerHTML = 'get one';
  43682. snackbarButton.target = '_blank';
  43683. var s = snackbarButton.style;
  43684. s.float = 'right';
  43685. s.fontWeight = 600;
  43686. s.textTransform = 'uppercase';
  43687. s.borderLeft = '1px solid gray';
  43688. s.paddingLeft = '24px';
  43689. s.textDecoration = 'none';
  43690. s.color = '#656A6B';
  43691. snackbar.appendChild(snackbarText);
  43692. snackbar.appendChild(snackbarButton);
  43693. this.overlay = overlay;
  43694. this.text = text;
  43695. this.hide();
  43696. }
  43697. RotateInstructions.prototype.show = function (parent) {
  43698. if (!parent && !this.overlay.parentElement) {
  43699. document.body.appendChild(this.overlay);
  43700. } else if (parent) {
  43701. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  43702. parent.appendChild(this.overlay);
  43703. }
  43704. this.overlay.style.display = 'block';
  43705. var img = this.overlay.querySelector('img');
  43706. var s = img.style;
  43707. if (isLandscapeMode()) {
  43708. s.width = '20%';
  43709. s.marginLeft = '40%';
  43710. s.marginTop = '3%';
  43711. } else {
  43712. s.width = '50%';
  43713. s.marginLeft = '25%';
  43714. s.marginTop = '25%';
  43715. }
  43716. };
  43717. RotateInstructions.prototype.hide = function () {
  43718. this.overlay.style.display = 'none';
  43719. };
  43720. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  43721. this.show(parent);
  43722. this.timer = setTimeout(this.hide.bind(this), ms);
  43723. };
  43724. RotateInstructions.prototype.disableShowTemporarily = function () {
  43725. clearTimeout(this.timer);
  43726. };
  43727. RotateInstructions.prototype.update = function () {
  43728. this.disableShowTemporarily();
  43729. if (!isLandscapeMode() && isMobile()) {
  43730. this.show();
  43731. } else {
  43732. this.hide();
  43733. }
  43734. };
  43735. RotateInstructions.prototype.loadIcon_ = function () {
  43736. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  43737. };
  43738. var DEFAULT_VIEWER = 'CardboardV1';
  43739. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  43740. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  43741. function ViewerSelector(defaultViewer) {
  43742. try {
  43743. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  43744. } catch (error) {
  43745. console.error('Failed to load viewer profile: %s', error);
  43746. }
  43747. if (!this.selectedKey) {
  43748. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  43749. }
  43750. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  43751. this.root = null;
  43752. this.onChangeCallbacks_ = [];
  43753. }
  43754. ViewerSelector.prototype.show = function (root) {
  43755. this.root = root;
  43756. root.appendChild(this.dialog);
  43757. var selected = this.dialog.querySelector('#' + this.selectedKey);
  43758. selected.checked = true;
  43759. this.dialog.style.display = 'block';
  43760. };
  43761. ViewerSelector.prototype.hide = function () {
  43762. if (this.root && this.root.contains(this.dialog)) {
  43763. this.root.removeChild(this.dialog);
  43764. }
  43765. this.dialog.style.display = 'none';
  43766. };
  43767. ViewerSelector.prototype.getCurrentViewer = function () {
  43768. return DeviceInfo.Viewers[this.selectedKey];
  43769. };
  43770. ViewerSelector.prototype.getSelectedKey_ = function () {
  43771. var input = this.dialog.querySelector('input[name=field]:checked');
  43772. if (input) {
  43773. return input.id;
  43774. }
  43775. return null;
  43776. };
  43777. ViewerSelector.prototype.onChange = function (cb) {
  43778. this.onChangeCallbacks_.push(cb);
  43779. };
  43780. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  43781. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  43782. this.onChangeCallbacks_[i](viewer);
  43783. }
  43784. };
  43785. ViewerSelector.prototype.onSave_ = function () {
  43786. this.selectedKey = this.getSelectedKey_();
  43787. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  43788. console.error('ViewerSelector.onSave_: this should never happen!');
  43789. return;
  43790. }
  43791. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  43792. try {
  43793. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  43794. } catch (error) {
  43795. console.error('Failed to save viewer profile: %s', error);
  43796. }
  43797. this.hide();
  43798. };
  43799. ViewerSelector.prototype.createDialog_ = function (options) {
  43800. var container = document.createElement('div');
  43801. container.classList.add(CLASS_NAME);
  43802. container.style.display = 'none';
  43803. var overlay = document.createElement('div');
  43804. var s = overlay.style;
  43805. s.position = 'fixed';
  43806. s.left = 0;
  43807. s.top = 0;
  43808. s.width = '100%';
  43809. s.height = '100%';
  43810. s.background = 'rgba(0, 0, 0, 0.3)';
  43811. overlay.addEventListener('click', this.hide.bind(this));
  43812. var width = 280;
  43813. var dialog = document.createElement('div');
  43814. var s = dialog.style;
  43815. s.boxSizing = 'border-box';
  43816. s.position = 'fixed';
  43817. s.top = '24px';
  43818. s.left = '50%';
  43819. s.marginLeft = -width / 2 + 'px';
  43820. s.width = width + 'px';
  43821. s.padding = '24px';
  43822. s.overflow = 'hidden';
  43823. s.background = '#fafafa';
  43824. s.fontFamily = "'Roboto', sans-serif";
  43825. s.boxShadow = '0px 5px 20px #666';
  43826. dialog.appendChild(this.createH1_('Select your viewer'));
  43827. for (var id in options) {
  43828. dialog.appendChild(this.createChoice_(id, options[id].label));
  43829. }
  43830. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  43831. container.appendChild(overlay);
  43832. container.appendChild(dialog);
  43833. return container;
  43834. };
  43835. ViewerSelector.prototype.createH1_ = function (name) {
  43836. var h1 = document.createElement('h1');
  43837. var s = h1.style;
  43838. s.color = 'black';
  43839. s.fontSize = '20px';
  43840. s.fontWeight = 'bold';
  43841. s.marginTop = 0;
  43842. s.marginBottom = '24px';
  43843. h1.innerHTML = name;
  43844. return h1;
  43845. };
  43846. ViewerSelector.prototype.createChoice_ = function (id, name) {
  43847. var div = document.createElement('div');
  43848. div.style.marginTop = '8px';
  43849. div.style.color = 'black';
  43850. var input = document.createElement('input');
  43851. input.style.fontSize = '30px';
  43852. input.setAttribute('id', id);
  43853. input.setAttribute('type', 'radio');
  43854. input.setAttribute('value', id);
  43855. input.setAttribute('name', 'field');
  43856. var label = document.createElement('label');
  43857. label.style.marginLeft = '4px';
  43858. label.setAttribute('for', id);
  43859. label.innerHTML = name;
  43860. div.appendChild(input);
  43861. div.appendChild(label);
  43862. return div;
  43863. };
  43864. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  43865. var button = document.createElement('button');
  43866. button.innerHTML = label;
  43867. var s = button.style;
  43868. s.float = 'right';
  43869. s.textTransform = 'uppercase';
  43870. s.color = '#1094f7';
  43871. s.fontSize = '14px';
  43872. s.letterSpacing = 0;
  43873. s.border = 0;
  43874. s.background = 'none';
  43875. s.marginTop = '16px';
  43876. button.addEventListener('click', onclick);
  43877. return button;
  43878. };
  43879. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  43880. function unwrapExports$$1 (x) {
  43881. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  43882. }
  43883. function createCommonjsModule$$1(fn, module) {
  43884. return module = { exports: {} }, fn(module, module.exports), module.exports;
  43885. }
  43886. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  43887. (function webpackUniversalModuleDefinition(root, factory) {
  43888. module.exports = factory();
  43889. })(commonjsGlobal$$1, function() {
  43890. return (function(modules) {
  43891. var installedModules = {};
  43892. function __webpack_require__(moduleId) {
  43893. if(installedModules[moduleId]) {
  43894. return installedModules[moduleId].exports;
  43895. }
  43896. var module = installedModules[moduleId] = {
  43897. i: moduleId,
  43898. l: false,
  43899. exports: {}
  43900. };
  43901. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  43902. module.l = true;
  43903. return module.exports;
  43904. }
  43905. __webpack_require__.m = modules;
  43906. __webpack_require__.c = installedModules;
  43907. __webpack_require__.d = function(exports, name, getter) {
  43908. if(!__webpack_require__.o(exports, name)) {
  43909. Object.defineProperty(exports, name, {
  43910. configurable: false,
  43911. enumerable: true,
  43912. get: getter
  43913. });
  43914. }
  43915. };
  43916. __webpack_require__.n = function(module) {
  43917. var getter = module && module.__esModule ?
  43918. function getDefault() { return module['default']; } :
  43919. function getModuleExports() { return module; };
  43920. __webpack_require__.d(getter, 'a', getter);
  43921. return getter;
  43922. };
  43923. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  43924. __webpack_require__.p = "";
  43925. return __webpack_require__(__webpack_require__.s = 0);
  43926. })
  43927. ([
  43928. (function(module, exports, __webpack_require__) {
  43929. 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; }; }();
  43930. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  43931. var mediaFile = __webpack_require__(1);
  43932. 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;
  43933. var NoSleep = function () {
  43934. function NoSleep() {
  43935. _classCallCheck(this, NoSleep);
  43936. if (oldIOS) {
  43937. this.noSleepTimer = null;
  43938. } else {
  43939. this.noSleepVideo = document.createElement('video');
  43940. this.noSleepVideo.setAttribute('playsinline', '');
  43941. this.noSleepVideo.setAttribute('src', mediaFile);
  43942. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  43943. if (this.noSleepVideo.currentTime > 0.5) {
  43944. this.noSleepVideo.currentTime = Math.random();
  43945. }
  43946. }.bind(this));
  43947. }
  43948. }
  43949. _createClass(NoSleep, [{
  43950. key: 'enable',
  43951. value: function enable() {
  43952. if (oldIOS) {
  43953. this.disable();
  43954. this.noSleepTimer = window.setInterval(function () {
  43955. window.location.href = '/';
  43956. window.setTimeout(window.stop, 0);
  43957. }, 15000);
  43958. } else {
  43959. this.noSleepVideo.play();
  43960. }
  43961. }
  43962. }, {
  43963. key: 'disable',
  43964. value: function disable() {
  43965. if (oldIOS) {
  43966. if (this.noSleepTimer) {
  43967. window.clearInterval(this.noSleepTimer);
  43968. this.noSleepTimer = null;
  43969. }
  43970. } else {
  43971. this.noSleepVideo.pause();
  43972. }
  43973. }
  43974. }]);
  43975. return NoSleep;
  43976. }();
  43977. module.exports = NoSleep;
  43978. }),
  43979. (function(module, exports, __webpack_require__) {
  43980. 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=';
  43981. })
  43982. ]);
  43983. });
  43984. });
  43985. var NoSleep$1 = unwrapExports$$1(NoSleep);
  43986. var nextDisplayId = 1000;
  43987. var defaultLeftBounds = [0, 0, 0.5, 1];
  43988. var defaultRightBounds = [0.5, 0, 0.5, 1];
  43989. var raf = window.requestAnimationFrame;
  43990. var caf = window.cancelAnimationFrame;
  43991. function VRFrameData() {
  43992. this.leftProjectionMatrix = new Float32Array(16);
  43993. this.leftViewMatrix = new Float32Array(16);
  43994. this.rightProjectionMatrix = new Float32Array(16);
  43995. this.rightViewMatrix = new Float32Array(16);
  43996. this.pose = null;
  43997. }
  43998. function VRDisplayCapabilities(config) {
  43999. Object.defineProperties(this, {
  44000. hasPosition: {
  44001. writable: false, enumerable: true, value: config.hasPosition
  44002. },
  44003. hasExternalDisplay: {
  44004. writable: false, enumerable: true, value: config.hasExternalDisplay
  44005. },
  44006. canPresent: {
  44007. writable: false, enumerable: true, value: config.canPresent
  44008. },
  44009. maxLayers: {
  44010. writable: false, enumerable: true, value: config.maxLayers
  44011. },
  44012. hasOrientation: {
  44013. enumerable: true, get: function get() {
  44014. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  44015. return config.hasOrientation;
  44016. }
  44017. }
  44018. });
  44019. }
  44020. function VRDisplay(config) {
  44021. config = config || {};
  44022. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  44023. this.isPolyfilled = true;
  44024. this.displayId = nextDisplayId++;
  44025. this.displayName = '';
  44026. this.depthNear = 0.01;
  44027. this.depthFar = 10000.0;
  44028. this.isPresenting = false;
  44029. Object.defineProperty(this, 'isConnected', {
  44030. get: function get() {
  44031. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  44032. return false;
  44033. }
  44034. });
  44035. this.capabilities = new VRDisplayCapabilities({
  44036. hasPosition: false,
  44037. hasOrientation: false,
  44038. hasExternalDisplay: false,
  44039. canPresent: false,
  44040. maxLayers: 1
  44041. });
  44042. this.stageParameters = null;
  44043. this.waitingForPresent_ = false;
  44044. this.layer_ = null;
  44045. this.originalParent_ = null;
  44046. this.fullscreenElement_ = null;
  44047. this.fullscreenWrapper_ = null;
  44048. this.fullscreenElementCachedStyle_ = null;
  44049. this.fullscreenEventTarget_ = null;
  44050. this.fullscreenChangeHandler_ = null;
  44051. this.fullscreenErrorHandler_ = null;
  44052. if (USE_WAKELOCK && isMobile()) {
  44053. this.wakelock_ = new NoSleep$1();
  44054. }
  44055. }
  44056. VRDisplay.prototype.getFrameData = function (frameData) {
  44057. return frameDataFromPose(frameData, this._getPose(), this);
  44058. };
  44059. VRDisplay.prototype.getPose = function () {
  44060. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  44061. return this._getPose();
  44062. };
  44063. VRDisplay.prototype.resetPose = function () {
  44064. deprecateWarning('VRDisplay.prototype.resetPose');
  44065. return this._resetPose();
  44066. };
  44067. VRDisplay.prototype.getImmediatePose = function () {
  44068. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  44069. return this._getPose();
  44070. };
  44071. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  44072. return raf(callback);
  44073. };
  44074. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  44075. return caf(id);
  44076. };
  44077. VRDisplay.prototype.wrapForFullscreen = function (element) {
  44078. if (isIOS()) {
  44079. return element;
  44080. }
  44081. if (!this.fullscreenWrapper_) {
  44082. this.fullscreenWrapper_ = document.createElement('div');
  44083. 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'];
  44084. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  44085. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  44086. }
  44087. if (this.fullscreenElement_ == element) {
  44088. return this.fullscreenWrapper_;
  44089. }
  44090. if (this.fullscreenElement_) {
  44091. if (this.originalParent_) {
  44092. this.originalParent_.appendChild(this.fullscreenElement_);
  44093. } else {
  44094. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  44095. }
  44096. }
  44097. this.fullscreenElement_ = element;
  44098. this.originalParent_ = element.parentElement;
  44099. if (!this.originalParent_) {
  44100. document.body.appendChild(element);
  44101. }
  44102. if (!this.fullscreenWrapper_.parentElement) {
  44103. var parent = this.fullscreenElement_.parentElement;
  44104. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  44105. parent.removeChild(this.fullscreenElement_);
  44106. }
  44107. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  44108. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  44109. var self = this;
  44110. function applyFullscreenElementStyle() {
  44111. if (!self.fullscreenElement_) {
  44112. return;
  44113. }
  44114. 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'];
  44115. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  44116. }
  44117. applyFullscreenElementStyle();
  44118. return this.fullscreenWrapper_;
  44119. };
  44120. VRDisplay.prototype.removeFullscreenWrapper = function () {
  44121. if (!this.fullscreenElement_) {
  44122. return;
  44123. }
  44124. var element = this.fullscreenElement_;
  44125. if (this.fullscreenElementCachedStyle_) {
  44126. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  44127. } else {
  44128. element.removeAttribute('style');
  44129. }
  44130. this.fullscreenElement_ = null;
  44131. this.fullscreenElementCachedStyle_ = null;
  44132. var parent = this.fullscreenWrapper_.parentElement;
  44133. this.fullscreenWrapper_.removeChild(element);
  44134. if (this.originalParent_ === parent) {
  44135. parent.insertBefore(element, this.fullscreenWrapper_);
  44136. }
  44137. else if (this.originalParent_) {
  44138. this.originalParent_.appendChild(element);
  44139. }
  44140. parent.removeChild(this.fullscreenWrapper_);
  44141. return element;
  44142. };
  44143. VRDisplay.prototype.requestPresent = function (layers) {
  44144. var wasPresenting = this.isPresenting;
  44145. var self = this;
  44146. if (!(layers instanceof Array)) {
  44147. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  44148. layers = [layers];
  44149. }
  44150. return new Promise(function (resolve, reject) {
  44151. if (!self.capabilities.canPresent) {
  44152. reject(new Error('VRDisplay is not capable of presenting.'));
  44153. return;
  44154. }
  44155. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  44156. reject(new Error('Invalid number of layers.'));
  44157. return;
  44158. }
  44159. var incomingLayer = layers[0];
  44160. if (!incomingLayer.source) {
  44161. resolve();
  44162. return;
  44163. }
  44164. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  44165. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  44166. if (wasPresenting) {
  44167. var layer = self.layer_;
  44168. if (layer.source !== incomingLayer.source) {
  44169. layer.source = incomingLayer.source;
  44170. }
  44171. for (var i = 0; i < 4; i++) {
  44172. layer.leftBounds[i] = leftBounds[i];
  44173. layer.rightBounds[i] = rightBounds[i];
  44174. }
  44175. self.wrapForFullscreen(self.layer_.source);
  44176. self.updatePresent_();
  44177. resolve();
  44178. return;
  44179. }
  44180. self.layer_ = {
  44181. predistorted: incomingLayer.predistorted,
  44182. source: incomingLayer.source,
  44183. leftBounds: leftBounds.slice(0),
  44184. rightBounds: rightBounds.slice(0)
  44185. };
  44186. self.waitingForPresent_ = false;
  44187. if (self.layer_ && self.layer_.source) {
  44188. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  44189. var onFullscreenChange = function onFullscreenChange() {
  44190. var actualFullscreenElement = getFullscreenElement();
  44191. self.isPresenting = fullscreenElement === actualFullscreenElement;
  44192. if (self.isPresenting) {
  44193. if (screen.orientation && screen.orientation.lock) {
  44194. screen.orientation.lock('landscape-primary').catch(function (error) {
  44195. console.error('screen.orientation.lock() failed due to', error.message);
  44196. });
  44197. }
  44198. self.waitingForPresent_ = false;
  44199. self.beginPresent_();
  44200. resolve();
  44201. } else {
  44202. if (screen.orientation && screen.orientation.unlock) {
  44203. screen.orientation.unlock();
  44204. }
  44205. self.removeFullscreenWrapper();
  44206. self.disableWakeLock();
  44207. self.endPresent_();
  44208. self.removeFullscreenListeners_();
  44209. }
  44210. self.fireVRDisplayPresentChange_();
  44211. };
  44212. var onFullscreenError = function onFullscreenError() {
  44213. if (!self.waitingForPresent_) {
  44214. return;
  44215. }
  44216. self.removeFullscreenWrapper();
  44217. self.removeFullscreenListeners_();
  44218. self.disableWakeLock();
  44219. self.waitingForPresent_ = false;
  44220. self.isPresenting = false;
  44221. reject(new Error('Unable to present.'));
  44222. };
  44223. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  44224. if (requestFullscreen(fullscreenElement)) {
  44225. self.enableWakeLock();
  44226. self.waitingForPresent_ = true;
  44227. } else if (isIOS() || isWebViewAndroid()) {
  44228. self.enableWakeLock();
  44229. self.isPresenting = true;
  44230. self.beginPresent_();
  44231. self.fireVRDisplayPresentChange_();
  44232. resolve();
  44233. }
  44234. }
  44235. if (!self.waitingForPresent_ && !isIOS()) {
  44236. exitFullscreen();
  44237. reject(new Error('Unable to present.'));
  44238. }
  44239. });
  44240. };
  44241. VRDisplay.prototype.exitPresent = function () {
  44242. var wasPresenting = this.isPresenting;
  44243. var self = this;
  44244. this.isPresenting = false;
  44245. this.layer_ = null;
  44246. this.disableWakeLock();
  44247. return new Promise(function (resolve, reject) {
  44248. if (wasPresenting) {
  44249. if (!exitFullscreen() && isIOS()) {
  44250. self.endPresent_();
  44251. self.fireVRDisplayPresentChange_();
  44252. }
  44253. if (isWebViewAndroid()) {
  44254. self.removeFullscreenWrapper();
  44255. self.removeFullscreenListeners_();
  44256. self.endPresent_();
  44257. self.fireVRDisplayPresentChange_();
  44258. }
  44259. resolve();
  44260. } else {
  44261. reject(new Error('Was not presenting to VRDisplay.'));
  44262. }
  44263. });
  44264. };
  44265. VRDisplay.prototype.getLayers = function () {
  44266. if (this.layer_) {
  44267. return [this.layer_];
  44268. }
  44269. return [];
  44270. };
  44271. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  44272. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  44273. window.dispatchEvent(event);
  44274. };
  44275. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  44276. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  44277. window.dispatchEvent(event);
  44278. };
  44279. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  44280. this.removeFullscreenListeners_();
  44281. this.fullscreenEventTarget_ = element;
  44282. this.fullscreenChangeHandler_ = changeHandler;
  44283. this.fullscreenErrorHandler_ = errorHandler;
  44284. if (changeHandler) {
  44285. if (document.fullscreenEnabled) {
  44286. element.addEventListener('fullscreenchange', changeHandler, false);
  44287. } else if (document.webkitFullscreenEnabled) {
  44288. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  44289. } else if (document.mozFullScreenEnabled) {
  44290. document.addEventListener('mozfullscreenchange', changeHandler, false);
  44291. } else if (document.msFullscreenEnabled) {
  44292. element.addEventListener('msfullscreenchange', changeHandler, false);
  44293. }
  44294. }
  44295. if (errorHandler) {
  44296. if (document.fullscreenEnabled) {
  44297. element.addEventListener('fullscreenerror', errorHandler, false);
  44298. } else if (document.webkitFullscreenEnabled) {
  44299. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  44300. } else if (document.mozFullScreenEnabled) {
  44301. document.addEventListener('mozfullscreenerror', errorHandler, false);
  44302. } else if (document.msFullscreenEnabled) {
  44303. element.addEventListener('msfullscreenerror', errorHandler, false);
  44304. }
  44305. }
  44306. };
  44307. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  44308. if (!this.fullscreenEventTarget_) return;
  44309. var element = this.fullscreenEventTarget_;
  44310. if (this.fullscreenChangeHandler_) {
  44311. var changeHandler = this.fullscreenChangeHandler_;
  44312. element.removeEventListener('fullscreenchange', changeHandler, false);
  44313. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  44314. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  44315. element.removeEventListener('msfullscreenchange', changeHandler, false);
  44316. }
  44317. if (this.fullscreenErrorHandler_) {
  44318. var errorHandler = this.fullscreenErrorHandler_;
  44319. element.removeEventListener('fullscreenerror', errorHandler, false);
  44320. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  44321. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  44322. element.removeEventListener('msfullscreenerror', errorHandler, false);
  44323. }
  44324. this.fullscreenEventTarget_ = null;
  44325. this.fullscreenChangeHandler_ = null;
  44326. this.fullscreenErrorHandler_ = null;
  44327. };
  44328. VRDisplay.prototype.enableWakeLock = function () {
  44329. if (this.wakelock_) {
  44330. this.wakelock_.enable();
  44331. }
  44332. };
  44333. VRDisplay.prototype.disableWakeLock = function () {
  44334. if (this.wakelock_) {
  44335. this.wakelock_.disable();
  44336. }
  44337. };
  44338. VRDisplay.prototype.beginPresent_ = function () {
  44339. };
  44340. VRDisplay.prototype.endPresent_ = function () {
  44341. };
  44342. VRDisplay.prototype.submitFrame = function (pose) {
  44343. };
  44344. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  44345. return null;
  44346. };
  44347. var config = {
  44348. ADDITIONAL_VIEWERS: [],
  44349. DEFAULT_VIEWER: '',
  44350. MOBILE_WAKE_LOCK: true,
  44351. DEBUG: false,
  44352. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44353. K_FILTER: 0.98,
  44354. PREDICTION_TIME_S: 0.040,
  44355. CARDBOARD_UI_DISABLED: false,
  44356. ROTATE_INSTRUCTIONS_DISABLED: false,
  44357. YAW_ONLY: false,
  44358. BUFFER_SCALE: 0.5,
  44359. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44360. };
  44361. var Eye = {
  44362. LEFT: 'left',
  44363. RIGHT: 'right'
  44364. };
  44365. function CardboardVRDisplay(config$$1) {
  44366. var defaults = extend({}, config);
  44367. config$$1 = extend(defaults, config$$1 || {});
  44368. VRDisplay.call(this, {
  44369. wakelock: config$$1.MOBILE_WAKE_LOCK
  44370. });
  44371. this.config = config$$1;
  44372. this.displayName = 'Cardboard VRDisplay';
  44373. this.capabilities = new VRDisplayCapabilities({
  44374. hasPosition: false,
  44375. hasOrientation: true,
  44376. hasExternalDisplay: false,
  44377. canPresent: true,
  44378. maxLayers: 1
  44379. });
  44380. this.stageParameters = null;
  44381. this.bufferScale_ = this.config.BUFFER_SCALE;
  44382. this.poseSensor_ = new PoseSensor(this.config);
  44383. this.distorter_ = null;
  44384. this.cardboardUI_ = null;
  44385. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  44386. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  44387. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  44388. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  44389. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  44390. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  44391. this.rotateInstructions_ = new RotateInstructions();
  44392. }
  44393. if (isIOS()) {
  44394. window.addEventListener('resize', this.onResize_.bind(this));
  44395. }
  44396. }
  44397. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  44398. CardboardVRDisplay.prototype._getPose = function () {
  44399. return {
  44400. position: null,
  44401. orientation: this.poseSensor_.getOrientation(),
  44402. linearVelocity: null,
  44403. linearAcceleration: null,
  44404. angularVelocity: null,
  44405. angularAcceleration: null
  44406. };
  44407. };
  44408. CardboardVRDisplay.prototype._resetPose = function () {
  44409. if (this.poseSensor_.resetPose) {
  44410. this.poseSensor_.resetPose();
  44411. }
  44412. };
  44413. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  44414. var fieldOfView;
  44415. if (whichEye == Eye.LEFT) {
  44416. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  44417. } else if (whichEye == Eye.RIGHT) {
  44418. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  44419. } else {
  44420. console.error('Invalid eye provided: %s', whichEye);
  44421. return null;
  44422. }
  44423. return fieldOfView;
  44424. };
  44425. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  44426. var offset;
  44427. if (whichEye == Eye.LEFT) {
  44428. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44429. } else if (whichEye == Eye.RIGHT) {
  44430. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44431. } else {
  44432. console.error('Invalid eye provided: %s', whichEye);
  44433. return null;
  44434. }
  44435. return offset;
  44436. };
  44437. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  44438. var offset = this._getEyeOffset(whichEye);
  44439. var fieldOfView = this._getFieldOfView(whichEye);
  44440. var eyeParams = {
  44441. offset: offset,
  44442. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  44443. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  44444. };
  44445. Object.defineProperty(eyeParams, 'fieldOfView', {
  44446. enumerable: true,
  44447. get: function get() {
  44448. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  44449. return fieldOfView;
  44450. }
  44451. });
  44452. return eyeParams;
  44453. };
  44454. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  44455. if (this.config.DEBUG) {
  44456. console.log('DPDB reported that device params were updated.');
  44457. }
  44458. this.deviceInfo_.updateDeviceParams(newParams);
  44459. if (this.distorter_) {
  44460. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44461. }
  44462. };
  44463. CardboardVRDisplay.prototype.updateBounds_ = function () {
  44464. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  44465. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  44466. }
  44467. };
  44468. CardboardVRDisplay.prototype.beginPresent_ = function () {
  44469. var gl = this.layer_.source.getContext('webgl');
  44470. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44471. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44472. if (!gl) return;
  44473. if (this.layer_.predistorted) {
  44474. if (!this.config.CARDBOARD_UI_DISABLED) {
  44475. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  44476. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  44477. this.cardboardUI_ = new CardboardUI(gl);
  44478. }
  44479. } else {
  44480. if (!this.config.CARDBOARD_UI_DISABLED) {
  44481. this.cardboardUI_ = new CardboardUI(gl);
  44482. }
  44483. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  44484. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44485. }
  44486. if (this.cardboardUI_) {
  44487. this.cardboardUI_.listen(function (e) {
  44488. this.viewerSelector_.show(this.layer_.source.parentElement);
  44489. e.stopPropagation();
  44490. e.preventDefault();
  44491. }.bind(this), function (e) {
  44492. this.exitPresent();
  44493. e.stopPropagation();
  44494. e.preventDefault();
  44495. }.bind(this));
  44496. }
  44497. if (this.rotateInstructions_) {
  44498. if (isLandscapeMode() && isMobile()) {
  44499. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  44500. } else {
  44501. this.rotateInstructions_.update();
  44502. }
  44503. }
  44504. this.orientationHandler = this.onOrientationChange_.bind(this);
  44505. window.addEventListener('orientationchange', this.orientationHandler);
  44506. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  44507. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44508. this.fireVRDisplayDeviceParamsChange_();
  44509. };
  44510. CardboardVRDisplay.prototype.endPresent_ = function () {
  44511. if (this.distorter_) {
  44512. this.distorter_.destroy();
  44513. this.distorter_ = null;
  44514. }
  44515. if (this.cardboardUI_) {
  44516. this.cardboardUI_.destroy();
  44517. this.cardboardUI_ = null;
  44518. }
  44519. if (this.rotateInstructions_) {
  44520. this.rotateInstructions_.hide();
  44521. }
  44522. this.viewerSelector_.hide();
  44523. window.removeEventListener('orientationchange', this.orientationHandler);
  44524. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44525. };
  44526. CardboardVRDisplay.prototype.updatePresent_ = function () {
  44527. this.endPresent_();
  44528. this.beginPresent_();
  44529. };
  44530. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  44531. if (this.distorter_) {
  44532. this.updateBounds_();
  44533. this.distorter_.submitFrame();
  44534. } else if (this.cardboardUI_ && this.layer_) {
  44535. var gl = this.layer_.source.getContext('webgl');
  44536. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44537. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44538. var canvas = gl.canvas;
  44539. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  44540. this.cardboardUI_.onResize();
  44541. }
  44542. this.lastWidth = canvas.width;
  44543. this.lastHeight = canvas.height;
  44544. this.cardboardUI_.render();
  44545. }
  44546. };
  44547. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  44548. this.viewerSelector_.hide();
  44549. if (this.rotateInstructions_) {
  44550. this.rotateInstructions_.update();
  44551. }
  44552. this.onResize_();
  44553. };
  44554. CardboardVRDisplay.prototype.onResize_ = function (e) {
  44555. if (this.layer_) {
  44556. var gl = this.layer_.source.getContext('webgl');
  44557. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44558. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44559. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  44560. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  44561. 'padding: 0px', 'box-sizing: content-box'];
  44562. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  44563. safariCssSizeWorkaround(gl.canvas);
  44564. }
  44565. };
  44566. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  44567. this.deviceInfo_.setViewer(viewer);
  44568. if (this.distorter_) {
  44569. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44570. }
  44571. this.fireVRDisplayDeviceParamsChange_();
  44572. };
  44573. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  44574. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  44575. detail: {
  44576. vrdisplay: this,
  44577. deviceInfo: this.deviceInfo_
  44578. }
  44579. });
  44580. window.dispatchEvent(event);
  44581. };
  44582. CardboardVRDisplay.VRFrameData = VRFrameData;
  44583. CardboardVRDisplay.VRDisplay = VRDisplay;
  44584. return CardboardVRDisplay;
  44585. })));
  44586. });
  44587. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  44588. var version = "0.10.12";
  44589. var DefaultConfig = {
  44590. ADDITIONAL_VIEWERS: [],
  44591. DEFAULT_VIEWER: '',
  44592. PROVIDE_MOBILE_VRDISPLAY: true,
  44593. MOBILE_WAKE_LOCK: true,
  44594. DEBUG: false,
  44595. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44596. K_FILTER: 0.98,
  44597. PREDICTION_TIME_S: 0.040,
  44598. CARDBOARD_UI_DISABLED: false,
  44599. ROTATE_INSTRUCTIONS_DISABLED: false,
  44600. YAW_ONLY: false,
  44601. BUFFER_SCALE: 0.5,
  44602. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44603. };
  44604. function WebVRPolyfill(config) {
  44605. this.config = extend(extend({}, DefaultConfig), config);
  44606. this.polyfillDisplays = [];
  44607. this.enabled = false;
  44608. this.hasNative = 'getVRDisplays' in navigator;
  44609. this.native = {};
  44610. this.native.getVRDisplays = navigator.getVRDisplays;
  44611. this.native.VRFrameData = window.VRFrameData;
  44612. this.native.VRDisplay = window.VRDisplay;
  44613. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  44614. this.enable();
  44615. this.getVRDisplays().then(function (displays) {
  44616. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  44617. displays[0].fireVRDisplayConnect_();
  44618. }
  44619. });
  44620. }
  44621. }
  44622. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  44623. if (this._polyfillDisplaysPopulated) {
  44624. return this.polyfillDisplays;
  44625. }
  44626. if (isMobile()) {
  44627. var vrDisplay = new CardboardVRDisplay({
  44628. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  44629. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  44630. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  44631. DEBUG: this.config.DEBUG,
  44632. DPDB_URL: this.config.DPDB_URL,
  44633. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  44634. K_FILTER: this.config.K_FILTER,
  44635. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  44636. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  44637. YAW_ONLY: this.config.YAW_ONLY,
  44638. BUFFER_SCALE: this.config.BUFFER_SCALE,
  44639. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  44640. });
  44641. this.polyfillDisplays.push(vrDisplay);
  44642. }
  44643. this._polyfillDisplaysPopulated = true;
  44644. return this.polyfillDisplays;
  44645. };
  44646. WebVRPolyfill.prototype.enable = function () {
  44647. this.enabled = true;
  44648. if (this.hasNative && this.native.VRFrameData) {
  44649. var NativeVRFrameData = this.native.VRFrameData;
  44650. var nativeFrameData = new this.native.VRFrameData();
  44651. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  44652. window.VRDisplay.prototype.getFrameData = function (frameData) {
  44653. if (frameData instanceof NativeVRFrameData) {
  44654. nativeGetFrameData.call(this, frameData);
  44655. return;
  44656. }
  44657. nativeGetFrameData.call(this, nativeFrameData);
  44658. frameData.pose = nativeFrameData.pose;
  44659. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  44660. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  44661. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  44662. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  44663. };
  44664. }
  44665. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  44666. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  44667. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  44668. };
  44669. WebVRPolyfill.prototype.getVRDisplays = function () {
  44670. var _this = this;
  44671. var config = this.config;
  44672. if (!this.hasNative) {
  44673. return Promise.resolve(this.getPolyfillDisplays());
  44674. }
  44675. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  44676. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  44677. });
  44678. };
  44679. WebVRPolyfill.version = version;
  44680. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  44681. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  44682. var webvrPolyfill = Object.freeze({
  44683. default: WebVRPolyfill
  44684. });
  44685. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  44686. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  44687. if (!commonjsGlobal.document) {
  44688. commonjsGlobal.document = commonjsGlobal.window.document;
  44689. }
  44690. if (!commonjsGlobal.navigator) {
  44691. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  44692. }
  44693. }
  44694. var src = require$$0;
  44695. return src;
  44696. })));
  44697. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  44698. },{}],69:[function(_dereq_,module,exports){
  44699. var newline = /\n/
  44700. var newlineChar = '\n'
  44701. var whitespace = /\s/
  44702. module.exports = function(text, opt) {
  44703. var lines = module.exports.lines(text, opt)
  44704. return lines.map(function(line) {
  44705. return text.substring(line.start, line.end)
  44706. }).join('\n')
  44707. }
  44708. module.exports.lines = function wordwrap(text, opt) {
  44709. opt = opt||{}
  44710. //zero width results in nothing visible
  44711. if (opt.width === 0 && opt.mode !== 'nowrap')
  44712. return []
  44713. text = text||''
  44714. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  44715. var start = Math.max(0, opt.start||0)
  44716. var end = typeof opt.end === 'number' ? opt.end : text.length
  44717. var mode = opt.mode
  44718. var measure = opt.measure || monospace
  44719. if (mode === 'pre')
  44720. return pre(measure, text, start, end, width)
  44721. else
  44722. return greedy(measure, text, start, end, width, mode)
  44723. }
  44724. function idxOf(text, chr, start, end) {
  44725. var idx = text.indexOf(chr, start)
  44726. if (idx === -1 || idx > end)
  44727. return end
  44728. return idx
  44729. }
  44730. function isWhitespace(chr) {
  44731. return whitespace.test(chr)
  44732. }
  44733. function pre(measure, text, start, end, width) {
  44734. var lines = []
  44735. var lineStart = start
  44736. for (var i=start; i<end && i<text.length; i++) {
  44737. var chr = text.charAt(i)
  44738. var isNewline = newline.test(chr)
  44739. //If we've reached a newline, then step down a line
  44740. //Or if we've reached the EOF
  44741. if (isNewline || i===end-1) {
  44742. var lineEnd = isNewline ? i : i+1
  44743. var measured = measure(text, lineStart, lineEnd, width)
  44744. lines.push(measured)
  44745. lineStart = i+1
  44746. }
  44747. }
  44748. return lines
  44749. }
  44750. function greedy(measure, text, start, end, width, mode) {
  44751. //A greedy word wrapper based on LibGDX algorithm
  44752. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  44753. var lines = []
  44754. var testWidth = width
  44755. //if 'nowrap' is specified, we only wrap on newline chars
  44756. if (mode === 'nowrap')
  44757. testWidth = Number.MAX_VALUE
  44758. while (start < end && start < text.length) {
  44759. //get next newline position
  44760. var newLine = idxOf(text, newlineChar, start, end)
  44761. //eat whitespace at start of line
  44762. while (start < newLine) {
  44763. if (!isWhitespace( text.charAt(start) ))
  44764. break
  44765. start++
  44766. }
  44767. //determine visible # of glyphs for the available width
  44768. var measured = measure(text, start, newLine, testWidth)
  44769. var lineEnd = start + (measured.end-measured.start)
  44770. var nextStart = lineEnd + newlineChar.length
  44771. //if we had to cut the line before the next newline...
  44772. if (lineEnd < newLine) {
  44773. //find char to break on
  44774. while (lineEnd > start) {
  44775. if (isWhitespace(text.charAt(lineEnd)))
  44776. break
  44777. lineEnd--
  44778. }
  44779. if (lineEnd === start) {
  44780. if (nextStart > start + newlineChar.length) nextStart--
  44781. lineEnd = nextStart // If no characters to break, show all.
  44782. } else {
  44783. nextStart = lineEnd
  44784. //eat whitespace at end of line
  44785. while (lineEnd > start) {
  44786. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  44787. break
  44788. lineEnd--
  44789. }
  44790. }
  44791. }
  44792. if (lineEnd >= start) {
  44793. var result = measure(text, start, lineEnd, testWidth)
  44794. lines.push(result)
  44795. }
  44796. start = nextStart
  44797. }
  44798. return lines
  44799. }
  44800. //determines the visible number of glyphs within a given width
  44801. function monospace(text, start, end, width) {
  44802. var glyphs = Math.min(width, end-start)
  44803. return {
  44804. start: start,
  44805. end: start+glyphs
  44806. }
  44807. }
  44808. },{}],70:[function(_dereq_,module,exports){
  44809. "use strict";
  44810. var window = _dereq_("global/window")
  44811. var isFunction = _dereq_("is-function")
  44812. var parseHeaders = _dereq_("parse-headers")
  44813. var xtend = _dereq_("xtend")
  44814. module.exports = createXHR
  44815. // Allow use of default import syntax in TypeScript
  44816. module.exports.default = createXHR;
  44817. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  44818. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  44819. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  44820. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  44821. options = initParams(uri, options, callback)
  44822. options.method = method.toUpperCase()
  44823. return _createXHR(options)
  44824. }
  44825. })
  44826. function forEachArray(array, iterator) {
  44827. for (var i = 0; i < array.length; i++) {
  44828. iterator(array[i])
  44829. }
  44830. }
  44831. function isEmpty(obj){
  44832. for(var i in obj){
  44833. if(obj.hasOwnProperty(i)) return false
  44834. }
  44835. return true
  44836. }
  44837. function initParams(uri, options, callback) {
  44838. var params = uri
  44839. if (isFunction(options)) {
  44840. callback = options
  44841. if (typeof uri === "string") {
  44842. params = {uri:uri}
  44843. }
  44844. } else {
  44845. params = xtend(options, {uri: uri})
  44846. }
  44847. params.callback = callback
  44848. return params
  44849. }
  44850. function createXHR(uri, options, callback) {
  44851. options = initParams(uri, options, callback)
  44852. return _createXHR(options)
  44853. }
  44854. function _createXHR(options) {
  44855. if(typeof options.callback === "undefined"){
  44856. throw new Error("callback argument missing")
  44857. }
  44858. var called = false
  44859. var callback = function cbOnce(err, response, body){
  44860. if(!called){
  44861. called = true
  44862. options.callback(err, response, body)
  44863. }
  44864. }
  44865. function readystatechange() {
  44866. if (xhr.readyState === 4) {
  44867. setTimeout(loadFunc, 0)
  44868. }
  44869. }
  44870. function getBody() {
  44871. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  44872. var body = undefined
  44873. if (xhr.response) {
  44874. body = xhr.response
  44875. } else {
  44876. body = xhr.responseText || getXml(xhr)
  44877. }
  44878. if (isJson) {
  44879. try {
  44880. body = JSON.parse(body)
  44881. } catch (e) {}
  44882. }
  44883. return body
  44884. }
  44885. function errorFunc(evt) {
  44886. clearTimeout(timeoutTimer)
  44887. if(!(evt instanceof Error)){
  44888. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  44889. }
  44890. evt.statusCode = 0
  44891. return callback(evt, failureResponse)
  44892. }
  44893. // will load the data & process the response in a special response object
  44894. function loadFunc() {
  44895. if (aborted) return
  44896. var status
  44897. clearTimeout(timeoutTimer)
  44898. if(options.useXDR && xhr.status===undefined) {
  44899. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  44900. status = 200
  44901. } else {
  44902. status = (xhr.status === 1223 ? 204 : xhr.status)
  44903. }
  44904. var response = failureResponse
  44905. var err = null
  44906. if (status !== 0){
  44907. response = {
  44908. body: getBody(),
  44909. statusCode: status,
  44910. method: method,
  44911. headers: {},
  44912. url: uri,
  44913. rawRequest: xhr
  44914. }
  44915. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  44916. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  44917. }
  44918. } else {
  44919. err = new Error("Internal XMLHttpRequest Error")
  44920. }
  44921. return callback(err, response, response.body)
  44922. }
  44923. var xhr = options.xhr || null
  44924. if (!xhr) {
  44925. if (options.cors || options.useXDR) {
  44926. xhr = new createXHR.XDomainRequest()
  44927. }else{
  44928. xhr = new createXHR.XMLHttpRequest()
  44929. }
  44930. }
  44931. var key
  44932. var aborted
  44933. var uri = xhr.url = options.uri || options.url
  44934. var method = xhr.method = options.method || "GET"
  44935. var body = options.body || options.data
  44936. var headers = xhr.headers = options.headers || {}
  44937. var sync = !!options.sync
  44938. var isJson = false
  44939. var timeoutTimer
  44940. var failureResponse = {
  44941. body: undefined,
  44942. headers: {},
  44943. statusCode: 0,
  44944. method: method,
  44945. url: uri,
  44946. rawRequest: xhr
  44947. }
  44948. if ("json" in options && options.json !== false) {
  44949. isJson = true
  44950. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  44951. if (method !== "GET" && method !== "HEAD") {
  44952. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  44953. body = JSON.stringify(options.json === true ? body : options.json)
  44954. }
  44955. }
  44956. xhr.onreadystatechange = readystatechange
  44957. xhr.onload = loadFunc
  44958. xhr.onerror = errorFunc
  44959. // IE9 must have onprogress be set to a unique function.
  44960. xhr.onprogress = function () {
  44961. // IE must die
  44962. }
  44963. xhr.onabort = function(){
  44964. aborted = true;
  44965. }
  44966. xhr.ontimeout = errorFunc
  44967. xhr.open(method, uri, !sync, options.username, options.password)
  44968. //has to be after open
  44969. if(!sync) {
  44970. xhr.withCredentials = !!options.withCredentials
  44971. }
  44972. // Cannot set timeout with sync request
  44973. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  44974. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  44975. if (!sync && options.timeout > 0 ) {
  44976. timeoutTimer = setTimeout(function(){
  44977. if (aborted) return
  44978. aborted = true//IE9 may still call readystatechange
  44979. xhr.abort("timeout")
  44980. var e = new Error("XMLHttpRequest timeout")
  44981. e.code = "ETIMEDOUT"
  44982. errorFunc(e)
  44983. }, options.timeout )
  44984. }
  44985. if (xhr.setRequestHeader) {
  44986. for(key in headers){
  44987. if(headers.hasOwnProperty(key)){
  44988. xhr.setRequestHeader(key, headers[key])
  44989. }
  44990. }
  44991. } else if (options.headers && !isEmpty(options.headers)) {
  44992. throw new Error("Headers cannot be set on an XDomainRequest object")
  44993. }
  44994. if ("responseType" in options) {
  44995. xhr.responseType = options.responseType
  44996. }
  44997. if ("beforeSend" in options &&
  44998. typeof options.beforeSend === "function"
  44999. ) {
  45000. options.beforeSend(xhr)
  45001. }
  45002. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  45003. // XMLHttpRequest spec says to pass null as body to indicate no body
  45004. // See https://github.com/naugtur/xhr/issues/100.
  45005. xhr.send(body || null)
  45006. return xhr
  45007. }
  45008. function getXml(xhr) {
  45009. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  45010. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  45011. try {
  45012. if (xhr.responseType === "document") {
  45013. return xhr.responseXML
  45014. }
  45015. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  45016. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  45017. return xhr.responseXML
  45018. }
  45019. } catch (e) {}
  45020. return null
  45021. }
  45022. function noop() {}
  45023. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":72}],71:[function(_dereq_,module,exports){
  45024. module.exports = (function xmlparser() {
  45025. //common browsers
  45026. if (typeof self.DOMParser !== 'undefined') {
  45027. return function(str) {
  45028. var parser = new self.DOMParser()
  45029. return parser.parseFromString(str, 'application/xml')
  45030. }
  45031. }
  45032. //IE8 fallback
  45033. if (typeof self.ActiveXObject !== 'undefined'
  45034. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  45035. return function(str) {
  45036. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  45037. xmlDoc.async = "false"
  45038. xmlDoc.loadXML(str)
  45039. return xmlDoc
  45040. }
  45041. }
  45042. //last resort fallback
  45043. return function(str) {
  45044. var div = document.createElement('div')
  45045. div.innerHTML = str
  45046. return div
  45047. }
  45048. })()
  45049. },{}],72:[function(_dereq_,module,exports){
  45050. module.exports = extend
  45051. var hasOwnProperty = Object.prototype.hasOwnProperty;
  45052. function extend() {
  45053. var target = {}
  45054. for (var i = 0; i < arguments.length; i++) {
  45055. var source = arguments[i]
  45056. for (var key in source) {
  45057. if (hasOwnProperty.call(source, key)) {
  45058. target[key] = source[key]
  45059. }
  45060. }
  45061. }
  45062. return target
  45063. }
  45064. },{}],73:[function(_dereq_,module,exports){
  45065. module.exports={
  45066. "name": "aframe",
  45067. "version": "1.2.0",
  45068. "description": "A web framework for building virtual reality experiences.",
  45069. "homepage": "https://aframe.io/",
  45070. "main": "dist/aframe-master.js",
  45071. "scripts": {
  45072. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  45073. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  45074. "codecov": "codecov",
  45075. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  45076. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  45077. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  45078. "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",
  45079. "docs": "markserv --dir docs --port 9001",
  45080. "preghpages": "node ./scripts/preghpages.js",
  45081. "ghpages": "ghpages -p gh-pages/",
  45082. "lint": "semistandard -v | snazzy",
  45083. "lint:fix": "semistandard --fix",
  45084. "precommit": "npm run lint",
  45085. "prepush": "node scripts/testOnlyCheck.js",
  45086. "prerelease": "node scripts/release.js 1.1.0 1.2.0",
  45087. "start": "npm run dev",
  45088. "start:https": "cross-env SSL=true npm run dev",
  45089. "test": "karma start ./tests/karma.conf.js",
  45090. "test:docs": "node scripts/docsLint.js",
  45091. "test:firefox": "npm test -- --browsers Firefox",
  45092. "test:chrome": "npm test -- --browsers Chrome",
  45093. "test:nobrowser": "NO_BROWSER=true npm test",
  45094. "test:node": "mocha --ui tdd tests/node"
  45095. },
  45096. "repository": "aframevr/aframe",
  45097. "license": "MIT",
  45098. "files": [
  45099. "dist/*",
  45100. "docs/**/*",
  45101. "src/**/*",
  45102. "vendor/**/*"
  45103. ],
  45104. "dependencies": {
  45105. "custom-event-polyfill": "^1.0.6",
  45106. "debug": "ngokevin/debug#noTimestamp",
  45107. "deep-assign": "^2.0.0",
  45108. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  45109. "load-bmfont": "^1.2.3",
  45110. "object-assign": "^4.0.1",
  45111. "present": "0.0.6",
  45112. "promise-polyfill": "^3.1.0",
  45113. "super-animejs": "^3.1.0",
  45114. "super-three": "^0.125.1",
  45115. "three-bmfont-text": "dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e",
  45116. "webvr-polyfill": "^0.10.12"
  45117. },
  45118. "devDependencies": {
  45119. "browserify": "^13.1.0",
  45120. "browserify-css": "^0.8.4",
  45121. "browserify-derequire": "^0.9.4",
  45122. "browserify-istanbul": "^2.0.0",
  45123. "budo": "^9.2.0",
  45124. "chai": "^3.5.0",
  45125. "chai-shallow-deep-equal": "^1.4.0",
  45126. "chalk": "^1.1.3",
  45127. "codecov": "^1.0.1",
  45128. "cross-env": "^5.0.1",
  45129. "envify": "^3.4.1",
  45130. "exorcist": "^0.4.0",
  45131. "ghpages": "0.0.8",
  45132. "git-rev": "^0.2.1",
  45133. "glob": "^7.1.1",
  45134. "husky": "^0.11.7",
  45135. "istanbul": "^0.4.5",
  45136. "jsdom": "^9.11.0",
  45137. "karma": "1.4.1",
  45138. "karma-browserify": "^5.1.0",
  45139. "karma-chai-shallow-deep-equal": "0.0.4",
  45140. "karma-chrome-launcher": "^2.0.0",
  45141. "karma-coverage": "^1.1.1",
  45142. "karma-env-preprocessor": "^0.1.1",
  45143. "karma-firefox-launcher": "^1.2.0",
  45144. "karma-mocha": "^1.1.1",
  45145. "karma-mocha-reporter": "^2.1.0",
  45146. "karma-sinon-chai": "1.2.4",
  45147. "lolex": "^1.5.1",
  45148. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  45149. "minifyify": "^7.3.3",
  45150. "mocha": "^3.0.2",
  45151. "mozilla-download": "^1.1.1",
  45152. "replace-in-file": "^2.5.3",
  45153. "semistandard": "^9.0.0",
  45154. "shelljs": "^0.7.7",
  45155. "shx": "^0.2.2",
  45156. "sinon": "^1.17.5",
  45157. "sinon-chai": "2.8.0",
  45158. "snazzy": "^5.0.0",
  45159. "too-wordy": "ngokevin/too-wordy",
  45160. "uglifyjs": "^2.4.10",
  45161. "write-good": "^0.9.1"
  45162. },
  45163. "link": true,
  45164. "browserify": {
  45165. "transform": [
  45166. "browserify-css",
  45167. "envify"
  45168. ]
  45169. },
  45170. "semistandard": {
  45171. "ignore": [
  45172. "build/**",
  45173. "dist/**",
  45174. "examples/**/shaders/*.js",
  45175. "**/vendor/**"
  45176. ]
  45177. },
  45178. "keywords": [
  45179. "3d",
  45180. "aframe",
  45181. "cardboard",
  45182. "components",
  45183. "oculus",
  45184. "three",
  45185. "three.js",
  45186. "rift",
  45187. "vive",
  45188. "vr",
  45189. "web-components",
  45190. "webvr"
  45191. ],
  45192. "browserify-css": {
  45193. "minify": true
  45194. },
  45195. "engines": {
  45196. "node": ">= 4.6.0",
  45197. "npm": "^2.15.9"
  45198. }
  45199. }
  45200. },{}],74:[function(_dereq_,module,exports){
  45201. var anime = _dereq_('super-animejs');
  45202. var components = _dereq_('../core/component').components;
  45203. var registerComponent = _dereq_('../core/component').registerComponent;
  45204. var THREE = _dereq_('../lib/three');
  45205. var utils = _dereq_('../utils');
  45206. var colorHelperFrom = new THREE.Color();
  45207. var colorHelperTo = new THREE.Color();
  45208. var getComponentProperty = utils.entity.getComponentProperty;
  45209. var setComponentProperty = utils.entity.setComponentProperty;
  45210. var splitCache = {};
  45211. var TYPE_COLOR = 'color';
  45212. var PROP_POSITION = 'position';
  45213. var PROP_ROTATION = 'rotation';
  45214. var PROP_SCALE = 'scale';
  45215. var STRING_COMPONENTS = 'components';
  45216. var STRING_OBJECT3D = 'object3D';
  45217. /**
  45218. * Animation component for A-Frame using anime.js.
  45219. *
  45220. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  45221. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  45222. * boolean * flag * `isAnimationPlaying`.
  45223. *
  45224. * anime.js animation config for tweenining Javascript objects and values works as:
  45225. *
  45226. * config = {
  45227. * targets: {foo: 0.0, bar: '#000'},
  45228. * foo: 1.0,
  45229. * bar: '#FFF'
  45230. * }
  45231. *
  45232. * The above will tween each property in `targets`. The `to` values are set in the root of
  45233. * the config.
  45234. *
  45235. * @member {object} animation - anime.js instance.
  45236. * @member {boolean} animationIsPlaying - Control if animation is playing.
  45237. */
  45238. module.exports.Component = registerComponent('animation', {
  45239. schema: {
  45240. autoplay: {default: true},
  45241. delay: {default: 0},
  45242. dir: {default: ''},
  45243. dur: {default: 1000},
  45244. easing: {default: 'easeInQuad'},
  45245. elasticity: {default: 400},
  45246. enabled: {default: true},
  45247. from: {default: ''},
  45248. loop: {
  45249. default: 0,
  45250. parse: function (value) {
  45251. // Boolean or integer.
  45252. if (value === true || value === 'true') { return true; }
  45253. if (value === false || value === 'false') { return false; }
  45254. return parseInt(value, 10);
  45255. }
  45256. },
  45257. property: {default: ''},
  45258. startEvents: {type: 'array'},
  45259. pauseEvents: {type: 'array'},
  45260. resumeEvents: {type: 'array'},
  45261. round: {default: false},
  45262. to: {default: ''},
  45263. type: {default: ''},
  45264. isRawProperty: {default: false}
  45265. },
  45266. multiple: true,
  45267. init: function () {
  45268. var self = this;
  45269. this.eventDetail = {name: this.attrName};
  45270. this.time = 0;
  45271. this.animation = null;
  45272. this.animationIsPlaying = false;
  45273. this.onStartEvent = this.onStartEvent.bind(this);
  45274. this.beginAnimation = this.beginAnimation.bind(this);
  45275. this.pauseAnimation = this.pauseAnimation.bind(this);
  45276. this.resumeAnimation = this.resumeAnimation.bind(this);
  45277. this.fromColor = {};
  45278. this.toColor = {};
  45279. this.targets = {};
  45280. this.targetsArray = [];
  45281. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  45282. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  45283. this.config = {
  45284. complete: function () {
  45285. self.animationIsPlaying = false;
  45286. self.el.emit('animationcomplete', self.eventDetail, false);
  45287. if (self.id) {
  45288. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  45289. }
  45290. }
  45291. };
  45292. },
  45293. update: function (oldData) {
  45294. var config = this.config;
  45295. var data = this.data;
  45296. this.animationIsPlaying = false;
  45297. if (!this.data.enabled) { return; }
  45298. if (!data.property) { return; }
  45299. // Base config.
  45300. config.autoplay = false;
  45301. config.direction = data.dir;
  45302. config.duration = data.dur;
  45303. config.easing = data.easing;
  45304. config.elasticity = data.elasticity;
  45305. config.loop = data.loop;
  45306. config.round = data.round;
  45307. // Start new animation.
  45308. this.createAndStartAnimation();
  45309. },
  45310. tick: function (t, dt) {
  45311. if (!this.animationIsPlaying) { return; }
  45312. this.time += dt;
  45313. this.animation.tick(this.time);
  45314. },
  45315. remove: function () {
  45316. this.pauseAnimation();
  45317. this.removeEventListeners();
  45318. },
  45319. pause: function () {
  45320. this.paused = true;
  45321. this.pausedWasPlaying = this.animationIsPlaying;
  45322. this.pauseAnimation();
  45323. this.removeEventListeners();
  45324. },
  45325. /**
  45326. * `play` handler only for resuming scene.
  45327. */
  45328. play: function () {
  45329. if (!this.paused) { return; }
  45330. this.paused = false;
  45331. this.addEventListeners();
  45332. if (this.pausedWasPlaying) {
  45333. this.resumeAnimation();
  45334. this.pausedWasPlaying = false;
  45335. }
  45336. },
  45337. /**
  45338. * Start animation from scratch.
  45339. */
  45340. createAndStartAnimation: function () {
  45341. var data = this.data;
  45342. this.updateConfig();
  45343. this.animationIsPlaying = false;
  45344. this.animation = anime(this.config);
  45345. this.animation.began = true;
  45346. this.removeEventListeners();
  45347. this.addEventListeners();
  45348. // Wait for start events for animation.
  45349. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  45350. // Delay animation.
  45351. if (data.delay) {
  45352. setTimeout(this.beginAnimation, data.delay);
  45353. return;
  45354. }
  45355. // Play animation.
  45356. this.beginAnimation();
  45357. },
  45358. /**
  45359. * This is before animation start (including from startEvents).
  45360. * Set to initial state (config.from, time = 0, seekTime = 0).
  45361. */
  45362. beginAnimation: function () {
  45363. this.updateConfig();
  45364. this.animation.began = true;
  45365. this.time = 0;
  45366. this.animationIsPlaying = true;
  45367. this.stopRelatedAnimations();
  45368. this.el.emit('animationbegin', this.eventDetail, false);
  45369. },
  45370. pauseAnimation: function () {
  45371. this.animationIsPlaying = false;
  45372. },
  45373. resumeAnimation: function () {
  45374. this.animationIsPlaying = true;
  45375. },
  45376. /**
  45377. * startEvents callback.
  45378. */
  45379. onStartEvent: function () {
  45380. if (!this.data.enabled) { return; }
  45381. this.updateConfig();
  45382. if (this.animation) {
  45383. this.animation.pause();
  45384. }
  45385. this.animation = anime(this.config);
  45386. // Include the delay before each start event.
  45387. if (this.data.delay) {
  45388. setTimeout(this.beginAnimation, this.data.delay);
  45389. return;
  45390. }
  45391. this.beginAnimation();
  45392. },
  45393. /**
  45394. * rawProperty: true and type: color;
  45395. */
  45396. updateConfigForRawColor: function () {
  45397. var config = this.config;
  45398. var data = this.data;
  45399. var el = this.el;
  45400. var from;
  45401. var key;
  45402. var to;
  45403. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  45404. return;
  45405. }
  45406. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  45407. to = data.to;
  45408. // Use r/g/b vector for color type.
  45409. this.setColorConfig(from, to);
  45410. from = this.fromColor;
  45411. to = this.toColor;
  45412. this.targetsArray.length = 0;
  45413. this.targetsArray.push(from);
  45414. config.targets = this.targetsArray;
  45415. for (key in to) { config[key] = to[key]; }
  45416. config.update = (function () {
  45417. var lastValue = {};
  45418. return function (anim) {
  45419. var value;
  45420. value = anim.animatables[0].target;
  45421. // For animation timeline.
  45422. if (value.r === lastValue.r &&
  45423. value.g === lastValue.g &&
  45424. value.b === lastValue.b) { return; }
  45425. setRawProperty(el, data.property, value, data.type);
  45426. };
  45427. })();
  45428. },
  45429. /**
  45430. * Stuff property into generic `property` key.
  45431. */
  45432. updateConfigForDefault: function () {
  45433. var config = this.config;
  45434. var data = this.data;
  45435. var el = this.el;
  45436. var from;
  45437. var isBoolean;
  45438. var isNumber;
  45439. var to;
  45440. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  45441. return;
  45442. }
  45443. if (data.from === '') {
  45444. // Infer from.
  45445. from = isRawProperty(data)
  45446. ? getRawProperty(el, data.property)
  45447. : getComponentProperty(el, data.property);
  45448. } else {
  45449. // Explicit from.
  45450. from = data.from;
  45451. }
  45452. to = data.to;
  45453. isNumber = !isNaN(from || to);
  45454. if (isNumber) {
  45455. from = parseFloat(from);
  45456. to = parseFloat(to);
  45457. } else {
  45458. from = from ? from.toString() : from;
  45459. to = to ? to.toString() : to;
  45460. }
  45461. // Convert booleans to integer to allow boolean flipping.
  45462. isBoolean = data.to === 'true' || data.to === 'false' ||
  45463. data.to === true || data.to === false;
  45464. if (isBoolean) {
  45465. from = data.from === 'true' || data.from === true ? 1 : 0;
  45466. to = data.to === 'true' || data.to === true ? 1 : 0;
  45467. }
  45468. this.targets.aframeProperty = from;
  45469. config.targets = this.targets;
  45470. config.aframeProperty = to;
  45471. config.update = (function () {
  45472. var lastValue;
  45473. return function (anim) {
  45474. var value;
  45475. value = anim.animatables[0].target.aframeProperty;
  45476. // Need to do a last value check for animation timeline since all the tweening
  45477. // begins simultaenously even if the value has not changed. Also better for perf
  45478. // anyways.
  45479. if (value === lastValue) { return; }
  45480. lastValue = value;
  45481. if (isBoolean) { value = value >= 1; }
  45482. if (isRawProperty(data)) {
  45483. setRawProperty(el, data.property, value, data.type);
  45484. } else {
  45485. setComponentProperty(el, data.property, value);
  45486. }
  45487. };
  45488. })();
  45489. },
  45490. /**
  45491. * Extend x/y/z/w onto the config.
  45492. * Update vector by modifying object3D.
  45493. */
  45494. updateConfigForVector: function () {
  45495. var config = this.config;
  45496. var data = this.data;
  45497. var el = this.el;
  45498. var key;
  45499. var from;
  45500. var to;
  45501. // Parse coordinates.
  45502. from = data.from !== ''
  45503. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  45504. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  45505. to = utils.coordinates.parse(data.to);
  45506. if (data.property === PROP_ROTATION) {
  45507. toRadians(from);
  45508. toRadians(to);
  45509. }
  45510. // Set to and from.
  45511. this.targetsArray.length = 0;
  45512. this.targetsArray.push(from);
  45513. config.targets = this.targetsArray;
  45514. for (key in to) { config[key] = to[key]; }
  45515. // If animating object3D transformation, run more optimized updater.
  45516. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  45517. data.property === PROP_SCALE) {
  45518. config.update = (function () {
  45519. var lastValue = {};
  45520. return function (anim) {
  45521. var value = anim.animatables[0].target;
  45522. if (data.property === PROP_SCALE) {
  45523. value.x = Math.max(0.0001, value.x);
  45524. value.y = Math.max(0.0001, value.y);
  45525. value.z = Math.max(0.0001, value.z);
  45526. }
  45527. // For animation timeline.
  45528. if (value.x === lastValue.x &&
  45529. value.y === lastValue.y &&
  45530. value.z === lastValue.z) { return; }
  45531. lastValue.x = value.x;
  45532. lastValue.y = value.y;
  45533. lastValue.z = value.z;
  45534. el.object3D[data.property].set(value.x, value.y, value.z);
  45535. };
  45536. })();
  45537. return;
  45538. }
  45539. // Animating some vector.
  45540. config.update = (function () {
  45541. var lastValue = {};
  45542. return function (anim) {
  45543. var value = anim.animatables[0].target;
  45544. // Animate rotation through radians.
  45545. // For animation timeline.
  45546. if (value.x === lastValue.x &&
  45547. value.y === lastValue.y &&
  45548. value.z === lastValue.z) { return; }
  45549. lastValue.x = value.x;
  45550. lastValue.y = value.y;
  45551. lastValue.z = value.z;
  45552. setComponentProperty(el, data.property, value);
  45553. };
  45554. })();
  45555. },
  45556. /**
  45557. * Update the config before each run.
  45558. */
  45559. updateConfig: function () {
  45560. var propType;
  45561. // Route config type.
  45562. propType = getPropertyType(this.el, this.data.property);
  45563. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  45564. this.updateConfigForRawColor();
  45565. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  45566. this.updateConfigForVector();
  45567. } else {
  45568. this.updateConfigForDefault();
  45569. }
  45570. },
  45571. /**
  45572. * Wait for component to initialize.
  45573. */
  45574. waitComponentInitRawProperty: function (cb) {
  45575. var componentName;
  45576. var data = this.data;
  45577. var el = this.el;
  45578. var self = this;
  45579. if (data.from !== '') { return false; }
  45580. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  45581. componentName = splitDot(data.property)[1];
  45582. if (el.components[componentName]) { return false; }
  45583. el.addEventListener('componentinitialized', function wait (evt) {
  45584. if (evt.detail.name !== componentName) { return; }
  45585. cb();
  45586. // Since the config was created async, create the animation now since we missed it
  45587. // earlier.
  45588. self.animation = anime(self.config);
  45589. el.removeEventListener('componentinitialized', wait);
  45590. });
  45591. return true;
  45592. },
  45593. /**
  45594. * Make sure two animations on the same property don't fight each other.
  45595. * e.g., animation__mouseenter="property: material.opacity"
  45596. * animation__mouseleave="property: material.opacity"
  45597. */
  45598. stopRelatedAnimations: function () {
  45599. var component;
  45600. var componentName;
  45601. for (componentName in this.el.components) {
  45602. component = this.el.components[componentName];
  45603. if (componentName === this.attrName) { continue; }
  45604. if (component.name !== 'animation') { continue; }
  45605. if (!component.animationIsPlaying) { continue; }
  45606. if (component.data.property !== this.data.property) { continue; }
  45607. component.animationIsPlaying = false;
  45608. }
  45609. },
  45610. addEventListeners: function () {
  45611. var data = this.data;
  45612. var el = this.el;
  45613. addEventListeners(el, data.startEvents, this.onStartEvent);
  45614. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45615. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45616. },
  45617. removeEventListeners: function () {
  45618. var data = this.data;
  45619. var el = this.el;
  45620. removeEventListeners(el, data.startEvents, this.onStartEvent);
  45621. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45622. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45623. },
  45624. setColorConfig: function (from, to) {
  45625. colorHelperFrom.set(from);
  45626. colorHelperTo.set(to);
  45627. from = this.fromColor;
  45628. to = this.toColor;
  45629. from.r = colorHelperFrom.r;
  45630. from.g = colorHelperFrom.g;
  45631. from.b = colorHelperFrom.b;
  45632. to.r = colorHelperTo.r;
  45633. to.g = colorHelperTo.g;
  45634. to.b = colorHelperTo.b;
  45635. }
  45636. });
  45637. /**
  45638. * Given property name, check schema to see what type we are animating.
  45639. * We just care whether the property is a vector.
  45640. */
  45641. function getPropertyType (el, property) {
  45642. var component;
  45643. var componentName;
  45644. var split;
  45645. var propertyName;
  45646. split = property.split('.');
  45647. componentName = split[0];
  45648. propertyName = split[1];
  45649. component = el.components[componentName] || components[componentName];
  45650. // Primitives.
  45651. if (!component) { return null; }
  45652. // Dynamic schema. We only care about vectors anyways.
  45653. if (propertyName && !component.schema[propertyName]) { return null; }
  45654. // Multi-prop.
  45655. if (propertyName) { return component.schema[propertyName].type; }
  45656. // Single-prop.
  45657. return component.schema.type;
  45658. }
  45659. /**
  45660. * Convert object to radians.
  45661. */
  45662. function toRadians (obj) {
  45663. obj.x = THREE.Math.degToRad(obj.x);
  45664. obj.y = THREE.Math.degToRad(obj.y);
  45665. obj.z = THREE.Math.degToRad(obj.z);
  45666. }
  45667. function addEventListeners (el, eventNames, handler) {
  45668. var i;
  45669. for (i = 0; i < eventNames.length; i++) {
  45670. el.addEventListener(eventNames[i], handler);
  45671. }
  45672. }
  45673. function removeEventListeners (el, eventNames, handler) {
  45674. var i;
  45675. for (i = 0; i < eventNames.length; i++) {
  45676. el.removeEventListener(eventNames[i], handler);
  45677. }
  45678. }
  45679. function getRawProperty (el, path) {
  45680. var i;
  45681. var split;
  45682. var value;
  45683. split = splitDot(path);
  45684. value = el;
  45685. for (i = 0; i < split.length; i++) {
  45686. value = value[split[i]];
  45687. }
  45688. if (value === undefined) {
  45689. console.log(el);
  45690. throw new Error('[animation] property (' + path + ') could not be found');
  45691. }
  45692. return value;
  45693. }
  45694. function setRawProperty (el, path, value, type) {
  45695. var i;
  45696. var split;
  45697. var propertyName;
  45698. var targetValue;
  45699. if (path.startsWith('object3D.rotation')) {
  45700. value = THREE.Math.degToRad(value);
  45701. }
  45702. // Walk.
  45703. split = splitDot(path);
  45704. targetValue = el;
  45705. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  45706. propertyName = split[split.length - 1];
  45707. // Raw color.
  45708. if (type === TYPE_COLOR) {
  45709. if ('r' in targetValue[propertyName]) {
  45710. targetValue[propertyName].r = value.r;
  45711. targetValue[propertyName].g = value.g;
  45712. targetValue[propertyName].b = value.b;
  45713. } else {
  45714. targetValue[propertyName].x = value.r;
  45715. targetValue[propertyName].y = value.g;
  45716. targetValue[propertyName].z = value.b;
  45717. }
  45718. return;
  45719. }
  45720. targetValue[propertyName] = value;
  45721. }
  45722. function splitDot (path) {
  45723. if (path in splitCache) { return splitCache[path]; }
  45724. splitCache[path] = path.split('.');
  45725. return splitCache[path];
  45726. }
  45727. function isRawProperty (data) {
  45728. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  45729. data.property.startsWith(STRING_OBJECT3D);
  45730. }
  45731. },{"../core/component":132,"../lib/three":180,"../utils":206,"super-animejs":56}],75:[function(_dereq_,module,exports){
  45732. var registerComponent = _dereq_('../core/component').registerComponent;
  45733. var THREE = _dereq_('../lib/three');
  45734. /**
  45735. * Camera component.
  45736. * Pairs along with camera system to handle tracking the active camera.
  45737. */
  45738. module.exports.Component = registerComponent('camera', {
  45739. schema: {
  45740. active: {default: true},
  45741. far: {default: 10000},
  45742. fov: {default: 80, min: 0},
  45743. near: {default: 0.005, min: 0},
  45744. spectator: {default: false},
  45745. zoom: {default: 1, min: 0}
  45746. },
  45747. /**
  45748. * Initialize three.js camera and add it to the entity.
  45749. * Add reference from scene to this entity as the camera.
  45750. */
  45751. init: function () {
  45752. var camera;
  45753. var el = this.el;
  45754. // Create camera.
  45755. camera = this.camera = new THREE.PerspectiveCamera();
  45756. el.setObject3D('camera', camera);
  45757. },
  45758. /**
  45759. * Update three.js camera.
  45760. */
  45761. update: function (oldData) {
  45762. var data = this.data;
  45763. var camera = this.camera;
  45764. // Update properties.
  45765. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  45766. camera.far = data.far;
  45767. camera.fov = data.fov;
  45768. camera.near = data.near;
  45769. camera.zoom = data.zoom;
  45770. camera.updateProjectionMatrix();
  45771. this.updateActiveCamera(oldData);
  45772. this.updateSpectatorCamera(oldData);
  45773. },
  45774. updateActiveCamera: function (oldData) {
  45775. var data = this.data;
  45776. var el = this.el;
  45777. var system = this.system;
  45778. // Active property did not change.
  45779. if (oldData && oldData.active === data.active || data.spectator) { return; }
  45780. // If `active` property changes, or first update, handle active camera with system.
  45781. if (data.active && system.activeCameraEl !== el) {
  45782. // Camera enabled. Set camera to this camera.
  45783. system.setActiveCamera(el);
  45784. } else if (!data.active && system.activeCameraEl === el) {
  45785. // Camera disabled. Set camera to another camera.
  45786. system.disableActiveCamera();
  45787. }
  45788. },
  45789. updateSpectatorCamera: function (oldData) {
  45790. var data = this.data;
  45791. var el = this.el;
  45792. var system = this.system;
  45793. // spectator property did not change.
  45794. if (oldData && oldData.spectator === data.spectator) { return; }
  45795. // If `spectator` property changes, or first update, handle spectator camera with system.
  45796. if (data.spectator && system.spectatorCameraEl !== el) {
  45797. // Camera enabled. Set camera to this camera.
  45798. system.setSpectatorCamera(el);
  45799. } else if (!data.spectator && system.spectatorCameraEl === el) {
  45800. // Camera disabled. Set camera to another camera.
  45801. system.disableSpectatorCamera();
  45802. }
  45803. },
  45804. /**
  45805. * Remove camera on remove (callback).
  45806. */
  45807. remove: function () {
  45808. this.el.removeObject3D('camera');
  45809. }
  45810. });
  45811. },{"../core/component":132,"../lib/three":180}],76:[function(_dereq_,module,exports){
  45812. /* global THREE */
  45813. var registerComponent = _dereq_('../core/component').registerComponent;
  45814. var utils = _dereq_('../utils/');
  45815. var bind = utils.bind;
  45816. var EVENTS = {
  45817. CLICK: 'click',
  45818. FUSING: 'fusing',
  45819. MOUSEENTER: 'mouseenter',
  45820. MOUSEDOWN: 'mousedown',
  45821. MOUSELEAVE: 'mouseleave',
  45822. MOUSEUP: 'mouseup'
  45823. };
  45824. var STATES = {
  45825. FUSING: 'cursor-fusing',
  45826. HOVERING: 'cursor-hovering',
  45827. HOVERED: 'cursor-hovered'
  45828. };
  45829. var CANVAS_EVENTS = {
  45830. DOWN: ['mousedown', 'touchstart'],
  45831. UP: ['mouseup', 'touchend']
  45832. };
  45833. var WEBXR_EVENTS = {
  45834. DOWN: ['selectstart'],
  45835. UP: ['selectend']
  45836. };
  45837. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  45838. /**
  45839. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  45840. * from the camera and pointing from camera's facing direction, and then only returning the
  45841. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  45842. *
  45843. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  45844. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  45845. * @member {object} intersection - Attributes of the current intersection event, including
  45846. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  45847. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  45848. * emit events when unintersecting.
  45849. */
  45850. module.exports.Component = registerComponent('cursor', {
  45851. dependencies: ['raycaster'],
  45852. schema: {
  45853. downEvents: {default: []},
  45854. fuse: {default: utils.device.isMobile()},
  45855. fuseTimeout: {default: 1500, min: 0},
  45856. mouseCursorStylesEnabled: {default: true},
  45857. upEvents: {default: []},
  45858. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  45859. },
  45860. init: function () {
  45861. var self = this;
  45862. this.fuseTimeout = undefined;
  45863. this.cursorDownEl = null;
  45864. this.intersectedEl = null;
  45865. this.canvasBounds = document.body.getBoundingClientRect();
  45866. this.isCursorDown = false;
  45867. // Debounce.
  45868. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  45869. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  45870. }, 500);
  45871. this.eventDetail = {};
  45872. this.intersectedEventDetail = {cursorEl: this.el};
  45873. // Bind methods.
  45874. this.onCursorDown = bind(this.onCursorDown, this);
  45875. this.onCursorUp = bind(this.onCursorUp, this);
  45876. this.onIntersection = bind(this.onIntersection, this);
  45877. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  45878. this.onMouseMove = bind(this.onMouseMove, this);
  45879. this.onEnterVR = bind(this.onEnterVR, this);
  45880. },
  45881. update: function (oldData) {
  45882. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  45883. this.updateMouseEventListeners();
  45884. },
  45885. play: function () {
  45886. this.addEventListeners();
  45887. },
  45888. pause: function () {
  45889. this.removeEventListeners();
  45890. },
  45891. remove: function () {
  45892. var el = this.el;
  45893. el.removeState(STATES.HOVERING);
  45894. el.removeState(STATES.FUSING);
  45895. clearTimeout(this.fuseTimeout);
  45896. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  45897. this.removeEventListeners();
  45898. },
  45899. addEventListeners: function () {
  45900. var canvas;
  45901. var data = this.data;
  45902. var el = this.el;
  45903. var self = this;
  45904. function addCanvasListeners () {
  45905. canvas = el.sceneEl.canvas;
  45906. if (data.downEvents.length || data.upEvents.length) { return; }
  45907. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  45908. canvas.addEventListener(downEvent, self.onCursorDown);
  45909. });
  45910. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  45911. canvas.addEventListener(upEvent, self.onCursorUp);
  45912. });
  45913. }
  45914. canvas = el.sceneEl.canvas;
  45915. if (canvas) {
  45916. addCanvasListeners();
  45917. } else {
  45918. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  45919. }
  45920. data.downEvents.forEach(function (downEvent) {
  45921. el.addEventListener(downEvent, self.onCursorDown);
  45922. });
  45923. data.upEvents.forEach(function (upEvent) {
  45924. el.addEventListener(upEvent, self.onCursorUp);
  45925. });
  45926. el.addEventListener('raycaster-intersection', this.onIntersection);
  45927. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  45928. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  45929. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  45930. window.addEventListener('resize', this.updateCanvasBounds);
  45931. window.addEventListener('scroll', this.updateCanvasBounds);
  45932. this.updateMouseEventListeners();
  45933. },
  45934. removeEventListeners: function () {
  45935. var canvas;
  45936. var data = this.data;
  45937. var el = this.el;
  45938. var self = this;
  45939. canvas = el.sceneEl.canvas;
  45940. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  45941. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  45942. canvas.removeEventListener(downEvent, self.onCursorDown);
  45943. });
  45944. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  45945. canvas.removeEventListener(upEvent, self.onCursorUp);
  45946. });
  45947. }
  45948. data.downEvents.forEach(function (downEvent) {
  45949. el.removeEventListener(downEvent, self.onCursorDown);
  45950. });
  45951. data.upEvents.forEach(function (upEvent) {
  45952. el.removeEventListener(upEvent, self.onCursorUp);
  45953. });
  45954. el.removeEventListener('raycaster-intersection', this.onIntersection);
  45955. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  45956. canvas.removeEventListener('mousemove', this.onMouseMove);
  45957. canvas.removeEventListener('touchstart', this.onMouseMove);
  45958. canvas.removeEventListener('touchmove', this.onMouseMove);
  45959. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  45960. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  45961. window.removeEventListener('resize', this.updateCanvasBounds);
  45962. window.removeEventListener('scroll', this.updateCanvasBounds);
  45963. },
  45964. updateMouseEventListeners: function () {
  45965. var canvas;
  45966. var el = this.el;
  45967. canvas = el.sceneEl.canvas;
  45968. canvas.removeEventListener('mousemove', this.onMouseMove);
  45969. canvas.removeEventListener('touchmove', this.onMouseMove);
  45970. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  45971. if (this.data.rayOrigin !== 'mouse') { return; }
  45972. canvas.addEventListener('mousemove', this.onMouseMove, false);
  45973. canvas.addEventListener('touchmove', this.onMouseMove, false);
  45974. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  45975. this.updateCanvasBounds();
  45976. },
  45977. onMouseMove: (function () {
  45978. var direction = new THREE.Vector3();
  45979. var mouse = new THREE.Vector2();
  45980. var origin = new THREE.Vector3();
  45981. var rayCasterConfig = {origin: origin, direction: direction};
  45982. return function (evt) {
  45983. var bounds = this.canvasBounds;
  45984. var camera = this.el.sceneEl.camera;
  45985. var left;
  45986. var point;
  45987. var top;
  45988. camera.parent.updateMatrixWorld();
  45989. // Calculate mouse position based on the canvas element
  45990. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  45991. // Track the first touch for simplicity.
  45992. point = evt.touches.item(0);
  45993. } else {
  45994. point = evt;
  45995. }
  45996. left = point.clientX - bounds.left;
  45997. top = point.clientY - bounds.top;
  45998. mouse.x = (left / bounds.width) * 2 - 1;
  45999. mouse.y = -(top / bounds.height) * 2 + 1;
  46000. origin.setFromMatrixPosition(camera.matrixWorld);
  46001. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  46002. this.el.setAttribute('raycaster', rayCasterConfig);
  46003. if (evt.type === 'touchmove') { evt.preventDefault(); }
  46004. };
  46005. })(),
  46006. /**
  46007. * Trigger mousedown and keep track of the mousedowned entity.
  46008. */
  46009. onCursorDown: function (evt) {
  46010. this.isCursorDown = true;
  46011. // Raycast again for touch.
  46012. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  46013. this.onMouseMove(evt);
  46014. this.el.components.raycaster.checkIntersections();
  46015. evt.preventDefault();
  46016. }
  46017. this.twoWayEmit(EVENTS.MOUSEDOWN);
  46018. this.cursorDownEl = this.intersectedEl;
  46019. },
  46020. /**
  46021. * Trigger mouseup if:
  46022. * - Not fusing (mobile has no mouse).
  46023. * - Currently intersecting an entity.
  46024. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  46025. * in case user mousedowned one entity, dragged to another, and mouseupped.
  46026. */
  46027. onCursorUp: function (evt) {
  46028. if (!this.isCursorDown) { return; }
  46029. this.isCursorDown = false;
  46030. var data = this.data;
  46031. this.twoWayEmit(EVENTS.MOUSEUP);
  46032. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  46033. // previously cursorUp entity.
  46034. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  46035. this.intersectedEventDetail.intersection = null;
  46036. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  46037. }
  46038. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  46039. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  46040. this.twoWayEmit(EVENTS.CLICK);
  46041. }
  46042. this.cursorDownEl = null;
  46043. if (evt.type === 'touchend') { evt.preventDefault(); }
  46044. },
  46045. /**
  46046. * Handle intersection.
  46047. */
  46048. onIntersection: function (evt) {
  46049. var currentIntersection;
  46050. var cursorEl = this.el;
  46051. var index;
  46052. var intersectedEl;
  46053. var intersection;
  46054. // Select closest object, excluding the cursor.
  46055. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  46056. intersection = evt.detail.intersections[index];
  46057. intersectedEl = evt.detail.els[index];
  46058. // If cursor is the only intersected object, ignore the event.
  46059. if (!intersectedEl) { return; }
  46060. // Already intersecting this entity.
  46061. if (this.intersectedEl === intersectedEl) { return; }
  46062. // Ignore events further away than active intersection.
  46063. if (this.intersectedEl) {
  46064. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  46065. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  46066. }
  46067. // Unset current intersection.
  46068. this.clearCurrentIntersection(true);
  46069. this.setIntersection(intersectedEl, intersection);
  46070. },
  46071. /**
  46072. * Handle intersection cleared.
  46073. */
  46074. onIntersectionCleared: function (evt) {
  46075. var clearedEls = evt.detail.clearedEls;
  46076. // Check if the current intersection has ended
  46077. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  46078. this.clearCurrentIntersection();
  46079. },
  46080. onEnterVR: function () {
  46081. this.clearCurrentIntersection(true);
  46082. var xrSession = this.el.sceneEl.xrSession;
  46083. var self = this;
  46084. if (!xrSession) { return; }
  46085. if (this.data.rayOrigin === 'mouse') { return; }
  46086. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  46087. xrSession.addEventListener(downEvent, self.onCursorDown);
  46088. });
  46089. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  46090. xrSession.addEventListener(upEvent, self.onCursorUp);
  46091. });
  46092. },
  46093. setIntersection: function (intersectedEl, intersection) {
  46094. var cursorEl = this.el;
  46095. var data = this.data;
  46096. var self = this;
  46097. // Already intersecting.
  46098. if (this.intersectedEl === intersectedEl) { return; }
  46099. // Set new intersection.
  46100. this.intersectedEl = intersectedEl;
  46101. // Hovering.
  46102. cursorEl.addState(STATES.HOVERING);
  46103. intersectedEl.addState(STATES.HOVERED);
  46104. this.twoWayEmit(EVENTS.MOUSEENTER);
  46105. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46106. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  46107. }
  46108. // Begin fuse if necessary.
  46109. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  46110. cursorEl.addState(STATES.FUSING);
  46111. this.twoWayEmit(EVENTS.FUSING);
  46112. this.fuseTimeout = setTimeout(function fuse () {
  46113. cursorEl.removeState(STATES.FUSING);
  46114. self.twoWayEmit(EVENTS.CLICK);
  46115. }, data.fuseTimeout);
  46116. },
  46117. clearCurrentIntersection: function (ignoreRemaining) {
  46118. var index;
  46119. var intersection;
  46120. var intersections;
  46121. var cursorEl = this.el;
  46122. // Nothing to be cleared.
  46123. if (!this.intersectedEl) { return; }
  46124. // No longer hovering (or fusing).
  46125. this.intersectedEl.removeState(STATES.HOVERED);
  46126. cursorEl.removeState(STATES.HOVERING);
  46127. cursorEl.removeState(STATES.FUSING);
  46128. this.twoWayEmit(EVENTS.MOUSELEAVE);
  46129. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46130. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  46131. }
  46132. // Unset intersected entity (after emitting the event).
  46133. this.intersectedEl = null;
  46134. // Clear fuseTimeout.
  46135. clearTimeout(this.fuseTimeout);
  46136. // Set intersection to another raycasted element if any.
  46137. if (ignoreRemaining === true) { return; }
  46138. intersections = this.el.components.raycaster.intersections;
  46139. if (intersections.length === 0) { return; }
  46140. // Exclude the cursor.
  46141. index = intersections[0].object.el === cursorEl ? 1 : 0;
  46142. intersection = intersections[index];
  46143. if (!intersection) { return; }
  46144. this.setIntersection(intersection.object.el, intersection);
  46145. },
  46146. /**
  46147. * Helper to emit on both the cursor and the intersected entity (if exists).
  46148. */
  46149. twoWayEmit: function (evtName) {
  46150. var el = this.el;
  46151. var intersectedEl = this.intersectedEl;
  46152. var intersection;
  46153. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  46154. this.eventDetail.intersectedEl = intersectedEl;
  46155. this.eventDetail.intersection = intersection;
  46156. el.emit(evtName, this.eventDetail);
  46157. if (!intersectedEl) { return; }
  46158. this.intersectedEventDetail.intersection = intersection;
  46159. intersectedEl.emit(evtName, this.intersectedEventDetail);
  46160. }
  46161. });
  46162. },{"../core/component":132,"../utils/":206}],77:[function(_dereq_,module,exports){
  46163. var registerComponent = _dereq_('../core/component').registerComponent;
  46164. var bind = _dereq_('../utils/bind');
  46165. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46166. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46167. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46168. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46169. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  46170. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  46171. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  46172. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46173. var GAMEPAD_ID_WEBXR = 'google-daydream';
  46174. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  46175. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46176. /**
  46177. * Button indices:
  46178. * 0 - trackpad
  46179. * 1 - menu (never dispatched on this layer)
  46180. * 2 - system (never dispatched on this layer)
  46181. *
  46182. * Axis:
  46183. * 0 - trackpad x
  46184. * 1 - trackpad y
  46185. */
  46186. var INPUT_MAPPING_WEBVR = {
  46187. axes: {trackpad: [0, 1]},
  46188. buttons: ['trackpad', 'menu', 'system']
  46189. };
  46190. /**
  46191. * Button indices:
  46192. * 0 - none
  46193. * 1 - none
  46194. * 2 - touchpad
  46195. *
  46196. * Axis:
  46197. * 0 - touchpad x
  46198. * 1 - touchpad y
  46199. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/google/google-daydream.json
  46200. */
  46201. var INPUT_MAPPING_WEBXR = {
  46202. axes: {touchpad: [0, 1]},
  46203. buttons: ['none', 'none', 'touchpad', 'menu', 'system']
  46204. };
  46205. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46206. /**
  46207. * Daydream controls.
  46208. * Interface with Daydream controller and map Gamepad events to
  46209. * controller buttons: trackpad, menu, system
  46210. * Load a controller model and highlight the pressed buttons.
  46211. */
  46212. module.exports.Component = registerComponent('daydream-controls', {
  46213. schema: {
  46214. hand: {default: ''}, // This informs the degenerate arm model.
  46215. buttonColor: {type: 'color', default: '#000000'},
  46216. buttonTouchedColor: {type: 'color', default: '#777777'},
  46217. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46218. model: {default: true},
  46219. orientationOffset: {type: 'vec3'},
  46220. armModel: {default: true}
  46221. },
  46222. mapping: INPUT_MAPPING,
  46223. bindMethods: function () {
  46224. this.onModelLoaded = bind(this.onModelLoaded, this);
  46225. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46226. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46227. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46228. this.onAxisMoved = bind(this.onAxisMoved, this);
  46229. },
  46230. init: function () {
  46231. var self = this;
  46232. this.onButtonChanged = bind(this.onButtonChanged, this);
  46233. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46234. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46235. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46236. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46237. this.controllerPresent = false;
  46238. this.lastControllerCheck = 0;
  46239. this.bindMethods();
  46240. },
  46241. addEventListeners: function () {
  46242. var el = this.el;
  46243. el.addEventListener('buttonchanged', this.onButtonChanged);
  46244. el.addEventListener('buttondown', this.onButtonDown);
  46245. el.addEventListener('buttonup', this.onButtonUp);
  46246. el.addEventListener('touchstart', this.onButtonTouchStart);
  46247. el.addEventListener('touchend', this.onButtonTouchEnd);
  46248. el.addEventListener('model-loaded', this.onModelLoaded);
  46249. el.addEventListener('axismove', this.onAxisMoved);
  46250. this.controllerEventsActive = true;
  46251. },
  46252. removeEventListeners: function () {
  46253. var el = this.el;
  46254. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46255. el.removeEventListener('buttondown', this.onButtonDown);
  46256. el.removeEventListener('buttonup', this.onButtonUp);
  46257. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46258. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46259. el.removeEventListener('model-loaded', this.onModelLoaded);
  46260. el.removeEventListener('axismove', this.onAxisMoved);
  46261. this.controllerEventsActive = false;
  46262. },
  46263. checkIfControllerPresent: function () {
  46264. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46265. this.data.hand ? {hand: this.data.hand} : {});
  46266. },
  46267. play: function () {
  46268. this.checkIfControllerPresent();
  46269. this.addControllersUpdateListener();
  46270. },
  46271. pause: function () {
  46272. this.removeEventListeners();
  46273. this.removeControllersUpdateListener();
  46274. },
  46275. injectTrackedControls: function () {
  46276. var el = this.el;
  46277. var data = this.data;
  46278. el.setAttribute('tracked-controls', {
  46279. armModel: data.armModel,
  46280. hand: data.hand,
  46281. idPrefix: GAMEPAD_ID_PREFIX,
  46282. id: GAMEPAD_ID_PREFIX,
  46283. orientationOffset: data.orientationOffset
  46284. });
  46285. if (!this.data.model) { return; }
  46286. this.el.setAttribute('obj-model', {
  46287. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  46288. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  46289. });
  46290. },
  46291. addControllersUpdateListener: function () {
  46292. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46293. },
  46294. removeControllersUpdateListener: function () {
  46295. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46296. },
  46297. onControllersUpdate: function () {
  46298. this.checkIfControllerPresent();
  46299. },
  46300. onModelLoaded: function (evt) {
  46301. var controllerObject3D = evt.detail.model;
  46302. var buttonMeshes;
  46303. if (!this.data.model) { return; }
  46304. buttonMeshes = this.buttonMeshes = {};
  46305. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  46306. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  46307. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46308. buttonMeshes.touchpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46309. // Offset pivot point.
  46310. controllerObject3D.position.set(0, 0, -0.04);
  46311. },
  46312. onAxisMoved: function (evt) {
  46313. emitIfAxesChanged(this, this.mapping.axes, evt);
  46314. },
  46315. onButtonChanged: function (evt) {
  46316. var button = this.mapping.buttons[evt.detail.id];
  46317. if (!button) return;
  46318. // Pass along changed event with button state, using button mapping for convenience.
  46319. this.el.emit(button + 'changed', evt.detail.state);
  46320. },
  46321. updateModel: function (buttonName, evtName) {
  46322. if (!this.data.model) { return; }
  46323. this.updateButtonModel(buttonName, evtName);
  46324. },
  46325. updateButtonModel: function (buttonName, state) {
  46326. var buttonMeshes = this.buttonMeshes;
  46327. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46328. var color;
  46329. switch (state) {
  46330. case 'down':
  46331. color = this.data.buttonHighlightColor;
  46332. break;
  46333. case 'touchstart':
  46334. color = this.data.buttonTouchedColor;
  46335. break;
  46336. default:
  46337. color = this.data.buttonColor;
  46338. }
  46339. buttonMeshes[buttonName].material.color.set(color);
  46340. }
  46341. });
  46342. },{"../core/component":132,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],78:[function(_dereq_,module,exports){
  46343. var registerComponent = _dereq_('../core/component').registerComponent;
  46344. var bind = _dereq_('../utils/bind');
  46345. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46346. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46347. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46348. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46349. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46350. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  46351. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  46352. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  46353. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  46354. var GAMEPAD_ID_WEBVR = 'Gear VR';
  46355. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  46356. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46357. /**
  46358. * Button indices:
  46359. * 0 - trackpad
  46360. * 1 - trigger
  46361. *
  46362. * Axis:
  46363. * 0 - trackpad x
  46364. * 1 - trackpad y
  46365. */
  46366. var INPUT_MAPPING_WEBVR = {
  46367. axes: {trackpad: [0, 1]},
  46368. buttons: ['trackpad', 'trigger']
  46369. };
  46370. /**
  46371. * Button indices:
  46372. * 0 - trigger
  46373. * 1 - none
  46374. * 2 - touchpad
  46375. * 3 - menu
  46376. *
  46377. * Axis:
  46378. * 0 - touchpad x
  46379. * 1 - touchpad y
  46380. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/samsung/samsung-gearvr.json
  46381. */
  46382. var INPUT_MAPPING_WEBXR = {
  46383. axes: {touchpad: [0, 1]},
  46384. buttons: ['trigger', 'none', 'touchpad', 'none', 'menu']
  46385. };
  46386. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46387. /**
  46388. * Gear VR controls.
  46389. * Interface with Gear VR controller and map Gamepad events to
  46390. * controller buttons: trackpad, trigger
  46391. * Load a controller model and highlight the pressed buttons.
  46392. */
  46393. module.exports.Component = registerComponent('gearvr-controls', {
  46394. schema: {
  46395. hand: {default: ''}, // This informs the degenerate arm model.
  46396. buttonColor: {type: 'color', default: '#000000'},
  46397. buttonTouchedColor: {type: 'color', default: '#777777'},
  46398. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46399. model: {default: true},
  46400. orientationOffset: {type: 'vec3'},
  46401. armModel: {default: true}
  46402. },
  46403. mapping: INPUT_MAPPING,
  46404. bindMethods: function () {
  46405. this.onModelLoaded = bind(this.onModelLoaded, this);
  46406. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46407. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46408. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46409. this.onAxisMoved = bind(this.onAxisMoved, this);
  46410. },
  46411. init: function () {
  46412. var self = this;
  46413. this.onButtonChanged = bind(this.onButtonChanged, this);
  46414. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46415. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46416. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46417. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46418. this.controllerPresent = false;
  46419. this.lastControllerCheck = 0;
  46420. this.bindMethods();
  46421. },
  46422. addEventListeners: function () {
  46423. var el = this.el;
  46424. el.addEventListener('buttonchanged', this.onButtonChanged);
  46425. el.addEventListener('buttondown', this.onButtonDown);
  46426. el.addEventListener('buttonup', this.onButtonUp);
  46427. el.addEventListener('touchstart', this.onButtonTouchStart);
  46428. el.addEventListener('touchend', this.onButtonTouchEnd);
  46429. el.addEventListener('model-loaded', this.onModelLoaded);
  46430. el.addEventListener('axismove', this.onAxisMoved);
  46431. this.controllerEventsActive = true;
  46432. },
  46433. removeEventListeners: function () {
  46434. var el = this.el;
  46435. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46436. el.removeEventListener('buttondown', this.onButtonDown);
  46437. el.removeEventListener('buttonup', this.onButtonUp);
  46438. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46439. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46440. el.removeEventListener('model-loaded', this.onModelLoaded);
  46441. el.removeEventListener('axismove', this.onAxisMoved);
  46442. this.controllerEventsActive = false;
  46443. },
  46444. checkIfControllerPresent: function () {
  46445. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46446. this.data.hand ? {hand: this.data.hand} : {});
  46447. },
  46448. play: function () {
  46449. this.checkIfControllerPresent();
  46450. this.addControllersUpdateListener();
  46451. },
  46452. pause: function () {
  46453. this.removeEventListeners();
  46454. this.removeControllersUpdateListener();
  46455. },
  46456. injectTrackedControls: function () {
  46457. var el = this.el;
  46458. var data = this.data;
  46459. el.setAttribute('tracked-controls', {
  46460. armModel: data.armModel,
  46461. hand: data.hand,
  46462. idPrefix: GAMEPAD_ID_PREFIX,
  46463. id: GAMEPAD_ID_PREFIX,
  46464. orientationOffset: data.orientationOffset
  46465. });
  46466. if (!this.data.model) { return; }
  46467. this.el.setAttribute('obj-model', {
  46468. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  46469. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  46470. });
  46471. },
  46472. addControllersUpdateListener: function () {
  46473. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46474. },
  46475. removeControllersUpdateListener: function () {
  46476. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46477. },
  46478. onControllersUpdate: function () {
  46479. this.checkIfControllerPresent();
  46480. },
  46481. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  46482. onModelLoaded: function (evt) {
  46483. var controllerObject3D = evt.detail.model;
  46484. var buttonMeshes;
  46485. if (!this.data.model) { return; }
  46486. buttonMeshes = this.buttonMeshes = {};
  46487. buttonMeshes.trigger = controllerObject3D.children[2];
  46488. buttonMeshes.trackpad = controllerObject3D.children[1];
  46489. buttonMeshes.touchpad = controllerObject3D.children[1];
  46490. },
  46491. onButtonChanged: function (evt) {
  46492. var button = this.mapping.buttons[evt.detail.id];
  46493. if (!button) return;
  46494. // Pass along changed event with button state, using button mapping for convenience.
  46495. this.el.emit(button + 'changed', evt.detail.state);
  46496. },
  46497. onAxisMoved: function (evt) {
  46498. emitIfAxesChanged(this, this.mapping.axes, evt);
  46499. },
  46500. updateModel: function (buttonName, evtName) {
  46501. if (!this.data.model) { return; }
  46502. this.updateButtonModel(buttonName, evtName);
  46503. },
  46504. updateButtonModel: function (buttonName, state) {
  46505. var buttonMeshes = this.buttonMeshes;
  46506. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46507. var color;
  46508. switch (state) {
  46509. case 'down':
  46510. color = this.data.buttonHighlightColor;
  46511. break;
  46512. case 'touchstart':
  46513. color = this.data.buttonTouchedColor;
  46514. break;
  46515. default:
  46516. color = this.data.buttonColor;
  46517. }
  46518. buttonMeshes[buttonName].material.color.set(color);
  46519. }
  46520. });
  46521. },{"../core/component":132,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],79:[function(_dereq_,module,exports){
  46522. var registerComponent = _dereq_('../core/component').registerComponent;
  46523. var bind = _dereq_('../utils/bind');
  46524. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46525. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46526. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46527. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46528. var GAMEPAD_ID_PREFIX = 'generic';
  46529. /**
  46530. * Button indices:
  46531. * 0 - trigger
  46532. * 1 - squeeze
  46533. * 2 - touchpad
  46534. * 3 - thumbstick
  46535. *
  46536. * Axis:
  46537. * 0 - touchpad
  46538. * 1 - thumbstick
  46539. *
  46540. */
  46541. var INPUT_MAPPING = {
  46542. axes: {
  46543. touchpad: [0, 1],
  46544. thumbstick: [2, 3]
  46545. },
  46546. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  46547. };
  46548. /**
  46549. * Oculus Go controls.
  46550. * Interface with Oculus Go controller and map Gamepad events to
  46551. * controller buttons: trackpad, trigger
  46552. * Load a controller model and highlight the pressed buttons.
  46553. */
  46554. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  46555. schema: {
  46556. hand: {default: ''}, // This informs the degenerate arm model.
  46557. defaultModel: {default: true},
  46558. defaultModelColor: {default: 'gray'},
  46559. orientationOffset: {type: 'vec3'},
  46560. disabled: {default: false}
  46561. },
  46562. /**
  46563. * Button IDs:
  46564. * 0 - trackpad
  46565. * 1 - trigger
  46566. */
  46567. mapping: INPUT_MAPPING,
  46568. bindMethods: function () {
  46569. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46570. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46571. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46572. this.onAxisMoved = bind(this.onAxisMoved, this);
  46573. },
  46574. init: function () {
  46575. var self = this;
  46576. this.onButtonChanged = bind(this.onButtonChanged, this);
  46577. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46578. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46579. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46580. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46581. this.controllerPresent = false;
  46582. this.wasControllerConnected = false;
  46583. this.lastControllerCheck = 0;
  46584. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46585. this.bindMethods();
  46586. // generic-tracked-controller-controls has the lowest precedence.
  46587. // We must diable this component if there are more specialized controls components.
  46588. this.el.addEventListener('controllerconnected', function (evt) {
  46589. if (evt.detail.name === self.name) { return; }
  46590. self.wasControllerConnected = true;
  46591. self.removeEventListeners();
  46592. self.removeControllersUpdateListener();
  46593. });
  46594. },
  46595. addEventListeners: function () {
  46596. var el = this.el;
  46597. el.addEventListener('buttonchanged', this.onButtonChanged);
  46598. el.addEventListener('buttondown', this.onButtonDown);
  46599. el.addEventListener('buttonup', this.onButtonUp);
  46600. el.addEventListener('touchstart', this.onButtonTouchStart);
  46601. el.addEventListener('touchend', this.onButtonTouchEnd);
  46602. el.addEventListener('axismove', this.onAxisMoved);
  46603. this.controllerEventsActive = true;
  46604. },
  46605. removeEventListeners: function () {
  46606. var el = this.el;
  46607. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46608. el.removeEventListener('buttondown', this.onButtonDown);
  46609. el.removeEventListener('buttonup', this.onButtonUp);
  46610. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46611. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46612. el.removeEventListener('axismove', this.onAxisMoved);
  46613. this.controllerEventsActive = false;
  46614. },
  46615. checkIfControllerPresent: function () {
  46616. var data = this.data;
  46617. var hand = data.hand ? data.hand : undefined;
  46618. checkControllerPresentAndSetup(
  46619. this, GAMEPAD_ID_PREFIX,
  46620. {hand: hand, iterateControllerProfiles: true});
  46621. },
  46622. play: function () {
  46623. if (this.wasControllerConnected) { return; }
  46624. this.checkIfControllerPresent();
  46625. this.addControllersUpdateListener();
  46626. },
  46627. pause: function () {
  46628. this.removeEventListeners();
  46629. this.removeControllersUpdateListener();
  46630. },
  46631. injectTrackedControls: function () {
  46632. var el = this.el;
  46633. var data = this.data;
  46634. // Do nothing if tracked-controls already set.
  46635. // Generic controls have the lowest precedence.
  46636. if (this.el.components['tracked-controls']) {
  46637. this.removeEventListeners();
  46638. return;
  46639. }
  46640. el.setAttribute('tracked-controls', {
  46641. hand: data.hand,
  46642. idPrefix: GAMEPAD_ID_PREFIX,
  46643. orientationOffset: data.orientationOffset,
  46644. iterateControllerProfiles: true
  46645. });
  46646. if (!this.data.defaultModel) { return; }
  46647. this.initDefaultModel();
  46648. },
  46649. addControllersUpdateListener: function () {
  46650. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46651. },
  46652. removeControllersUpdateListener: function () {
  46653. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46654. },
  46655. onControllersUpdate: function () {
  46656. this.checkIfControllerPresent();
  46657. },
  46658. onButtonChanged: function (evt) {
  46659. var button = this.mapping.buttons[evt.detail.id];
  46660. if (!button) return;
  46661. // Pass along changed event with button state, using button mapping for convenience.
  46662. this.el.emit(button + 'changed', evt.detail.state);
  46663. },
  46664. onAxisMoved: function (evt) {
  46665. emitIfAxesChanged(this, this.mapping.axes, evt);
  46666. },
  46667. initDefaultModel: function () {
  46668. var modelEl = this.modelEl = document.createElement('a-entity');
  46669. modelEl.setAttribute('geometry', {
  46670. primitive: 'sphere',
  46671. radius: 0.03
  46672. });
  46673. modelEl.setAttribute('material', {color: this.data.color});
  46674. this.el.appendChild(modelEl);
  46675. }
  46676. });
  46677. },{"../core/component":132,"../utils/bind":200,"../utils/tracked-controls":215}],80:[function(_dereq_,module,exports){
  46678. var geometries = _dereq_('../core/geometry').geometries;
  46679. var geometryNames = _dereq_('../core/geometry').geometryNames;
  46680. var registerComponent = _dereq_('../core/component').registerComponent;
  46681. var THREE = _dereq_('../lib/three');
  46682. var dummyGeometry = new THREE.BufferGeometry();
  46683. /**
  46684. * Geometry component. Combined with material component to make a mesh in 3D object.
  46685. * Extended with registered geometries.
  46686. */
  46687. module.exports.Component = registerComponent('geometry', {
  46688. schema: {
  46689. buffer: {default: true},
  46690. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  46691. skipCache: {default: false}
  46692. },
  46693. init: function () {
  46694. this.geometry = null;
  46695. },
  46696. /**
  46697. * Talk to geometry system to get or create geometry.
  46698. */
  46699. update: function (previousData) {
  46700. var data = this.data;
  46701. var el = this.el;
  46702. var mesh;
  46703. var system = this.system;
  46704. // Dispose old geometry if we created one.
  46705. if (this.geometry) {
  46706. system.unuseGeometry(previousData);
  46707. this.geometry = null;
  46708. }
  46709. // Create new geometry.
  46710. this.geometry = system.getOrCreateGeometry(data);
  46711. // Set on mesh. If mesh does not exist, create it.
  46712. mesh = el.getObject3D('mesh');
  46713. if (mesh) {
  46714. mesh.geometry = this.geometry;
  46715. } else {
  46716. mesh = new THREE.Mesh();
  46717. mesh.geometry = this.geometry;
  46718. // Default material if not defined on the entity.
  46719. if (!this.el.getAttribute('material')) {
  46720. mesh.material = new THREE.MeshStandardMaterial({
  46721. color: Math.random() * 0xFFFFFF,
  46722. metalness: 0,
  46723. roughness: 0.5
  46724. });
  46725. }
  46726. el.setObject3D('mesh', mesh);
  46727. }
  46728. },
  46729. /**
  46730. * Tell geometry system that entity is no longer using the geometry.
  46731. * Unset the geometry on the mesh
  46732. */
  46733. remove: function () {
  46734. this.system.unuseGeometry(this.data);
  46735. this.el.getObject3D('mesh').geometry = dummyGeometry;
  46736. this.geometry = null;
  46737. },
  46738. /**
  46739. * Update geometry component schema based on geometry type.
  46740. */
  46741. updateSchema: function (data) {
  46742. var currentGeometryType = this.oldData && this.oldData.primitive;
  46743. var newGeometryType = data.primitive;
  46744. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  46745. // Geometry has no schema.
  46746. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  46747. // Nothing has changed.
  46748. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  46749. this.extendSchema(schema);
  46750. }
  46751. });
  46752. },{"../core/component":132,"../core/geometry":133,"../lib/three":180}],81:[function(_dereq_,module,exports){
  46753. var registerComponent = _dereq_('../core/component').registerComponent;
  46754. var THREE = _dereq_('../lib/three');
  46755. var utils = _dereq_('../utils/');
  46756. var warn = utils.debug('components:gltf-model:warn');
  46757. /**
  46758. * glTF model loader.
  46759. */
  46760. module.exports.Component = registerComponent('gltf-model', {
  46761. schema: {type: 'model'},
  46762. init: function () {
  46763. var dracoLoader = this.system.getDRACOLoader();
  46764. this.model = null;
  46765. this.loader = new THREE.GLTFLoader();
  46766. if (dracoLoader) {
  46767. this.loader.setDRACOLoader(dracoLoader);
  46768. }
  46769. },
  46770. update: function () {
  46771. var self = this;
  46772. var el = this.el;
  46773. var src = this.data;
  46774. if (!src) { return; }
  46775. this.remove();
  46776. this.loader.load(src, function gltfLoaded (gltfModel) {
  46777. self.model = gltfModel.scene || gltfModel.scenes[0];
  46778. self.model.animations = gltfModel.animations;
  46779. el.setObject3D('mesh', self.model);
  46780. el.emit('model-loaded', {format: 'gltf', model: self.model});
  46781. }, undefined /* onProgress */, function gltfFailed (error) {
  46782. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  46783. warn(message);
  46784. el.emit('model-error', {format: 'gltf', src: src});
  46785. });
  46786. },
  46787. remove: function () {
  46788. if (!this.model) { return; }
  46789. this.el.removeObject3D('mesh');
  46790. }
  46791. });
  46792. },{"../core/component":132,"../lib/three":180,"../utils/":206}],82:[function(_dereq_,module,exports){
  46793. /* global THREE */
  46794. var registerComponent = _dereq_('../core/component').registerComponent;
  46795. // Found at https://github.com/aframevr/assets.
  46796. var MODEL_URLS = {
  46797. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  46798. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  46799. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  46800. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  46801. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  46802. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  46803. };
  46804. // Poses.
  46805. var ANIMATIONS = {
  46806. open: 'Open',
  46807. // point: grip active, trackpad surface active, trigger inactive.
  46808. point: 'Point',
  46809. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  46810. pointThumb: 'Point + Thumb',
  46811. // fist: grip active, trigger active, trackpad surface active.
  46812. fist: 'Fist',
  46813. // hold: trigger active, grip inactive.
  46814. hold: 'Hold',
  46815. // thumbUp: grip active, trigger active, trackpad surface inactive.
  46816. thumbUp: 'Thumb Up'
  46817. };
  46818. // Map animation to public events for the API.
  46819. var EVENTS = {};
  46820. EVENTS[ANIMATIONS.fist] = 'grip';
  46821. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  46822. EVENTS[ANIMATIONS.point] = 'pointing';
  46823. /**
  46824. * Hand controls component that abstracts 6DoF controls:
  46825. * oculus-touch-controls, vive-controls, windows-motion-controls.
  46826. *
  46827. * Originally meant to be a sample implementation of applications-specific controls that
  46828. * abstracts multiple types of controllers.
  46829. *
  46830. * Auto-detect appropriate controller.
  46831. * Handle common events coming from the detected vendor-specific controls.
  46832. * Translate button events to semantic hand-related event names:
  46833. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  46834. * Load hand model with gestures that are applied based on the button pressed.
  46835. *
  46836. * @property {string} Hand mapping (`left`, `right`).
  46837. */
  46838. module.exports.Component = registerComponent('hand-controls', {
  46839. schema: {
  46840. color: {default: 'white', type: 'color'},
  46841. hand: { default: 'left' },
  46842. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  46843. },
  46844. init: function () {
  46845. var self = this;
  46846. var el = this.el;
  46847. // Current pose.
  46848. this.gesture = ANIMATIONS.open;
  46849. // Active buttons populated by events provided by the attached controls.
  46850. this.pressedButtons = {};
  46851. this.touchedButtons = {};
  46852. this.loader = new THREE.GLTFLoader();
  46853. this.loader.setCrossOrigin('anonymous');
  46854. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  46855. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  46856. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  46857. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  46858. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  46859. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  46860. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  46861. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  46862. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  46863. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  46864. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  46865. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  46866. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  46867. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  46868. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  46869. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  46870. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  46871. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  46872. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  46873. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  46874. this.onControllerConnected = this.onControllerConnected.bind(this);
  46875. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  46876. el.addEventListener('controllerconnected', this.onControllerConnected);
  46877. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  46878. // Hidden by default.
  46879. el.object3D.visible = false;
  46880. },
  46881. play: function () {
  46882. this.addEventListeners();
  46883. },
  46884. pause: function () {
  46885. this.removeEventListeners();
  46886. },
  46887. tick: function (time, delta) {
  46888. var mesh = this.el.getObject3D('mesh');
  46889. if (!mesh || !mesh.mixer) { return; }
  46890. mesh.mixer.update(delta / 1000);
  46891. },
  46892. onControllerConnected: function () {
  46893. this.el.object3D.visible = true;
  46894. },
  46895. onControllerDisconnected: function () {
  46896. this.el.object3D.visible = false;
  46897. },
  46898. addEventListeners: function () {
  46899. var el = this.el;
  46900. el.addEventListener('gripdown', this.onGripDown);
  46901. el.addEventListener('gripup', this.onGripUp);
  46902. el.addEventListener('trackpaddown', this.onTrackpadDown);
  46903. el.addEventListener('trackpadup', this.onTrackpadUp);
  46904. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46905. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46906. el.addEventListener('triggerdown', this.onTriggerDown);
  46907. el.addEventListener('triggerup', this.onTriggerUp);
  46908. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  46909. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  46910. el.addEventListener('griptouchstart', this.onGripTouchStart);
  46911. el.addEventListener('griptouchend', this.onGripTouchEnd);
  46912. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  46913. el.addEventListener('thumbstickup', this.onThumbstickUp);
  46914. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  46915. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  46916. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  46917. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  46918. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  46919. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  46920. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  46921. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  46922. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  46923. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  46924. },
  46925. removeEventListeners: function () {
  46926. var el = this.el;
  46927. el.removeEventListener('gripdown', this.onGripDown);
  46928. el.removeEventListener('gripup', this.onGripUp);
  46929. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  46930. el.removeEventListener('trackpadup', this.onTrackpadUp);
  46931. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46932. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46933. el.removeEventListener('triggerdown', this.onTriggerDown);
  46934. el.removeEventListener('triggerup', this.onTriggerUp);
  46935. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  46936. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  46937. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  46938. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  46939. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  46940. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  46941. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  46942. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  46943. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  46944. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  46945. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  46946. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  46947. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  46948. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  46949. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  46950. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  46951. },
  46952. /**
  46953. * Update handler. More like the `init` handler since the only property is the hand, and
  46954. * that won't be changing much.
  46955. */
  46956. update: function (previousHand) {
  46957. var controlConfiguration;
  46958. var el = this.el;
  46959. var hand = this.data.hand;
  46960. var handModelStyle = this.data.handModelStyle;
  46961. var handColor = this.data.color;
  46962. var self = this;
  46963. // Get common configuration to abstract different vendor controls.
  46964. controlConfiguration = {
  46965. hand: hand,
  46966. model: false
  46967. };
  46968. // Set model.
  46969. if (hand !== previousHand) {
  46970. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  46971. this.loader.load(handmodelUrl, function (gltf) {
  46972. var mesh = gltf.scene.children[0];
  46973. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  46974. mesh.mixer = new THREE.AnimationMixer(mesh);
  46975. self.clips = gltf.animations;
  46976. el.setObject3D('mesh', mesh);
  46977. var handMaterial = mesh.children[1].material;
  46978. handMaterial.color = new THREE.Color(handColor);
  46979. mesh.position.set(0, 0, 0);
  46980. mesh.rotation.set(0, 0, handModelOrientation);
  46981. el.setAttribute('magicleap-controls', controlConfiguration);
  46982. el.setAttribute('vive-controls', controlConfiguration);
  46983. el.setAttribute('oculus-touch-controls', controlConfiguration);
  46984. el.setAttribute('windows-motion-controls', controlConfiguration);
  46985. el.setAttribute('hp-mixed-reality-controls', controlConfiguration);
  46986. });
  46987. }
  46988. },
  46989. remove: function () {
  46990. this.el.removeObject3D('mesh');
  46991. },
  46992. /**
  46993. * Play model animation, based on which button was pressed and which kind of event.
  46994. *
  46995. * 1. Process buttons.
  46996. * 2. Determine gesture (this.determineGesture()).
  46997. * 3. Animation gesture (this.animationGesture()).
  46998. * 4. Emit gesture events (this.emitGestureEvents()).
  46999. *
  47000. * @param {string} button - Name of the button.
  47001. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  47002. */
  47003. handleButton: function (button, evt) {
  47004. var lastGesture;
  47005. var isPressed = evt === 'down';
  47006. var isTouched = evt === 'touchstart';
  47007. // Update objects.
  47008. if (evt.indexOf('touch') === 0) {
  47009. // Update touch object.
  47010. if (isTouched === this.touchedButtons[button]) { return; }
  47011. this.touchedButtons[button] = isTouched;
  47012. } else {
  47013. // Update button object.
  47014. if (isPressed === this.pressedButtons[button]) { return; }
  47015. this.pressedButtons[button] = isPressed;
  47016. }
  47017. // Determine the gesture.
  47018. lastGesture = this.gesture;
  47019. this.gesture = this.determineGesture();
  47020. // Same gesture.
  47021. if (this.gesture === lastGesture) { return; }
  47022. // Animate gesture.
  47023. this.animateGesture(this.gesture, lastGesture);
  47024. // Emit events.
  47025. this.emitGestureEvents(this.gesture, lastGesture);
  47026. },
  47027. /**
  47028. * Determine which pose hand should be in considering active and touched buttons.
  47029. */
  47030. determineGesture: function () {
  47031. var gesture;
  47032. var isGripActive = this.pressedButtons.grip;
  47033. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  47034. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  47035. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  47036. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  47037. var isVive = isViveController(this.el.components['tracked-controls']);
  47038. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  47039. if (isVive) {
  47040. if (isGripActive || isTriggerActive) {
  47041. gesture = ANIMATIONS.fist;
  47042. } else if (isTrackpadActive) {
  47043. gesture = ANIMATIONS.point;
  47044. }
  47045. } else {
  47046. if (isGripActive) {
  47047. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  47048. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  47049. } else {
  47050. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  47051. }
  47052. } else if (isTriggerActive) {
  47053. gesture = ANIMATIONS.hold;
  47054. }
  47055. }
  47056. return gesture;
  47057. },
  47058. /**
  47059. * Play corresponding clip to a gesture
  47060. */
  47061. getClip: function (gesture) {
  47062. var clip;
  47063. var i;
  47064. for (i = 0; i < this.clips.length; i++) {
  47065. clip = this.clips[i];
  47066. if (clip.name !== gesture) { continue; }
  47067. return clip;
  47068. }
  47069. },
  47070. /**
  47071. * Play gesture animation.
  47072. *
  47073. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  47074. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  47075. */
  47076. animateGesture: function (gesture, lastGesture) {
  47077. if (gesture) {
  47078. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  47079. return;
  47080. }
  47081. // If no gesture, then reverse the current gesture back to open pose.
  47082. this.playAnimation(lastGesture, lastGesture, true);
  47083. },
  47084. /**
  47085. * Emit `hand-controls`-specific events.
  47086. */
  47087. emitGestureEvents: function (gesture, lastGesture) {
  47088. var el = this.el;
  47089. var eventName;
  47090. if (lastGesture === gesture) { return; }
  47091. // Emit event for lastGesture not inactive.
  47092. eventName = getGestureEventName(lastGesture, false);
  47093. if (eventName) { el.emit(eventName); }
  47094. // Emit event for current gesture now active.
  47095. eventName = getGestureEventName(gesture, true);
  47096. if (eventName) { el.emit(eventName); }
  47097. },
  47098. /**
  47099. * Play hand animation based on button state.
  47100. *
  47101. * @param {string} gesture - Name of the animation as specified by the model.
  47102. * @param {string} lastGesture - Previous pose.
  47103. * @param {boolean} reverse - Whether animation should play in reverse.
  47104. */
  47105. playAnimation: function (gesture, lastGesture, reverse) {
  47106. var clip;
  47107. var fromAction;
  47108. var mesh = this.el.getObject3D('mesh');
  47109. var toAction;
  47110. if (!mesh) { return; }
  47111. // Stop all current animations.
  47112. mesh.mixer.stopAllAction();
  47113. // Grab clip action.
  47114. clip = this.getClip(gesture);
  47115. toAction = mesh.mixer.clipAction(clip);
  47116. toAction.clampWhenFinished = true;
  47117. toAction.loop = THREE.LoopRepeat;
  47118. toAction.repetitions = 0;
  47119. toAction.timeScale = reverse ? -1 : 1;
  47120. toAction.time = reverse ? clip.duration : 0;
  47121. toAction.weight = 1;
  47122. // No gesture to gesture or gesture to no gesture.
  47123. if (!lastGesture || gesture === lastGesture) {
  47124. // Stop all current animations.
  47125. mesh.mixer.stopAllAction();
  47126. // Play animation.
  47127. toAction.play();
  47128. return;
  47129. }
  47130. // Animate or crossfade from gesture to gesture.
  47131. clip = this.getClip(lastGesture);
  47132. fromAction = mesh.mixer.clipAction(clip);
  47133. fromAction.weight = 0.15;
  47134. fromAction.play();
  47135. toAction.play();
  47136. fromAction.crossFadeTo(toAction, 0.15, true);
  47137. }
  47138. });
  47139. /**
  47140. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  47141. *
  47142. * @param {string} gesture
  47143. * @param {boolean} active
  47144. */
  47145. function getGestureEventName (gesture, active) {
  47146. var eventName;
  47147. if (!gesture) { return; }
  47148. eventName = EVENTS[gesture];
  47149. if (eventName === 'grip') {
  47150. return eventName + (active ? 'close' : 'open');
  47151. }
  47152. if (eventName === 'point') {
  47153. return eventName + (active ? 'up' : 'down');
  47154. }
  47155. if (eventName === 'pointing' || eventName === 'pistol') {
  47156. return eventName + (active ? 'start' : 'end');
  47157. }
  47158. }
  47159. function isViveController (trackedControls) {
  47160. var controller = trackedControls && trackedControls.controller;
  47161. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  47162. (controller.profiles &&
  47163. controller.profiles[0] &&
  47164. controller.profiles[0] === 'htc-vive'));
  47165. return isVive;
  47166. }
  47167. },{"../core/component":132}],83:[function(_dereq_,module,exports){
  47168. /* global THREE, XRRigidTransform */
  47169. var registerComponent = _dereq_('../core/component').registerComponent;
  47170. var bind = _dereq_('../utils/bind');
  47171. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47172. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47173. var LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v3/left.glb';
  47174. var RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v3/right.glb';
  47175. var BONE_PREFIX = {
  47176. left: 'b_l_',
  47177. right: 'b_r_'
  47178. };
  47179. var JOINTS = [
  47180. 'wrist',
  47181. 'thumb-metacarpal',
  47182. 'thumb-phalanx-proximal',
  47183. 'thumb-phalanx-distal',
  47184. 'thumb-tip',
  47185. 'index-finger-metacarpal',
  47186. 'index-finger-phalanx-proximal',
  47187. 'index-finger-phalanx-intermediate',
  47188. 'index-finger-phalanx-distal',
  47189. 'index-finger-tip',
  47190. 'middle-finger-metacarpal',
  47191. 'middle-finger-phalanx-proximal',
  47192. 'middle-finger-phalanx-intermediate',
  47193. 'middle-finger-phalanx-distal',
  47194. 'middle-finger-tip',
  47195. 'ring-finger-metacarpal',
  47196. 'ring-finger-phalanx-proximal',
  47197. 'ring-finger-phalanx-intermediate',
  47198. 'ring-finger-phalanx-distal',
  47199. 'ring-finger-tip',
  47200. 'pinky-finger-metacarpal',
  47201. 'pinky-finger-phalanx-proximal',
  47202. 'pinky-finger-phalanx-intermediate',
  47203. 'pinky-finger-phalanx-distal',
  47204. 'pinky-finger-tip'
  47205. ];
  47206. var BONE_MAPPING = {
  47207. 'wrist': 'wrist',
  47208. 'thumb-metacarpal': 'thumb1',
  47209. 'thumb-phalanx-proximal': 'thumb2',
  47210. 'thumb-phalanx-distal': 'thumb3',
  47211. 'thumb-tip': 'thumb_null',
  47212. 'index-finger-metacarpal': 'index0',
  47213. 'index-finger-phalanx-proximal': 'index1',
  47214. 'index-finger-phalanx-intermediate': 'index2',
  47215. 'index-finger-phalanx-distal': 'index3',
  47216. 'index-finger-tip': 'index_null',
  47217. 'middle-finger-metacarpal': 'middle0',
  47218. 'middle-finger-phalanx-proximal': 'middle1',
  47219. 'middle-finger-phalanx-intermediate': 'middle2',
  47220. 'middle-finger-phalanx-distal': 'middle3',
  47221. 'middle-finger-tip': 'middle_null',
  47222. 'ring-finger-metacarpal': 'ring0',
  47223. 'ring-finger-phalanx-proximal': 'ring1',
  47224. 'ring-finger-phalanx-intermediate': 'ring2',
  47225. 'ring-finger-phalanx-distal': 'ring3',
  47226. 'ring-finger-tip': 'ring_null',
  47227. 'pinky-finger-metacarpal': 'pinky0',
  47228. 'pinky-finger-phalanx-proximal': 'pinky1',
  47229. 'pinky-finger-phalanx-intermediate': 'pinky2',
  47230. 'pinky-finger-phalanx-distal': 'pinky3',
  47231. 'pinky-finger-tip': 'pinky_null'
  47232. };
  47233. var PINCH_START_DISTANCE = 0.015;
  47234. var PINCH_END_DISTANCE = 0.03;
  47235. var PINCH_POSITION_INTERPOLATION = 0.5;
  47236. /**
  47237. * Controls for hand tracking
  47238. */
  47239. module.exports.Component = registerComponent('hand-tracking-controls', {
  47240. schema: {
  47241. hand: {default: 'right', oneOf: ['left', 'right']},
  47242. modelStyle: {default: 'mesh', oneOf: ['dots', 'mesh']},
  47243. modelColor: {default: 'white'}
  47244. },
  47245. bindMethods: function () {
  47246. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47247. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47248. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47249. },
  47250. addEventListeners: function () {
  47251. this.el.addEventListener('model-loaded', this.onModelLoaded);
  47252. for (var i = 0; i < this.jointEls.length; ++i) {
  47253. this.jointEls[i].object3D.visible = true;
  47254. }
  47255. },
  47256. removeEventListeners: function () {
  47257. this.el.removeEventListener('model-loaded', this.onModelLoaded);
  47258. for (var i = 0; i < this.jointEls.length; ++i) {
  47259. this.jointEls[i].object3D.visible = false;
  47260. }
  47261. },
  47262. init: function () {
  47263. var sceneEl = this.el.sceneEl;
  47264. var webXROptionalAttributes = sceneEl.getAttribute('webxr').optionalFeatures;
  47265. webXROptionalAttributes.push('hand-tracking');
  47266. sceneEl.setAttribute('webxr', {optionalFeatures: webXROptionalAttributes});
  47267. this.onModelLoaded = this.onModelLoaded.bind(this);
  47268. this.jointEls = [];
  47269. this.controllerPresent = false;
  47270. this.isPinched = false;
  47271. this.pinchEventDetail = {position: new THREE.Vector3()};
  47272. this.indexTipPosition = new THREE.Vector3();
  47273. this.bindMethods();
  47274. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  47275. this.el.sceneEl.addEventListener('enter-vr', this.updateReferenceSpace);
  47276. this.el.sceneEl.addEventListener('exit-vr', this.updateReferenceSpace);
  47277. },
  47278. updateReferenceSpace: function () {
  47279. var self = this;
  47280. var xrSession = this.el.sceneEl.xrSession;
  47281. this.referenceSpace = undefined;
  47282. if (!xrSession) { return; }
  47283. var referenceSpaceType = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  47284. xrSession.requestReferenceSpace(referenceSpaceType).then(function (referenceSpace) {
  47285. self.referenceSpace = referenceSpace.getOffsetReferenceSpace(new XRRigidTransform({x: 0, y: 1.5, z: 0}));
  47286. }).catch(function (error) {
  47287. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(referenceSpaceType, 'tracked-controls-webxr uses reference space ' + referenceSpaceType);
  47288. throw error;
  47289. });
  47290. },
  47291. checkIfControllerPresent: function () {
  47292. var data = this.data;
  47293. var hand = data.hand ? data.hand : undefined;
  47294. checkControllerPresentAndSetup(
  47295. this, '',
  47296. {hand: hand, iterateControllerProfiles: true, handTracking: true});
  47297. },
  47298. play: function () {
  47299. this.checkIfControllerPresent();
  47300. this.addControllersUpdateListener();
  47301. },
  47302. tick: function () {
  47303. var sceneEl = this.el.sceneEl;
  47304. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47305. var frame = sceneEl.frame;
  47306. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47307. if (!controller || !frame || !trackedControlsWebXR) { return; }
  47308. if (controller.hand) {
  47309. this.el.object3D.position.set(0, 0, 0);
  47310. this.el.object3D.rotation.set(0, 0, 0);
  47311. if (frame.getJointPose) { this.updateHandModel(); }
  47312. this.detectGesture();
  47313. }
  47314. },
  47315. updateHandModel: function () {
  47316. if (this.data.modelStyle === 'dots') {
  47317. this.updateHandDotsModel();
  47318. }
  47319. if (this.data.modelStyle === 'mesh') {
  47320. this.updateHandMeshModel();
  47321. }
  47322. },
  47323. getBone: function (name) {
  47324. var bones = this.bones;
  47325. for (var i = 0; i < bones.length; i++) {
  47326. if (bones[i].name === name) { return bones[i]; }
  47327. }
  47328. return null;
  47329. },
  47330. updateHandMeshModel: function () {
  47331. var frame = this.el.sceneEl.frame;
  47332. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47333. var referenceSpace = this.referenceSpace;
  47334. if (!controller || !this.mesh || !referenceSpace) { return; }
  47335. this.mesh.visible = false;
  47336. for (var inputjoint of controller.hand.values()) {
  47337. var bone;
  47338. var jointPose;
  47339. var jointTransform;
  47340. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  47341. if (!BONE_MAPPING[inputjoint.jointName]) { continue; }
  47342. bone = this.getBone(BONE_PREFIX[this.data.hand] + BONE_MAPPING[inputjoint.jointName]);
  47343. if (bone != null && jointPose) {
  47344. jointTransform = jointPose.transform;
  47345. this.mesh.visible = true;
  47346. bone.position.copy(jointTransform.position).multiplyScalar(100);
  47347. bone.quaternion.set(jointTransform.orientation.x, jointTransform.orientation.y, jointTransform.orientation.z, jointTransform.orientation.w);
  47348. }
  47349. }
  47350. },
  47351. updateHandDotsModel: function () {
  47352. var frame = this.el.sceneEl.frame;
  47353. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47354. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47355. var referenceSpace = trackedControlsWebXR.system.referenceSpace;
  47356. var jointEl;
  47357. var object3D;
  47358. var jointPose;
  47359. var i = 0;
  47360. for (var inputjoint of controller.hand.values()) {
  47361. jointEl = this.jointEls[i++];
  47362. object3D = jointEl.object3D;
  47363. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  47364. jointEl.object3D.visible = !!jointPose;
  47365. if (!jointPose) { continue; }
  47366. object3D.matrix.elements = jointPose.transform.matrix;
  47367. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47368. jointEl.setAttribute('scale', {x: jointPose.radius, y: jointPose.radius, z: jointPose.radius});
  47369. }
  47370. },
  47371. detectGesture: function () {
  47372. this.detectPinch();
  47373. },
  47374. detectPinch: (function () {
  47375. var thumbTipPosition = new THREE.Vector3();
  47376. return function () {
  47377. var frame = this.el.sceneEl.frame;
  47378. var indexTipPosition = this.indexTipPosition;
  47379. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47380. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47381. var referenceSpace = this.referenceSpace || trackedControlsWebXR.system.referenceSpace;
  47382. var indexTip = controller.hand.get('index-finger-tip');
  47383. var thumbTip = controller.hand.get('thumb-tip');
  47384. if (!indexTip ||
  47385. !thumbTip) { return; }
  47386. var indexTipPose = frame.getJointPose(indexTip, referenceSpace);
  47387. var thumbTipPose = frame.getJointPose(thumbTip, referenceSpace);
  47388. if (!indexTipPose || !thumbTipPose) { return; }
  47389. thumbTipPosition.copy(thumbTipPose.transform.position);
  47390. indexTipPosition.copy(indexTipPose.transform.position);
  47391. var distance = indexTipPosition.distanceTo(thumbTipPosition);
  47392. if (distance < PINCH_START_DISTANCE && this.isPinched === false) {
  47393. this.isPinched = true;
  47394. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47395. this.pinchEventDetail.position.y += 1.5;
  47396. this.el.emit('pinchstarted', this.pinchEventDetail);
  47397. }
  47398. if (distance > PINCH_END_DISTANCE && this.isPinched === true) {
  47399. this.isPinched = false;
  47400. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47401. this.pinchEventDetail.position.y += 1.5;
  47402. this.el.emit('pinchended', this.pinchEventDetail);
  47403. }
  47404. if (this.isPinched) {
  47405. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47406. this.pinchEventDetail.position.y += 1.5;
  47407. this.el.emit('pinchmoved', this.pinchEventDetail);
  47408. }
  47409. indexTipPosition.y += 1.5;
  47410. };
  47411. })(),
  47412. pause: function () {
  47413. this.removeEventListeners();
  47414. this.removeControllersUpdateListener();
  47415. },
  47416. injectTrackedControls: function () {
  47417. var el = this.el;
  47418. var data = this.data;
  47419. el.setAttribute('tracked-controls', {
  47420. hand: data.hand,
  47421. iterateControllerProfiles: true,
  47422. handTrackingEnabled: true
  47423. });
  47424. this.initDefaultModel();
  47425. },
  47426. addControllersUpdateListener: function () {
  47427. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47428. },
  47429. removeControllersUpdateListener: function () {
  47430. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47431. },
  47432. onControllersUpdate: function () {
  47433. var controller;
  47434. this.checkIfControllerPresent();
  47435. controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47436. if (!this.el.getObject3D('mesh')) { return; }
  47437. if (!controller || !controller.hand || !controller.hand[0]) {
  47438. this.el.getObject3D('mesh').visible = false;
  47439. }
  47440. },
  47441. initDefaultModel: function () {
  47442. if (this.el.getObject3D('mesh')) { return; }
  47443. if (this.data.modelStyle === 'dots') {
  47444. this.initDotsModel();
  47445. }
  47446. if (this.data.modelStyle === 'mesh') {
  47447. this.initMeshHandModel();
  47448. }
  47449. },
  47450. initDotsModel: function () {
  47451. // Add models just once.
  47452. if (this.jointEls.length !== 0) { return; }
  47453. for (var i = 0; i < JOINTS.length; ++i) {
  47454. var jointEl = this.jointEl = document.createElement('a-entity');
  47455. jointEl.setAttribute('geometry', {
  47456. primitive: 'sphere',
  47457. radius: 1.0
  47458. });
  47459. jointEl.setAttribute('material', {color: this.data.modelColor});
  47460. jointEl.object3D.visible = false;
  47461. this.el.appendChild(jointEl);
  47462. this.jointEls.push(jointEl);
  47463. }
  47464. },
  47465. initMeshHandModel: function () {
  47466. var modelURL = this.data.hand === 'left' ? LEFT_HAND_MODEL_URL : RIGHT_HAND_MODEL_URL;
  47467. this.el.setAttribute('gltf-model', modelURL);
  47468. },
  47469. onModelLoaded: function () {
  47470. var mesh = this.mesh = this.el.getObject3D('mesh').children[0];
  47471. var skinnedMesh = this.skinnedMesh = mesh.children[30];
  47472. if (!this.skinnedMesh) { return; }
  47473. this.bones = skinnedMesh.skeleton.bones;
  47474. this.el.removeObject3D('mesh');
  47475. mesh.position.set(0, 1.5, 0);
  47476. mesh.rotation.set(0, 0, 0);
  47477. skinnedMesh.frustumCulled = false;
  47478. skinnedMesh.material = new THREE.MeshStandardMaterial({skinning: true, color: this.data.modelColor});
  47479. this.el.setObject3D('mesh', mesh);
  47480. }
  47481. });
  47482. },{"../core/component":132,"../utils/bind":200,"../utils/tracked-controls":215}],84:[function(_dereq_,module,exports){
  47483. var bind = _dereq_('../utils/bind');
  47484. var registerComponent = _dereq_('../core/component').registerComponent;
  47485. var THREE = _dereq_('../lib/three');
  47486. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47487. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47488. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47489. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47490. // See Profiles Registry:
  47491. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  47492. // TODO: Add a more robust system for deriving gamepad name.
  47493. var GAMEPAD_ID = 'hp-mixed-reality';
  47494. var HP_MIXEDL_REALITY_MODEL_GLB_BASE_URL = 'https://cdn.aframe.io/controllers/hp/mixed-reality/';
  47495. var HP_MIXED_REALITY_POSITION_OFFSET = {x: 0, y: 0, z: 0.06};
  47496. var HP_MIXED_REALITY_ROTATION_OFFSET = {_x: Math.PI / 4, _y: 0, _z: 0, _order: 'XYZ'};
  47497. /**
  47498. * Button IDs:
  47499. * 0 - trigger
  47500. * 1 - grip
  47501. * 3 - X / A
  47502. * 4 - Y / B
  47503. *
  47504. * Axis:
  47505. * 2 - joystick x axis
  47506. * 3 - joystick y axis
  47507. */
  47508. var INPUT_MAPPING_WEBXR = {
  47509. left: {
  47510. axes: {touchpad: [2, 3]},
  47511. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton']
  47512. },
  47513. right: {
  47514. axes: {touchpad: [2, 3]},
  47515. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton']
  47516. }
  47517. };
  47518. /**
  47519. * HP Mixed Reality Controls
  47520. */
  47521. module.exports.Component = registerComponent('hp-mixed-reality-controls', {
  47522. schema: {
  47523. hand: {default: 'none'},
  47524. model: {default: true},
  47525. orientationOffset: {type: 'vec3'}
  47526. },
  47527. mapping: INPUT_MAPPING_WEBXR,
  47528. init: function () {
  47529. var self = this;
  47530. this.controllerPresent = false;
  47531. this.lastControllerCheck = 0;
  47532. this.onButtonChanged = bind(this.onButtonChanged, this);
  47533. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  47534. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  47535. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  47536. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  47537. this.previousButtonValues = {};
  47538. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47539. this.bindMethods();
  47540. },
  47541. update: function () {
  47542. var data = this.data;
  47543. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47544. },
  47545. play: function () {
  47546. this.checkIfControllerPresent();
  47547. this.addControllersUpdateListener();
  47548. },
  47549. pause: function () {
  47550. this.removeEventListeners();
  47551. this.removeControllersUpdateListener();
  47552. },
  47553. bindMethods: function () {
  47554. this.onModelLoaded = bind(this.onModelLoaded, this);
  47555. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47556. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47557. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47558. this.onAxisMoved = bind(this.onAxisMoved, this);
  47559. },
  47560. addEventListeners: function () {
  47561. var el = this.el;
  47562. el.addEventListener('buttonchanged', this.onButtonChanged);
  47563. el.addEventListener('buttondown', this.onButtonDown);
  47564. el.addEventListener('buttonup', this.onButtonUp);
  47565. el.addEventListener('touchstart', this.onButtonTouchStart);
  47566. el.addEventListener('touchend', this.onButtonTouchEnd);
  47567. el.addEventListener('axismove', this.onAxisMoved);
  47568. el.addEventListener('model-loaded', this.onModelLoaded);
  47569. this.controllerEventsActive = true;
  47570. },
  47571. removeEventListeners: function () {
  47572. var el = this.el;
  47573. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47574. el.removeEventListener('buttondown', this.onButtonDown);
  47575. el.removeEventListener('buttonup', this.onButtonUp);
  47576. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47577. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47578. el.removeEventListener('axismove', this.onAxisMoved);
  47579. el.removeEventListener('model-loaded', this.onModelLoaded);
  47580. this.controllerEventsActive = false;
  47581. },
  47582. checkIfControllerPresent: function () {
  47583. var data = this.data;
  47584. checkControllerPresentAndSetup(this, GAMEPAD_ID,
  47585. {index: this.controllerIndex, hand: data.hand});
  47586. },
  47587. injectTrackedControls: function () {
  47588. var el = this.el;
  47589. var data = this.data;
  47590. el.setAttribute('tracked-controls', {
  47591. // TODO: verify expected behavior between reserved prefixes.
  47592. idPrefix: GAMEPAD_ID,
  47593. hand: data.hand,
  47594. controller: this.controllerIndex,
  47595. orientationOffset: data.orientationOffset
  47596. });
  47597. // Load model.
  47598. if (!this.data.model) { return; }
  47599. this.el.setAttribute('gltf-model', HP_MIXEDL_REALITY_MODEL_GLB_BASE_URL + this.data.hand + '.glb');
  47600. },
  47601. addControllersUpdateListener: function () {
  47602. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47603. },
  47604. removeControllersUpdateListener: function () {
  47605. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47606. },
  47607. onControllersUpdate: function () {
  47608. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47609. this.checkIfControllerPresent();
  47610. },
  47611. onButtonChanged: function (evt) {
  47612. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  47613. var analogValue;
  47614. if (!button) { return; }
  47615. if (button === 'trigger') {
  47616. analogValue = evt.detail.state.value;
  47617. console.log('analog value of trigger press: ' + analogValue);
  47618. }
  47619. // Pass along changed event with button state, using button mapping for convenience.
  47620. this.el.emit(button + 'changed', evt.detail.state);
  47621. },
  47622. onModelLoaded: function (evt) {
  47623. var controllerObject3D = evt.detail.model;
  47624. if (!this.data.model) { return; }
  47625. controllerObject3D.position.copy(HP_MIXED_REALITY_POSITION_OFFSET);
  47626. controllerObject3D.rotation.copy(HP_MIXED_REALITY_ROTATION_OFFSET);
  47627. this.el.emit('controllermodelready', {
  47628. name: 'hp-mixed-reality-controls',
  47629. model: this.data.model,
  47630. rayOrigin: new THREE.Vector3(0, 0, 0)
  47631. });
  47632. },
  47633. onAxisMoved: function (evt) {
  47634. emitIfAxesChanged(this, this.mapping.axes, evt);
  47635. }
  47636. });
  47637. },{"../core/component":132,"../lib/three":180,"../utils/bind":200,"../utils/tracked-controls":215}],85:[function(_dereq_,module,exports){
  47638. _dereq_('./animation');
  47639. _dereq_('./camera');
  47640. _dereq_('./cursor');
  47641. _dereq_('./daydream-controls');
  47642. _dereq_('./gearvr-controls');
  47643. _dereq_('./geometry');
  47644. _dereq_('./generic-tracked-controller-controls');
  47645. _dereq_('./gltf-model');
  47646. _dereq_('./hand-tracking-controls');
  47647. _dereq_('./hand-controls');
  47648. _dereq_('./hp-mixed-reality-controls');
  47649. _dereq_('./layer');
  47650. _dereq_('./laser-controls');
  47651. _dereq_('./light');
  47652. _dereq_('./line');
  47653. _dereq_('./link');
  47654. _dereq_('./look-controls');
  47655. _dereq_('./magicleap-controls');
  47656. _dereq_('./material');
  47657. _dereq_('./obj-model');
  47658. _dereq_('./oculus-go-controls');
  47659. _dereq_('./oculus-touch-controls');
  47660. _dereq_('./position');
  47661. _dereq_('./raycaster');
  47662. _dereq_('./rotation');
  47663. _dereq_('./scale');
  47664. _dereq_('./shadow');
  47665. _dereq_('./sound');
  47666. _dereq_('./text');
  47667. _dereq_('./tracked-controls');
  47668. _dereq_('./tracked-controls-webvr');
  47669. _dereq_('./tracked-controls-webxr');
  47670. _dereq_('./visible');
  47671. _dereq_('./valve-index-controls');
  47672. _dereq_('./vive-controls');
  47673. _dereq_('./vive-focus-controls');
  47674. _dereq_('./wasd-controls');
  47675. _dereq_('./windows-motion-controls');
  47676. _dereq_('./scene/background');
  47677. _dereq_('./scene/debug');
  47678. _dereq_('./scene/device-orientation-permission-ui');
  47679. _dereq_('./scene/embedded');
  47680. _dereq_('./scene/inspector');
  47681. _dereq_('./scene/fog');
  47682. _dereq_('./scene/keyboard-shortcuts');
  47683. _dereq_('./scene/pool');
  47684. _dereq_('./scene/screenshot');
  47685. _dereq_('./scene/stats');
  47686. _dereq_('./scene/vr-mode-ui');
  47687. },{"./animation":74,"./camera":75,"./cursor":76,"./daydream-controls":77,"./gearvr-controls":78,"./generic-tracked-controller-controls":79,"./geometry":80,"./gltf-model":81,"./hand-controls":82,"./hand-tracking-controls":83,"./hp-mixed-reality-controls":84,"./laser-controls":86,"./layer":87,"./light":88,"./line":89,"./link":90,"./look-controls":91,"./magicleap-controls":92,"./material":93,"./obj-model":94,"./oculus-go-controls":95,"./oculus-touch-controls":96,"./position":97,"./raycaster":98,"./rotation":99,"./scale":100,"./scene/background":101,"./scene/debug":102,"./scene/device-orientation-permission-ui":103,"./scene/embedded":104,"./scene/fog":105,"./scene/inspector":106,"./scene/keyboard-shortcuts":107,"./scene/pool":108,"./scene/screenshot":109,"./scene/stats":110,"./scene/vr-mode-ui":111,"./shadow":112,"./sound":113,"./text":114,"./tracked-controls":117,"./tracked-controls-webvr":115,"./tracked-controls-webxr":116,"./valve-index-controls":118,"./visible":119,"./vive-controls":120,"./vive-focus-controls":121,"./wasd-controls":122,"./windows-motion-controls":123}],86:[function(_dereq_,module,exports){
  47688. var registerComponent = _dereq_('../core/component').registerComponent;
  47689. var utils = _dereq_('../utils/');
  47690. registerComponent('laser-controls', {
  47691. schema: {
  47692. hand: {default: 'right'},
  47693. model: {default: true},
  47694. defaultModelColor: {type: 'color', default: 'grey'}
  47695. },
  47696. init: function () {
  47697. var config = this.config;
  47698. var data = this.data;
  47699. var el = this.el;
  47700. var self = this;
  47701. var controlsConfiguration = {hand: data.hand, model: data.model};
  47702. // Set all controller models.
  47703. el.setAttribute('daydream-controls', controlsConfiguration);
  47704. el.setAttribute('gearvr-controls', controlsConfiguration);
  47705. el.setAttribute('hp-mixed-reality-controls', controlsConfiguration);
  47706. el.setAttribute('magicleap-controls', controlsConfiguration);
  47707. el.setAttribute('oculus-go-controls', controlsConfiguration);
  47708. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  47709. el.setAttribute('valve-index-controls', controlsConfiguration);
  47710. el.setAttribute('vive-controls', controlsConfiguration);
  47711. el.setAttribute('vive-focus-controls', controlsConfiguration);
  47712. el.setAttribute('windows-motion-controls', controlsConfiguration);
  47713. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  47714. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  47715. el.addEventListener('controllerconnected', createRay);
  47716. el.addEventListener('controllerdisconnected', hideRay);
  47717. el.addEventListener('controllermodelready', function (evt) {
  47718. createRay(evt);
  47719. self.modelReady = true;
  47720. });
  47721. function createRay (evt) {
  47722. var controllerConfig = config[evt.detail.name];
  47723. if (!controllerConfig) { return; }
  47724. // Show the line unless a particular config opts to hide it, until a controllermodelready
  47725. // event comes through.
  47726. var raycasterConfig = utils.extend({
  47727. showLine: true
  47728. }, controllerConfig.raycaster || {});
  47729. // The controllermodelready event contains a rayOrigin that takes into account
  47730. // offsets specific to the loaded model.
  47731. if (evt.detail.rayOrigin) {
  47732. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  47733. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  47734. raycasterConfig.showLine = true;
  47735. }
  47736. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  47737. // config applied from a controllermodelready event.
  47738. if (evt.detail.rayOrigin || !self.modelReady) {
  47739. el.setAttribute('raycaster', raycasterConfig);
  47740. } else {
  47741. el.setAttribute('raycaster', 'showLine', true);
  47742. }
  47743. el.setAttribute('cursor', utils.extend({
  47744. fuse: false
  47745. }, controllerConfig.cursor));
  47746. }
  47747. function hideRay () {
  47748. el.setAttribute('raycaster', 'showLine', false);
  47749. }
  47750. },
  47751. config: {
  47752. 'daydream-controls': {
  47753. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47754. },
  47755. 'gearvr-controls': {
  47756. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47757. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  47758. },
  47759. 'generic-tracked-controller-controls': {
  47760. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47761. },
  47762. 'hp-mixed-reality-controls': {
  47763. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47764. raycaster: {origin: {x: 0, y: 0, z: 0}}
  47765. },
  47766. 'magicleap-controls': {
  47767. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47768. },
  47769. 'oculus-go-controls': {
  47770. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47771. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  47772. },
  47773. 'oculus-touch-controls': {
  47774. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47775. raycaster: {origin: {x: 0, y: 0, z: 0}}
  47776. },
  47777. 'valve-index-controls': {
  47778. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47779. },
  47780. 'vive-controls': {
  47781. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47782. },
  47783. 'vive-focus-controls': {
  47784. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47785. },
  47786. 'windows-motion-controls': {
  47787. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47788. raycaster: {showLine: false}
  47789. }
  47790. }
  47791. });
  47792. },{"../core/component":132,"../utils/":206}],87:[function(_dereq_,module,exports){
  47793. /* global THREE, XRRigidTransform, XRWebGLBinding */
  47794. var registerComponent = _dereq_('../core/component').registerComponent;
  47795. var utils = _dereq_('../utils/');
  47796. var warn = utils.debug('components:layer:warn');
  47797. module.exports.Component = registerComponent('layer', {
  47798. schema: {
  47799. type: {default: 'quad', oneOf: ['quad', 'monocubemap', 'stereocubemap']},
  47800. src: {type: 'map'},
  47801. rotateCubemap: {default: false},
  47802. width: {default: 0},
  47803. height: {default: 0}
  47804. },
  47805. init: function () {
  47806. var gl = this.el.sceneEl.renderer.getContext();
  47807. this.quaternion = new THREE.Quaternion();
  47808. this.position = new THREE.Vector3();
  47809. this.bindMethods();
  47810. this.needsRedraw = false;
  47811. this.frameBuffer = gl.createFramebuffer();
  47812. var requiredFeatures = this.el.sceneEl.getAttribute('webxr').requiredFeatures;
  47813. requiredFeatures.push('layers');
  47814. this.el.sceneEl.getAttribute('webxr', 'requiredFeatures', requiredFeatures);
  47815. this.el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  47816. this.el.sceneEl.addEventListener('exit-vr', this.onExitVR);
  47817. },
  47818. bindMethods: function () {
  47819. this.onRequestedReferenceSpace = this.onRequestedReferenceSpace.bind(this);
  47820. this.onEnterVR = this.onEnterVR.bind(this);
  47821. this.onExitVR = this.onExitVR.bind(this);
  47822. },
  47823. update: function (oldData) {
  47824. if (this.data.src !== oldData.src) { this.updateSrc(); }
  47825. },
  47826. updateSrc: function () {
  47827. var type = this.data.type;
  47828. this.texture = undefined;
  47829. if (type === 'quad') {
  47830. this.loadQuadImage();
  47831. return;
  47832. }
  47833. if (type === 'monocubemap' || type === 'stereocubemap') {
  47834. this.loadCubeMapImages();
  47835. return;
  47836. }
  47837. },
  47838. loadCubeMapImages: function () {
  47839. var type = this.data.type;
  47840. var glayer;
  47841. var xrGLFactory = this.xrGLFactory;
  47842. var frame = this.el.sceneEl.frame;
  47843. var src = this.data.src;
  47844. this.visibilityChanged = false;
  47845. if (!this.layer) { return; }
  47846. if (!src.complete) {
  47847. this.pendingCubeMapUpdate = true;
  47848. } else {
  47849. this.pendingCubeMapUpdate = false;
  47850. }
  47851. if (!this.loadingScreen) {
  47852. this.loadingScreen = true;
  47853. } else {
  47854. this.loadingScreen = false;
  47855. }
  47856. if (type === 'monocubemap') {
  47857. glayer = xrGLFactory.getSubImage(this.layer, frame);
  47858. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47859. } else {
  47860. glayer = xrGLFactory.getSubImage(this.layer, frame, 'left');
  47861. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47862. glayer = xrGLFactory.getSubImage(this.layer, frame, 'right');
  47863. this.loadCubeMapImage(glayer.colorTexture, src, 6);
  47864. }
  47865. },
  47866. loadQuadImage: function () {
  47867. var src = this.data.src;
  47868. var self = this;
  47869. this.el.sceneEl.systems.material.loadTexture(src, {src: src}, function textureLoaded (texture) {
  47870. self.el.sceneEl.renderer.initTexture(texture);
  47871. self.texture = texture;
  47872. if (src.tagName === 'VIDEO') { setTimeout(function () { self.textureIsVideo = true; }, 1000); }
  47873. if (self.layer) {
  47874. self.layer.height = self.data.height / 2 || self.texture.image.height / 1000;
  47875. self.layer.width = self.data.width / 2 || self.texture.image.width / 1000;
  47876. self.needsRedraw = true;
  47877. }
  47878. self.updateQuadPanel();
  47879. });
  47880. },
  47881. preGenerateCubeMapTextures: function (src, callback) {
  47882. if (this.data.type === 'monocubemap') {
  47883. this.generateCubeMapTextures(src, 0, callback);
  47884. } else {
  47885. this.generateCubeMapTextures(src, 0, callback);
  47886. this.generateCubeMapTextures(src, 6, callback);
  47887. }
  47888. },
  47889. generateCubeMapTextures: function (src, faceOffset, callback) {
  47890. var data = this.data;
  47891. var cubeFaceSize = this.cubeFaceSize;
  47892. var textureSourceCubeFaceSize = Math.min(src.width, src.height);
  47893. var cubefaceTextures = [];
  47894. var imgTmp0;
  47895. var imgTmp2;
  47896. for (var i = 0; i < 6; i++) {
  47897. var tempCanvas = document.createElement('CANVAS');
  47898. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47899. var tempCanvasContext = tempCanvas.getContext('2d');
  47900. if (data.rotateCubemap) {
  47901. if (i === 2 || i === 3) {
  47902. tempCanvasContext.save();
  47903. tempCanvasContext.translate(cubeFaceSize, cubeFaceSize);
  47904. tempCanvasContext.rotate(Math.PI);
  47905. }
  47906. }
  47907. // Note that this call to drawImage will not only copy the bytes to the
  47908. // canvas but also could resized the image if our cube face size is
  47909. // smaller than the source image due to GL max texture size.
  47910. tempCanvasContext.drawImage(
  47911. src,
  47912. (i + faceOffset) * textureSourceCubeFaceSize, // top left x coord in source
  47913. 0, // top left y coord in source
  47914. textureSourceCubeFaceSize, // x pixel count from source
  47915. textureSourceCubeFaceSize, // y pixel count from source
  47916. 0, // dest x offset in the canvas
  47917. 0, // dest y offset in the canvas
  47918. cubeFaceSize, // x pixel count in dest
  47919. cubeFaceSize // y pixel count in dest
  47920. );
  47921. tempCanvasContext.restore();
  47922. if (callback) { callback(); }
  47923. cubefaceTextures.push(tempCanvas);
  47924. }
  47925. if (data.rotateCubemap) {
  47926. imgTmp0 = cubefaceTextures[0];
  47927. imgTmp2 = cubefaceTextures[1];
  47928. cubefaceTextures[0] = imgTmp2;
  47929. cubefaceTextures[1] = imgTmp0;
  47930. imgTmp0 = cubefaceTextures[4];
  47931. imgTmp2 = cubefaceTextures[5];
  47932. cubefaceTextures[4] = imgTmp2;
  47933. cubefaceTextures[5] = imgTmp0;
  47934. }
  47935. if (callback) { callback(); }
  47936. return cubefaceTextures;
  47937. },
  47938. loadCubeMapImage: function (layerColorTexture, src, faceOffset) {
  47939. var gl = this.el.sceneEl.renderer.getContext();
  47940. var cubefaceTextures;
  47941. // dont flip the pixels as we load them into the texture buffer.
  47942. // TEXTURE_CUBE_MAP expects the Y to be flipped for the faces and it already
  47943. // is flipped in our texture image.
  47944. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  47945. gl.bindTexture(gl.TEXTURE_CUBE_MAP, layerColorTexture);
  47946. if (!src.complete || this.loadingScreen) {
  47947. cubefaceTextures = this.loadingScreenImages;
  47948. } else {
  47949. cubefaceTextures = this.generateCubeMapTextures(src, faceOffset);
  47950. }
  47951. var errorCode = 0;
  47952. cubefaceTextures.forEach(function (canvas, i) {
  47953. gl.texSubImage2D(
  47954. gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,
  47955. 0,
  47956. 0, 0,
  47957. gl.RGBA,
  47958. gl.UNSIGNED_BYTE,
  47959. canvas
  47960. );
  47961. errorCode = gl.getError();
  47962. });
  47963. if (errorCode !== 0) {
  47964. console.log('renderingError, WebGL Error Code: ' + errorCode);
  47965. }
  47966. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  47967. },
  47968. tick: function () {
  47969. if (!this.el.sceneEl.xrSession) { return; }
  47970. if (!this.layer && this.el.sceneEl.is('vr-mode')) { this.initLayer(); }
  47971. this.updateTransform();
  47972. if (this.data.src.complete && (this.pendingCubeMapUpdate || this.loadingScreen || this.visibilityChanged)) { this.loadCubeMapImages(); }
  47973. if (!this.needsRedraw && !this.layer.needsRedraw && !this.textureIsVideo) { return; }
  47974. if (this.data.type === 'quad') { this.draw(); }
  47975. this.needsRedraw = false;
  47976. },
  47977. initLayer: function () {
  47978. var self = this;
  47979. var type = this.data.type;
  47980. this.el.sceneEl.xrSession.onvisibilitychange = function (evt) {
  47981. self.visibilityChanged = evt.session.visibilityState !== 'hidden';
  47982. };
  47983. if (type === 'quad') {
  47984. this.initQuadLayer();
  47985. return;
  47986. }
  47987. if (type === 'monocubemap' || type === 'stereocubemap') {
  47988. this.initCubeMapLayer();
  47989. return;
  47990. }
  47991. },
  47992. initQuadLayer: function () {
  47993. var sceneEl = this.el.sceneEl;
  47994. var gl = sceneEl.renderer.getContext();
  47995. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  47996. if (!this.texture) { return; }
  47997. this.layer = xrGLFactory.createQuadLayer({
  47998. space: this.referenceSpace,
  47999. viewPixelHeight: 2048,
  48000. viewPixelWidth: 2048,
  48001. height: this.data.height / 2 || this.texture.image.height / 1000,
  48002. width: this.data.width / 2 || this.texture.image.width / 1000
  48003. });
  48004. sceneEl.renderer.xr.addLayer(this.layer);
  48005. },
  48006. initCubeMapLayer: function () {
  48007. var src = this.data.src;
  48008. var sceneEl = this.el.sceneEl;
  48009. var gl = sceneEl.renderer.getContext();
  48010. var glSizeLimit = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  48011. var cubeFaceSize = this.cubeFaceSize = Math.min(glSizeLimit, Math.min(src.width, src.height));
  48012. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  48013. this.layer = xrGLFactory.createCubeLayer({
  48014. space: this.referenceSpace,
  48015. viewPixelWidth: cubeFaceSize,
  48016. viewPixelHeight: cubeFaceSize,
  48017. layout: this.data.type === 'monocubemap' ? 'mono' : 'stereo',
  48018. isStatic: false
  48019. });
  48020. this.initLoadingScreenImages();
  48021. this.loadCubeMapImages();
  48022. sceneEl.renderer.xr.addLayer(this.layer);
  48023. },
  48024. initLoadingScreenImages: function () {
  48025. var cubeFaceSize = this.cubeFaceSize;
  48026. var loadingScreenImages = this.loadingScreenImages = [];
  48027. for (var i = 0; i < 6; i++) {
  48028. var tempCanvas = document.createElement('CANVAS');
  48029. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  48030. var tempCanvasContext = tempCanvas.getContext('2d');
  48031. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  48032. tempCanvasContext.fillStyle = 'black';
  48033. tempCanvasContext.fillRect(0, 0, cubeFaceSize, cubeFaceSize);
  48034. if (i !== 2 && i !== 3) {
  48035. tempCanvasContext.translate(cubeFaceSize, 0);
  48036. tempCanvasContext.scale(-1, 1);
  48037. tempCanvasContext.fillStyle = 'white';
  48038. tempCanvasContext.font = '30px Arial';
  48039. tempCanvasContext.fillText('Loading', cubeFaceSize / 2, cubeFaceSize / 2);
  48040. }
  48041. loadingScreenImages.push(tempCanvas);
  48042. }
  48043. },
  48044. destroyLayer: function () {
  48045. if (!this.layer) { return; }
  48046. this.el.sceneEl.renderer.xr.removeLayer(this.layer);
  48047. this.layer.destroy();
  48048. this.layer = undefined;
  48049. },
  48050. toggleCompositorLayer: function () {
  48051. this.enableCompositorLayer(!this.layerEnabled);
  48052. },
  48053. enableCompositorLayer: function (enable) {
  48054. this.layerEnabled = enable;
  48055. this.quadPanelEl.object3D.visible = !this.layerEnabled;
  48056. },
  48057. updateQuadPanel: function () {
  48058. var quadPanelEl = this.quadPanelEl;
  48059. if (!this.quadPanelEl) {
  48060. quadPanelEl = this.quadPanelEl = document.createElement('a-entity');
  48061. this.el.appendChild(quadPanelEl);
  48062. }
  48063. quadPanelEl.setAttribute('material', {
  48064. shader: 'flat',
  48065. src: this.data.src,
  48066. transparent: true
  48067. });
  48068. quadPanelEl.setAttribute('geometry', {
  48069. primitive: 'plane',
  48070. height: this.data.height || this.texture.image.height / 1000,
  48071. width: this.data.width || this.texture.image.height / 1000
  48072. });
  48073. },
  48074. draw: function () {
  48075. var sceneEl = this.el.sceneEl;
  48076. var gl = this.el.sceneEl.renderer.getContext();
  48077. var glayer = this.xrGLFactory.getSubImage(this.layer, sceneEl.frame);
  48078. var texture = sceneEl.renderer.properties.get(this.texture).__webglTexture;
  48079. var previousFrameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  48080. gl.viewport(glayer.viewport.x, glayer.viewport.y, glayer.viewport.width, glayer.viewport.height);
  48081. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer);
  48082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glayer.colorTexture, 0);
  48083. blitTexture(gl, texture, glayer, this.data.src);
  48084. gl.bindFramebuffer(gl.FRAMEBUFFER, previousFrameBuffer);
  48085. },
  48086. updateTransform: function () {
  48087. var el = this.el;
  48088. var position = this.position;
  48089. var quaternion = this.quaternion;
  48090. el.object3D.updateMatrixWorld();
  48091. position.setFromMatrixPosition(el.object3D.matrixWorld);
  48092. quaternion.setFromRotationMatrix(el.object3D.matrixWorld);
  48093. if (!this.layerEnabled) { position.set(0, 0, 100000000); }
  48094. this.layer.transform = new XRRigidTransform(position, quaternion);
  48095. },
  48096. onEnterVR: function () {
  48097. var sceneEl = this.el.sceneEl;
  48098. var xrSession = sceneEl.xrSession;
  48099. if (!sceneEl.hasWebXR || !XRWebGLBinding || !xrSession) {
  48100. warn('The layer component requires WebXR and the layers API enabled');
  48101. return;
  48102. }
  48103. xrSession.requestReferenceSpace('local').then(this.onRequestedReferenceSpace);
  48104. this.needsRedraw = true;
  48105. this.layerEnabled = true;
  48106. if (this.quadPanelEl) {
  48107. this.quadPanelEl.object3D.visible = false;
  48108. }
  48109. if (this.data.src.play) { this.data.src.play(); }
  48110. },
  48111. onExitVR: function () {
  48112. if (this.quadPanelEl) {
  48113. this.quadPanelEl.object3D.visible = true;
  48114. }
  48115. this.destroyLayer();
  48116. },
  48117. onRequestedReferenceSpace: function (referenceSpace) {
  48118. this.referenceSpace = referenceSpace;
  48119. }
  48120. });
  48121. function blitTexture (gl, texture, subImage, textureEl) {
  48122. var xrReadFramebuffer = gl.createFramebuffer();
  48123. let x1offset = subImage.viewport.x;
  48124. let y1offset = subImage.viewport.y;
  48125. let x2offset = subImage.viewport.x + subImage.viewport.width;
  48126. let y2offset = subImage.viewport.y + subImage.viewport.height;
  48127. // Update video texture.
  48128. if (textureEl.tagName === 'VIDEO') {
  48129. gl.bindTexture(gl.TEXTURE_2D, texture);
  48130. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, textureEl.width, textureEl.height, gl.RGB, gl.UNSIGNED_BYTE, textureEl);
  48131. }
  48132. // Bind texture to read framebuffer.
  48133. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, xrReadFramebuffer);
  48134. gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  48135. // Blit into layer buffer.
  48136. gl.readBuffer(gl.COLOR_ATTACHMENT0);
  48137. gl.blitFramebuffer(0, 0, textureEl.width, textureEl.height, x1offset, y1offset, x2offset, y2offset, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  48138. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  48139. gl.deleteFramebuffer(xrReadFramebuffer);
  48140. }
  48141. },{"../core/component":132,"../utils/":206}],88:[function(_dereq_,module,exports){
  48142. var bind = _dereq_('../utils/bind');
  48143. var diff = _dereq_('../utils').diff;
  48144. var debug = _dereq_('../utils/debug');
  48145. var registerComponent = _dereq_('../core/component').registerComponent;
  48146. var THREE = _dereq_('../lib/three');
  48147. var degToRad = THREE.Math.degToRad;
  48148. var warn = debug('components:light:warn');
  48149. /**
  48150. * Light component.
  48151. */
  48152. module.exports.Component = registerComponent('light', {
  48153. schema: {
  48154. angle: {default: 60, if: {type: ['spot']}},
  48155. color: {type: 'color'},
  48156. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  48157. decay: {default: 1, if: {type: ['point', 'spot']}},
  48158. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  48159. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  48160. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  48161. type: {
  48162. default: 'directional',
  48163. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  48164. schemaChange: true
  48165. },
  48166. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  48167. // Shadows.
  48168. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  48169. shadowBias: {default: 0, if: {castShadow: true}},
  48170. shadowCameraFar: {default: 500, if: {castShadow: true}},
  48171. shadowCameraFov: {default: 90, if: {castShadow: true}},
  48172. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  48173. shadowCameraTop: {default: 5, if: {castShadow: true}},
  48174. shadowCameraRight: {default: 5, if: {castShadow: true}},
  48175. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  48176. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  48177. shadowCameraVisible: {default: false, if: {castShadow: true}},
  48178. shadowMapHeight: {default: 512, if: {castShadow: true}},
  48179. shadowMapWidth: {default: 512, if: {castShadow: true}},
  48180. shadowRadius: {default: 1, if: {castShadow: true}}
  48181. },
  48182. /**
  48183. * Notifies scene a light has been added to remove default lighting.
  48184. */
  48185. init: function () {
  48186. var el = this.el;
  48187. this.light = null;
  48188. this.defaultTarget = null;
  48189. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48190. this.system.registerLight(el);
  48191. },
  48192. /**
  48193. * (Re)create or update light.
  48194. */
  48195. update: function (oldData) {
  48196. var data = this.data;
  48197. var diffData = diff(data, oldData);
  48198. var light = this.light;
  48199. var rendererSystem = this.rendererSystem;
  48200. var self = this;
  48201. // Existing light.
  48202. if (light && !('type' in diffData)) {
  48203. var shadowsLoaded = false;
  48204. // Light type has not changed. Update light.
  48205. Object.keys(diffData).forEach(function (key) {
  48206. var value = data[key];
  48207. switch (key) {
  48208. case 'color': {
  48209. light.color.set(value);
  48210. rendererSystem.applyColorCorrection(light.color);
  48211. break;
  48212. }
  48213. case 'groundColor': {
  48214. light.groundColor.set(value);
  48215. rendererSystem.applyColorCorrection(light.groundColor);
  48216. break;
  48217. }
  48218. case 'angle': {
  48219. light.angle = degToRad(value);
  48220. break;
  48221. }
  48222. case 'target': {
  48223. // Reset target if selector is null.
  48224. if (value === null) {
  48225. if (data.type === 'spot' || data.type === 'directional') {
  48226. light.target = self.defaultTarget;
  48227. }
  48228. } else {
  48229. // Target specified, set target to entity's `object3D` when it is loaded.
  48230. if (value.hasLoaded) {
  48231. self.onSetTarget(value, light);
  48232. } else {
  48233. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  48234. }
  48235. }
  48236. break;
  48237. }
  48238. case 'castShadow':
  48239. case 'shadowBias':
  48240. case 'shadowCameraFar':
  48241. case 'shadowCameraFov':
  48242. case 'shadowCameraNear':
  48243. case 'shadowCameraTop':
  48244. case 'shadowCameraRight':
  48245. case 'shadowCameraBottom':
  48246. case 'shadowCameraLeft':
  48247. case 'shadowCameraVisible':
  48248. case 'shadowMapHeight':
  48249. case 'shadowMapWidth':
  48250. case 'shadowRadius':
  48251. if (!shadowsLoaded) {
  48252. self.updateShadow();
  48253. shadowsLoaded = true;
  48254. }
  48255. break;
  48256. default: {
  48257. light[key] = value;
  48258. }
  48259. }
  48260. });
  48261. return;
  48262. }
  48263. // No light yet or light type has changed. Create and add light.
  48264. this.setLight(this.data);
  48265. this.updateShadow();
  48266. },
  48267. setLight: function (data) {
  48268. var el = this.el;
  48269. var newLight = this.getLight(data);
  48270. if (newLight) {
  48271. if (this.light) {
  48272. el.removeObject3D('light');
  48273. }
  48274. this.light = newLight;
  48275. this.light.el = el;
  48276. el.setObject3D('light', this.light);
  48277. // HACK solution for issue #1624
  48278. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  48279. el.getObject3D('light').translateY(-1);
  48280. }
  48281. // set and position default lighttarget as a child to enable spotlight orientation
  48282. if (data.type === 'spot') {
  48283. el.setObject3D('light-target', this.defaultTarget);
  48284. el.getObject3D('light-target').position.set(0, 0, -1);
  48285. }
  48286. }
  48287. },
  48288. /**
  48289. * Updates shadow-related properties on the current light.
  48290. */
  48291. updateShadow: function () {
  48292. var el = this.el;
  48293. var data = this.data;
  48294. var light = this.light;
  48295. light.castShadow = data.castShadow;
  48296. // Shadow camera helper.
  48297. var cameraHelper = el.getObject3D('cameraHelper');
  48298. if (data.shadowCameraVisible && !cameraHelper) {
  48299. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  48300. } else if (!data.shadowCameraVisible && cameraHelper) {
  48301. el.removeObject3D('cameraHelper');
  48302. }
  48303. if (!data.castShadow) { return light; }
  48304. // Shadow appearance.
  48305. light.shadow.bias = data.shadowBias;
  48306. light.shadow.radius = data.shadowRadius;
  48307. light.shadow.mapSize.height = data.shadowMapHeight;
  48308. light.shadow.mapSize.width = data.shadowMapWidth;
  48309. // Shadow camera.
  48310. light.shadow.camera.near = data.shadowCameraNear;
  48311. light.shadow.camera.far = data.shadowCameraFar;
  48312. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  48313. light.shadow.camera.top = data.shadowCameraTop;
  48314. light.shadow.camera.right = data.shadowCameraRight;
  48315. light.shadow.camera.bottom = data.shadowCameraBottom;
  48316. light.shadow.camera.left = data.shadowCameraLeft;
  48317. } else {
  48318. light.shadow.camera.fov = data.shadowCameraFov;
  48319. }
  48320. light.shadow.camera.updateProjectionMatrix();
  48321. if (cameraHelper) { cameraHelper.update(); }
  48322. },
  48323. /**
  48324. * Creates a new three.js light object given data object defining the light.
  48325. *
  48326. * @param {object} data
  48327. */
  48328. getLight: function (data) {
  48329. var angle = data.angle;
  48330. var color = new THREE.Color(data.color);
  48331. this.rendererSystem.applyColorCorrection(color);
  48332. color = color.getHex();
  48333. var decay = data.decay;
  48334. var distance = data.distance;
  48335. var groundColor = new THREE.Color(data.groundColor);
  48336. this.rendererSystem.applyColorCorrection(groundColor);
  48337. groundColor = groundColor.getHex();
  48338. var intensity = data.intensity;
  48339. var type = data.type;
  48340. var target = data.target;
  48341. var light = null;
  48342. switch (type.toLowerCase()) {
  48343. case 'ambient': {
  48344. return new THREE.AmbientLight(color, intensity);
  48345. }
  48346. case 'directional': {
  48347. light = new THREE.DirectionalLight(color, intensity);
  48348. this.defaultTarget = light.target;
  48349. if (target) {
  48350. if (target.hasLoaded) {
  48351. this.onSetTarget(target, light);
  48352. } else {
  48353. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48354. }
  48355. }
  48356. return light;
  48357. }
  48358. case 'hemisphere': {
  48359. return new THREE.HemisphereLight(color, groundColor, intensity);
  48360. }
  48361. case 'point': {
  48362. return new THREE.PointLight(color, intensity, distance, decay);
  48363. }
  48364. case 'spot': {
  48365. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  48366. this.defaultTarget = light.target;
  48367. if (target) {
  48368. if (target.hasLoaded) {
  48369. this.onSetTarget(target, light);
  48370. } else {
  48371. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48372. }
  48373. }
  48374. return light;
  48375. }
  48376. default: {
  48377. warn('%s is not a valid light type. ' +
  48378. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  48379. }
  48380. }
  48381. },
  48382. onSetTarget: function (targetEl, light) {
  48383. light.target = targetEl.object3D;
  48384. },
  48385. /**
  48386. * Remove light on remove (callback).
  48387. */
  48388. remove: function () {
  48389. var el = this.el;
  48390. el.removeObject3D('light');
  48391. if (el.getObject3D('cameraHelper')) {
  48392. el.removeObject3D('cameraHelper');
  48393. }
  48394. }
  48395. });
  48396. },{"../core/component":132,"../lib/three":180,"../utils":206,"../utils/bind":200,"../utils/debug":202}],89:[function(_dereq_,module,exports){
  48397. /* global THREE */
  48398. var registerComponent = _dereq_('../core/component').registerComponent;
  48399. module.exports.Component = registerComponent('line', {
  48400. schema: {
  48401. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48402. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48403. color: {type: 'color', default: '#74BEC1'},
  48404. opacity: {type: 'number', default: 1},
  48405. visible: {default: true}
  48406. },
  48407. multiple: true,
  48408. init: function () {
  48409. var data = this.data;
  48410. var geometry;
  48411. var material;
  48412. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48413. material = this.material = new THREE.LineBasicMaterial({
  48414. color: data.color,
  48415. opacity: data.opacity,
  48416. transparent: data.opacity < 1,
  48417. visible: data.visible
  48418. });
  48419. geometry = this.geometry = new THREE.BufferGeometry();
  48420. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  48421. this.rendererSystem.applyColorCorrection(material.color);
  48422. this.line = new THREE.Line(geometry, material);
  48423. this.el.setObject3D(this.attrName, this.line);
  48424. },
  48425. update: function (oldData) {
  48426. var data = this.data;
  48427. var geometry = this.geometry;
  48428. var geoNeedsUpdate = false;
  48429. var material = this.material;
  48430. var positionArray = geometry.attributes.position.array;
  48431. // Update geometry.
  48432. if (!isEqualVec3(data.start, oldData.start)) {
  48433. positionArray[0] = data.start.x;
  48434. positionArray[1] = data.start.y;
  48435. positionArray[2] = data.start.z;
  48436. geoNeedsUpdate = true;
  48437. }
  48438. if (!isEqualVec3(data.end, oldData.end)) {
  48439. positionArray[3] = data.end.x;
  48440. positionArray[4] = data.end.y;
  48441. positionArray[5] = data.end.z;
  48442. geoNeedsUpdate = true;
  48443. }
  48444. if (geoNeedsUpdate) {
  48445. geometry.attributes.position.needsUpdate = true;
  48446. geometry.computeBoundingSphere();
  48447. }
  48448. material.color.setStyle(data.color);
  48449. this.rendererSystem.applyColorCorrection(material.color);
  48450. material.opacity = data.opacity;
  48451. material.transparent = data.opacity < 1;
  48452. material.visible = data.visible;
  48453. },
  48454. remove: function () {
  48455. this.el.removeObject3D('line', this.line);
  48456. }
  48457. });
  48458. function isEqualVec3 (a, b) {
  48459. if (!a || !b) { return false; }
  48460. return (a.x === b.x && a.y === b.y && a.z === b.z);
  48461. }
  48462. },{"../core/component":132}],90:[function(_dereq_,module,exports){
  48463. var registerComponent = _dereq_('../core/component').registerComponent;
  48464. var registerShader = _dereq_('../core/shader').registerShader;
  48465. var THREE = _dereq_('../lib/three');
  48466. /**
  48467. * Link component. Connect experiences and traverse between them in VR
  48468. *
  48469. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  48470. */
  48471. module.exports.Component = registerComponent('link', {
  48472. schema: {
  48473. backgroundColor: {default: 'red', type: 'color'},
  48474. borderColor: {default: 'white', type: 'color'},
  48475. highlighted: {default: false},
  48476. highlightedColor: {default: '#24CAFF', type: 'color'},
  48477. href: {default: ''},
  48478. image: {type: 'asset'},
  48479. on: {default: 'click'},
  48480. peekMode: {default: false},
  48481. title: {default: ''},
  48482. titleColor: {default: 'white', type: 'color'},
  48483. visualAspectEnabled: {default: false}
  48484. },
  48485. init: function () {
  48486. this.navigate = this.navigate.bind(this);
  48487. this.previousQuaternion = undefined;
  48488. this.quaternionClone = new THREE.Quaternion();
  48489. // Store hidden elements during peek mode so we can show them again later.
  48490. this.hiddenEls = [];
  48491. },
  48492. update: function (oldData) {
  48493. var data = this.data;
  48494. var el = this.el;
  48495. var backgroundColor;
  48496. var strokeColor;
  48497. if (!data.visualAspectEnabled) { return; }
  48498. this.initVisualAspect();
  48499. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  48500. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  48501. el.setAttribute('material', 'backgroundColor', backgroundColor);
  48502. el.setAttribute('material', 'strokeColor', strokeColor);
  48503. if (data.on !== oldData.on) { this.updateEventListener(); }
  48504. if (oldData.peekMode !== undefined &&
  48505. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  48506. if (!data.image || oldData.image === data.image) { return; }
  48507. el.setAttribute('material', 'pano',
  48508. typeof data.image === 'string' ? data.image : data.image.src);
  48509. },
  48510. /*
  48511. * Toggle all elements and full 360 preview of the linked page.
  48512. */
  48513. updatePeekMode: function () {
  48514. var el = this.el;
  48515. var sphereEl = this.sphereEl;
  48516. if (this.data.peekMode) {
  48517. this.hideAll();
  48518. el.getObject3D('mesh').visible = false;
  48519. sphereEl.setAttribute('visible', true);
  48520. } else {
  48521. this.showAll();
  48522. el.getObject3D('mesh').visible = true;
  48523. sphereEl.setAttribute('visible', false);
  48524. }
  48525. },
  48526. play: function () {
  48527. this.updateEventListener();
  48528. },
  48529. pause: function () {
  48530. this.removeEventListener();
  48531. },
  48532. updateEventListener: function () {
  48533. var el = this.el;
  48534. if (!el.isPlaying) { return; }
  48535. this.removeEventListener();
  48536. el.addEventListener(this.data.on, this.navigate);
  48537. },
  48538. removeEventListener: function () {
  48539. var on = this.data.on;
  48540. if (!on) { return; }
  48541. this.el.removeEventListener(on, this.navigate);
  48542. },
  48543. initVisualAspect: function () {
  48544. var el = this.el;
  48545. var semiSphereEl;
  48546. var sphereEl;
  48547. var textEl;
  48548. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  48549. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  48550. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  48551. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  48552. // Set portal.
  48553. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  48554. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  48555. // Set text that displays the link title and URL.
  48556. textEl.setAttribute('text', {
  48557. color: this.data.titleColor,
  48558. align: 'center',
  48559. font: 'kelsonsans',
  48560. value: this.data.title || this.data.href,
  48561. width: 4
  48562. });
  48563. textEl.setAttribute('position', '0 1.5 0');
  48564. el.appendChild(textEl);
  48565. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48566. semiSphereEl.setAttribute('geometry', {
  48567. primitive: 'sphere',
  48568. radius: 1.0,
  48569. phiStart: 0,
  48570. segmentsWidth: 64,
  48571. segmentsHeight: 64,
  48572. phiLength: 180,
  48573. thetaStart: 0,
  48574. thetaLength: 360
  48575. });
  48576. semiSphereEl.setAttribute('material', {
  48577. shader: 'portal',
  48578. borderEnabled: 0.0,
  48579. pano: this.data.image,
  48580. side: 'back'
  48581. });
  48582. semiSphereEl.setAttribute('rotation', '0 180 0');
  48583. semiSphereEl.setAttribute('position', '0 0 0');
  48584. semiSphereEl.setAttribute('visible', false);
  48585. el.appendChild(semiSphereEl);
  48586. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48587. sphereEl.setAttribute('geometry', {
  48588. primitive: 'sphere',
  48589. radius: 10,
  48590. segmentsWidth: 64,
  48591. segmentsHeight: 64
  48592. });
  48593. sphereEl.setAttribute('material', {
  48594. shader: 'portal',
  48595. borderEnabled: 0.0,
  48596. pano: this.data.image,
  48597. side: 'back'
  48598. });
  48599. sphereEl.setAttribute('visible', false);
  48600. el.appendChild(sphereEl);
  48601. this.visualAspectInitialized = true;
  48602. },
  48603. navigate: function () {
  48604. window.location = this.data.href;
  48605. },
  48606. /**
  48607. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  48608. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  48609. * from where user enters.
  48610. * 2. Place the url/title above or inside portal depending on distance to camera.
  48611. * 3. Face portal to camera when far away from user.
  48612. */
  48613. tick: (function () {
  48614. var cameraWorldPosition = new THREE.Vector3();
  48615. var elWorldPosition = new THREE.Vector3();
  48616. var quaternion = new THREE.Quaternion();
  48617. var scale = new THREE.Vector3();
  48618. return function () {
  48619. var el = this.el;
  48620. var object3D = el.object3D;
  48621. var camera = el.sceneEl.camera;
  48622. var cameraPortalOrientation;
  48623. var distance;
  48624. var textEl = this.textEl;
  48625. if (!this.data.visualAspectEnabled) { return; }
  48626. // Update matrices
  48627. object3D.updateMatrixWorld();
  48628. camera.parent.updateMatrixWorld();
  48629. camera.updateMatrixWorld();
  48630. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  48631. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  48632. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  48633. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  48634. if (distance > 20) {
  48635. // Store original orientation to be restored when the portal stops facing the camera.
  48636. if (!this.previousQuaternion) {
  48637. this.quaternionClone.copy(quaternion);
  48638. this.previousQuaternion = this.quaternionClone;
  48639. }
  48640. // If the portal is far away from the user, face portal to camera.
  48641. object3D.lookAt(cameraWorldPosition);
  48642. } else {
  48643. // When portal is close to the user/camera.
  48644. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  48645. // If user gets very close to portal, replace with holed sphere they can peek in.
  48646. if (distance < 0.5) {
  48647. // Configure text size and sphere orientation depending side user approaches portal.
  48648. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  48649. textEl.setAttribute('text', 'width', 1.5);
  48650. if (cameraPortalOrientation <= 0.0) {
  48651. textEl.setAttribute('position', '0 0 0.75');
  48652. textEl.setAttribute('rotation', '0 180 0');
  48653. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  48654. } else {
  48655. textEl.setAttribute('position', '0 0 -0.75');
  48656. textEl.setAttribute('rotation', '0 0 0');
  48657. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  48658. }
  48659. el.getObject3D('mesh').visible = false;
  48660. this.semiSphereEl.setAttribute('visible', true);
  48661. this.peekCameraPortalOrientation = cameraPortalOrientation;
  48662. } else {
  48663. // Calculate wich side the camera is approaching the camera (back / front).
  48664. // Adjust text orientation based on camera position.
  48665. if (cameraPortalOrientation <= 0.0) {
  48666. textEl.setAttribute('rotation', '0 180 0');
  48667. } else {
  48668. textEl.setAttribute('rotation', '0 0 0');
  48669. }
  48670. textEl.setAttribute('text', 'width', 5);
  48671. textEl.setAttribute('position', '0 1.5 0');
  48672. el.getObject3D('mesh').visible = true;
  48673. this.semiSphereEl.setAttribute('visible', false);
  48674. this.peekCameraPortalOrientation = undefined;
  48675. }
  48676. if (this.previousQuaternion) {
  48677. object3D.quaternion.copy(this.previousQuaternion);
  48678. this.previousQuaternion = undefined;
  48679. }
  48680. }
  48681. };
  48682. })(),
  48683. hideAll: function () {
  48684. var el = this.el;
  48685. var hiddenEls = this.hiddenEls;
  48686. var self = this;
  48687. if (hiddenEls.length > 0) { return; }
  48688. el.sceneEl.object3D.traverse(function (object) {
  48689. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  48690. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  48691. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  48692. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  48693. object.el === self.semiSphereEl) {
  48694. return;
  48695. }
  48696. object.el.setAttribute('visible', false);
  48697. hiddenEls.push(object.el);
  48698. });
  48699. },
  48700. showAll: function () {
  48701. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  48702. this.hiddenEls = [];
  48703. },
  48704. /**
  48705. * Calculate whether the camera faces the front or back face of the portal.
  48706. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  48707. */
  48708. calculateCameraPortalOrientation: (function () {
  48709. var mat4 = new THREE.Matrix4();
  48710. var cameraPosition = new THREE.Vector3();
  48711. var portalNormal = new THREE.Vector3(0, 0, 1);
  48712. var portalPosition = new THREE.Vector3(0, 0, 0);
  48713. return function () {
  48714. var el = this.el;
  48715. var camera = el.sceneEl.camera;
  48716. // Reset tmp variables.
  48717. cameraPosition.set(0, 0, 0);
  48718. portalNormal.set(0, 0, 1);
  48719. portalPosition.set(0, 0, 0);
  48720. // Apply portal orientation to the normal.
  48721. el.object3D.matrixWorld.extractRotation(mat4);
  48722. portalNormal.applyMatrix4(mat4);
  48723. // Calculate portal world position.
  48724. el.object3D.updateMatrixWorld();
  48725. el.object3D.localToWorld(portalPosition);
  48726. // Calculate camera world position.
  48727. camera.parent.parent.updateMatrixWorld();
  48728. camera.parent.updateMatrixWorld();
  48729. camera.updateMatrixWorld();
  48730. camera.localToWorld(cameraPosition);
  48731. // Calculate vector from portal to camera.
  48732. // (portal) -------> (camera)
  48733. cameraPosition.sub(portalPosition).normalize();
  48734. portalNormal.normalize();
  48735. // Side where camera approaches portal is given by sign of dot product of portal normal
  48736. // and portal to camera vectors.
  48737. return Math.sign(portalNormal.dot(cameraPosition));
  48738. };
  48739. })(),
  48740. remove: function () {
  48741. this.removeEventListener();
  48742. }
  48743. });
  48744. /* eslint-disable */
  48745. registerShader('portal', {
  48746. schema: {
  48747. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  48748. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  48749. pano: {type: 'map', is: 'uniform'},
  48750. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  48751. },
  48752. vertexShader: [
  48753. 'vec3 portalPosition;',
  48754. 'varying vec3 vWorldPosition;',
  48755. 'varying float vDistanceToCenter;',
  48756. 'varying float vDistance;',
  48757. 'void main() {',
  48758. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  48759. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  48760. 'vDistance = length(portalPosition - cameraPosition);',
  48761. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  48762. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  48763. '}'
  48764. ].join('\n'),
  48765. fragmentShader: [
  48766. '#define RECIPROCAL_PI2 0.15915494',
  48767. 'uniform sampler2D pano;',
  48768. 'uniform vec3 strokeColor;',
  48769. 'uniform vec3 backgroundColor;',
  48770. 'uniform float borderEnabled;',
  48771. 'varying float vDistanceToCenter;',
  48772. 'varying float vDistance;',
  48773. 'varying vec3 vWorldPosition;',
  48774. 'void main() {',
  48775. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  48776. 'vec2 sampleUV;',
  48777. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  48778. 'sampleUV.y = clamp(direction.y * 0.5 + 0.5, 0.0, 1.0);',
  48779. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  48780. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  48781. 'gl_FragColor = vec4(strokeColor, 1.0);',
  48782. '} else {',
  48783. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  48784. '}',
  48785. '}'
  48786. ].join('\n')
  48787. });
  48788. /* eslint-enable */
  48789. },{"../core/component":132,"../core/shader":142,"../lib/three":180}],91:[function(_dereq_,module,exports){
  48790. /* global DeviceOrientationEvent */
  48791. var registerComponent = _dereq_('../core/component').registerComponent;
  48792. var THREE = _dereq_('../lib/three');
  48793. var utils = _dereq_('../utils/');
  48794. var bind = utils.bind;
  48795. // To avoid recalculation at every mouse movement tick
  48796. var PI_2 = Math.PI / 2;
  48797. /**
  48798. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  48799. */
  48800. module.exports.Component = registerComponent('look-controls', {
  48801. dependencies: ['position', 'rotation'],
  48802. schema: {
  48803. enabled: {default: true},
  48804. magicWindowTrackingEnabled: {default: true},
  48805. pointerLockEnabled: {default: false},
  48806. reverseMouseDrag: {default: false},
  48807. reverseTouchDrag: {default: false},
  48808. touchEnabled: {default: true},
  48809. mouseEnabled: {default: true}
  48810. },
  48811. init: function () {
  48812. this.deltaYaw = 0;
  48813. this.previousHMDPosition = new THREE.Vector3();
  48814. this.hmdQuaternion = new THREE.Quaternion();
  48815. this.magicWindowAbsoluteEuler = new THREE.Euler();
  48816. this.magicWindowDeltaEuler = new THREE.Euler();
  48817. this.position = new THREE.Vector3();
  48818. this.magicWindowObject = new THREE.Object3D();
  48819. this.rotation = {};
  48820. this.deltaRotation = {};
  48821. this.savedPose = null;
  48822. this.pointerLocked = false;
  48823. this.setupMouseControls();
  48824. this.bindMethods();
  48825. this.previousMouseEvent = {};
  48826. this.setupMagicWindowControls();
  48827. // To save / restore camera pose
  48828. this.savedPose = {
  48829. position: new THREE.Vector3(),
  48830. rotation: new THREE.Euler()
  48831. };
  48832. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  48833. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  48834. },
  48835. setupMagicWindowControls: function () {
  48836. var magicWindowControls;
  48837. var data = this.data;
  48838. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  48839. if (utils.device.isMobile()) {
  48840. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  48841. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  48842. magicWindowControls.enabled = false;
  48843. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  48844. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48845. } else {
  48846. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  48847. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48848. });
  48849. }
  48850. }
  48851. }
  48852. },
  48853. update: function (oldData) {
  48854. var data = this.data;
  48855. // Disable grab cursor classes if no longer enabled.
  48856. if (data.enabled !== oldData.enabled) {
  48857. this.updateGrabCursor(data.enabled);
  48858. }
  48859. // Reset magic window eulers if tracking is disabled.
  48860. if (oldData && !data.magicWindowTrackingEnabled && oldData.magicWindowTrackingEnabled) {
  48861. this.magicWindowAbsoluteEuler.set(0, 0, 0);
  48862. this.magicWindowDeltaEuler.set(0, 0, 0);
  48863. }
  48864. // Pass on magic window tracking setting to magicWindowControls.
  48865. if (this.magicWindowControls) {
  48866. this.magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48867. }
  48868. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  48869. this.removeEventListeners();
  48870. this.addEventListeners();
  48871. if (this.pointerLocked) { this.exitPointerLock(); }
  48872. }
  48873. },
  48874. tick: function (t) {
  48875. var data = this.data;
  48876. if (!data.enabled) { return; }
  48877. this.updateOrientation();
  48878. },
  48879. play: function () {
  48880. this.addEventListeners();
  48881. },
  48882. pause: function () {
  48883. this.removeEventListeners();
  48884. if (this.pointerLocked) { this.exitPointerLock(); }
  48885. },
  48886. remove: function () {
  48887. this.removeEventListeners();
  48888. if (this.pointerLocked) { this.exitPointerLock(); }
  48889. },
  48890. bindMethods: function () {
  48891. this.onMouseDown = bind(this.onMouseDown, this);
  48892. this.onMouseMove = bind(this.onMouseMove, this);
  48893. this.onMouseUp = bind(this.onMouseUp, this);
  48894. this.onTouchStart = bind(this.onTouchStart, this);
  48895. this.onTouchMove = bind(this.onTouchMove, this);
  48896. this.onTouchEnd = bind(this.onTouchEnd, this);
  48897. this.onEnterVR = bind(this.onEnterVR, this);
  48898. this.onExitVR = bind(this.onExitVR, this);
  48899. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  48900. this.onPointerLockError = bind(this.onPointerLockError, this);
  48901. },
  48902. /**
  48903. * Set up states and Object3Ds needed to store rotation data.
  48904. */
  48905. setupMouseControls: function () {
  48906. this.mouseDown = false;
  48907. this.pitchObject = new THREE.Object3D();
  48908. this.yawObject = new THREE.Object3D();
  48909. this.yawObject.position.y = 10;
  48910. this.yawObject.add(this.pitchObject);
  48911. },
  48912. /**
  48913. * Add mouse and touch event listeners to canvas.
  48914. */
  48915. addEventListeners: function () {
  48916. var sceneEl = this.el.sceneEl;
  48917. var canvasEl = sceneEl.canvas;
  48918. // Wait for canvas to load.
  48919. if (!canvasEl) {
  48920. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  48921. return;
  48922. }
  48923. // Mouse events.
  48924. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  48925. window.addEventListener('mousemove', this.onMouseMove, false);
  48926. window.addEventListener('mouseup', this.onMouseUp, false);
  48927. // Touch events.
  48928. canvasEl.addEventListener('touchstart', this.onTouchStart);
  48929. window.addEventListener('touchmove', this.onTouchMove);
  48930. window.addEventListener('touchend', this.onTouchEnd);
  48931. // sceneEl events.
  48932. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  48933. sceneEl.addEventListener('exit-vr', this.onExitVR);
  48934. // Pointer Lock events.
  48935. if (this.data.pointerLockEnabled) {
  48936. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  48937. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48938. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  48939. }
  48940. },
  48941. /**
  48942. * Remove mouse and touch event listeners from canvas.
  48943. */
  48944. removeEventListeners: function () {
  48945. var sceneEl = this.el.sceneEl;
  48946. var canvasEl = sceneEl && sceneEl.canvas;
  48947. if (!canvasEl) { return; }
  48948. // Mouse events.
  48949. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  48950. window.removeEventListener('mousemove', this.onMouseMove);
  48951. window.removeEventListener('mouseup', this.onMouseUp);
  48952. // Touch events.
  48953. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  48954. window.removeEventListener('touchmove', this.onTouchMove);
  48955. window.removeEventListener('touchend', this.onTouchEnd);
  48956. // sceneEl events.
  48957. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  48958. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  48959. // Pointer Lock events.
  48960. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  48961. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48962. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  48963. },
  48964. /**
  48965. * Update orientation for mobile, mouse drag, and headset.
  48966. * Mouse-drag only enabled if HMD is not active.
  48967. */
  48968. updateOrientation: (function () {
  48969. var poseMatrix = new THREE.Matrix4();
  48970. return function () {
  48971. var object3D = this.el.object3D;
  48972. var pitchObject = this.pitchObject;
  48973. var yawObject = this.yawObject;
  48974. var pose;
  48975. var sceneEl = this.el.sceneEl;
  48976. // In VR mode, THREE is in charge of updating the camera pose.
  48977. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) {
  48978. // With WebXR THREE applies headset pose to the object3D matrixWorld internally.
  48979. // Reflect values back on position, rotation, scale for getAttribute to return the expected values.
  48980. if (sceneEl.hasWebXR) {
  48981. pose = sceneEl.renderer.xr.getCameraPose();
  48982. if (pose) {
  48983. poseMatrix.elements = pose.transform.matrix;
  48984. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  48985. }
  48986. }
  48987. return;
  48988. }
  48989. this.updateMagicWindowOrientation();
  48990. // On mobile, do camera rotation with touch events and sensors.
  48991. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  48992. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  48993. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  48994. };
  48995. })(),
  48996. updateMagicWindowOrientation: function () {
  48997. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  48998. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  48999. // Calculate magic window HMD quaternion.
  49000. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  49001. this.magicWindowControls.update();
  49002. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  49003. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  49004. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  49005. }
  49006. if (this.previousMagicWindowYaw) {
  49007. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  49008. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  49009. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  49010. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  49011. }
  49012. }
  49013. },
  49014. /**
  49015. * Translate mouse drag into rotation.
  49016. *
  49017. * Dragging up and down rotates the camera around the X-axis (yaw).
  49018. * Dragging left and right rotates the camera around the Y-axis (pitch).
  49019. */
  49020. onMouseMove: function (evt) {
  49021. var direction;
  49022. var movementX;
  49023. var movementY;
  49024. var pitchObject = this.pitchObject;
  49025. var previousMouseEvent = this.previousMouseEvent;
  49026. var yawObject = this.yawObject;
  49027. // Not dragging or not enabled.
  49028. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  49029. // Calculate delta.
  49030. if (this.pointerLocked) {
  49031. movementX = evt.movementX || evt.mozMovementX || 0;
  49032. movementY = evt.movementY || evt.mozMovementY || 0;
  49033. } else {
  49034. movementX = evt.screenX - previousMouseEvent.screenX;
  49035. movementY = evt.screenY - previousMouseEvent.screenY;
  49036. }
  49037. this.previousMouseEvent.screenX = evt.screenX;
  49038. this.previousMouseEvent.screenY = evt.screenY;
  49039. // Calculate rotation.
  49040. direction = this.data.reverseMouseDrag ? 1 : -1;
  49041. yawObject.rotation.y += movementX * 0.002 * direction;
  49042. pitchObject.rotation.x += movementY * 0.002 * direction;
  49043. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  49044. },
  49045. /**
  49046. * Register mouse down to detect mouse drag.
  49047. */
  49048. onMouseDown: function (evt) {
  49049. var sceneEl = this.el.sceneEl;
  49050. if (!this.data.enabled || !this.data.mouseEnabled || (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected())) { return; }
  49051. // Handle only primary button.
  49052. if (evt.button !== 0) { return; }
  49053. var canvasEl = sceneEl && sceneEl.canvas;
  49054. this.mouseDown = true;
  49055. this.previousMouseEvent.screenX = evt.screenX;
  49056. this.previousMouseEvent.screenY = evt.screenY;
  49057. this.showGrabbingCursor();
  49058. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  49059. if (canvasEl.requestPointerLock) {
  49060. canvasEl.requestPointerLock();
  49061. } else if (canvasEl.mozRequestPointerLock) {
  49062. canvasEl.mozRequestPointerLock();
  49063. }
  49064. }
  49065. },
  49066. /**
  49067. * Shows grabbing cursor on scene
  49068. */
  49069. showGrabbingCursor: function () {
  49070. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  49071. },
  49072. /**
  49073. * Hides grabbing cursor on scene
  49074. */
  49075. hideGrabbingCursor: function () {
  49076. this.el.sceneEl.canvas.style.cursor = '';
  49077. },
  49078. /**
  49079. * Register mouse up to detect release of mouse drag.
  49080. */
  49081. onMouseUp: function () {
  49082. this.mouseDown = false;
  49083. this.hideGrabbingCursor();
  49084. },
  49085. /**
  49086. * Register touch down to detect touch drag.
  49087. */
  49088. onTouchStart: function (evt) {
  49089. if (evt.touches.length !== 1 ||
  49090. !this.data.touchEnabled ||
  49091. this.el.sceneEl.is('vr-mode')) { return; }
  49092. this.touchStart = {
  49093. x: evt.touches[0].pageX,
  49094. y: evt.touches[0].pageY
  49095. };
  49096. this.touchStarted = true;
  49097. },
  49098. /**
  49099. * Translate touch move to Y-axis rotation.
  49100. */
  49101. onTouchMove: function (evt) {
  49102. var direction;
  49103. var canvas = this.el.sceneEl.canvas;
  49104. var deltaY;
  49105. var yawObject = this.yawObject;
  49106. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  49107. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  49108. direction = this.data.reverseTouchDrag ? 1 : -1;
  49109. // Limit touch orientaion to to yaw (y axis).
  49110. yawObject.rotation.y -= deltaY * 0.5 * direction;
  49111. this.touchStart = {
  49112. x: evt.touches[0].pageX,
  49113. y: evt.touches[0].pageY
  49114. };
  49115. },
  49116. /**
  49117. * Register touch end to detect release of touch drag.
  49118. */
  49119. onTouchEnd: function () {
  49120. this.touchStarted = false;
  49121. },
  49122. /**
  49123. * Save pose.
  49124. */
  49125. onEnterVR: function () {
  49126. var sceneEl = this.el.sceneEl;
  49127. if (!sceneEl.checkHeadsetConnected()) { return; }
  49128. this.saveCameraPose();
  49129. this.el.object3D.position.set(0, 0, 0);
  49130. this.el.object3D.rotation.set(0, 0, 0);
  49131. if (sceneEl.hasWebXR) {
  49132. this.el.object3D.matrixAutoUpdate = false;
  49133. this.el.object3D.updateMatrix();
  49134. }
  49135. },
  49136. /**
  49137. * Restore the pose.
  49138. */
  49139. onExitVR: function () {
  49140. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  49141. this.restoreCameraPose();
  49142. this.previousHMDPosition.set(0, 0, 0);
  49143. this.el.object3D.matrixAutoUpdate = true;
  49144. },
  49145. /**
  49146. * Update Pointer Lock state.
  49147. */
  49148. onPointerLockChange: function () {
  49149. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  49150. },
  49151. /**
  49152. * Recover from Pointer Lock error.
  49153. */
  49154. onPointerLockError: function () {
  49155. this.pointerLocked = false;
  49156. },
  49157. // Exits pointer-locked mode.
  49158. exitPointerLock: function () {
  49159. document.exitPointerLock();
  49160. this.pointerLocked = false;
  49161. },
  49162. /**
  49163. * Toggle the feature of showing/hiding the grab cursor.
  49164. */
  49165. updateGrabCursor: function (enabled) {
  49166. var sceneEl = this.el.sceneEl;
  49167. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  49168. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  49169. if (!sceneEl.canvas) {
  49170. if (enabled) {
  49171. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  49172. } else {
  49173. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  49174. }
  49175. return;
  49176. }
  49177. if (enabled) {
  49178. enableGrabCursor();
  49179. return;
  49180. }
  49181. disableGrabCursor();
  49182. },
  49183. /**
  49184. * Save camera pose before entering VR to restore later if exiting.
  49185. */
  49186. saveCameraPose: function () {
  49187. var el = this.el;
  49188. this.savedPose.position.copy(el.object3D.position);
  49189. this.savedPose.rotation.copy(el.object3D.rotation);
  49190. this.hasSavedPose = true;
  49191. },
  49192. /**
  49193. * Reset camera pose to before entering VR.
  49194. */
  49195. restoreCameraPose: function () {
  49196. var el = this.el;
  49197. var savedPose = this.savedPose;
  49198. if (!this.hasSavedPose) { return; }
  49199. // Reset camera orientation.
  49200. el.object3D.position.copy(savedPose.position);
  49201. el.object3D.rotation.copy(savedPose.rotation);
  49202. this.hasSavedPose = false;
  49203. }
  49204. });
  49205. },{"../core/component":132,"../lib/three":180,"../utils/":206}],92:[function(_dereq_,module,exports){
  49206. var bind = _dereq_('../utils/bind');
  49207. var registerComponent = _dereq_('../core/component').registerComponent;
  49208. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49209. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49210. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49211. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49212. // See Profiles Registry:
  49213. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  49214. // TODO: Add a more robust system for deriving gamepad name.
  49215. var GAMEPAD_ID_PREFIX = 'magicleap';
  49216. var GAMEPAD_ID_SUFFIX = '-one';
  49217. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  49218. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  49219. /**
  49220. * Button IDs:
  49221. * 0 - trigger
  49222. * 1 - grip
  49223. * 2 - touchpad
  49224. * 3 - menu (never dispatched on this layer)
  49225. *
  49226. * Axis:
  49227. * 0 - touchpad x axis
  49228. * 1 - touchpad y axis
  49229. */
  49230. var INPUT_MAPPING_WEBXR = {
  49231. axes: {touchpad: [0, 1]},
  49232. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  49233. };
  49234. /**
  49235. * Magic Leap Controls
  49236. * Interface with Magic Leap control and map Gamepad events to controller
  49237. * buttons: trigger, grip, touchpad, and menu.
  49238. * Load a controller model.
  49239. */
  49240. module.exports.Component = registerComponent('magicleap-controls', {
  49241. schema: {
  49242. hand: {default: 'none'},
  49243. model: {default: true},
  49244. orientationOffset: {type: 'vec3'}
  49245. },
  49246. mapping: INPUT_MAPPING_WEBXR,
  49247. init: function () {
  49248. var self = this;
  49249. this.controllerPresent = false;
  49250. this.lastControllerCheck = 0;
  49251. this.onButtonChanged = bind(this.onButtonChanged, this);
  49252. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49253. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49254. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49255. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49256. this.previousButtonValues = {};
  49257. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49258. this.bindMethods();
  49259. },
  49260. update: function () {
  49261. var data = this.data;
  49262. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  49263. },
  49264. play: function () {
  49265. this.checkIfControllerPresent();
  49266. this.addControllersUpdateListener();
  49267. },
  49268. pause: function () {
  49269. this.removeEventListeners();
  49270. this.removeControllersUpdateListener();
  49271. },
  49272. bindMethods: function () {
  49273. this.onModelLoaded = bind(this.onModelLoaded, this);
  49274. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49275. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49276. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49277. this.onAxisMoved = bind(this.onAxisMoved, this);
  49278. },
  49279. addEventListeners: function () {
  49280. var el = this.el;
  49281. el.addEventListener('buttonchanged', this.onButtonChanged);
  49282. el.addEventListener('buttondown', this.onButtonDown);
  49283. el.addEventListener('buttonup', this.onButtonUp);
  49284. el.addEventListener('touchstart', this.onButtonTouchStart);
  49285. el.addEventListener('touchend', this.onButtonTouchEnd);
  49286. el.addEventListener('axismove', this.onAxisMoved);
  49287. el.addEventListener('model-loaded', this.onModelLoaded);
  49288. this.controllerEventsActive = true;
  49289. },
  49290. removeEventListeners: function () {
  49291. var el = this.el;
  49292. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49293. el.removeEventListener('buttondown', this.onButtonDown);
  49294. el.removeEventListener('buttonup', this.onButtonUp);
  49295. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49296. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49297. el.removeEventListener('axismove', this.onAxisMoved);
  49298. el.removeEventListener('model-loaded', this.onModelLoaded);
  49299. this.controllerEventsActive = false;
  49300. },
  49301. checkIfControllerPresent: function () {
  49302. var data = this.data;
  49303. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  49304. {index: this.controllerIndex, hand: data.hand});
  49305. },
  49306. injectTrackedControls: function () {
  49307. var el = this.el;
  49308. var data = this.data;
  49309. el.setAttribute('tracked-controls', {
  49310. // TODO: verify expected behavior between reserved prefixes.
  49311. idPrefix: GAMEPAD_ID_COMPOSITE,
  49312. hand: data.hand,
  49313. controller: this.controllerIndex,
  49314. orientationOffset: data.orientationOffset
  49315. });
  49316. // Load model.
  49317. if (!this.data.model) { return; }
  49318. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  49319. },
  49320. addControllersUpdateListener: function () {
  49321. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49322. },
  49323. removeControllersUpdateListener: function () {
  49324. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49325. },
  49326. onControllersUpdate: function () {
  49327. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  49328. this.checkIfControllerPresent();
  49329. },
  49330. /**
  49331. * Rotate the trigger button based on how hard the trigger is pressed.
  49332. */
  49333. onButtonChanged: function (evt) {
  49334. var button = this.mapping.buttons[evt.detail.id];
  49335. var analogValue;
  49336. if (!button) { return; }
  49337. if (button === 'trigger') {
  49338. analogValue = evt.detail.state.value;
  49339. console.log('analog value of trigger press: ' + analogValue);
  49340. }
  49341. // Pass along changed event with button state, using button mapping for convenience.
  49342. this.el.emit(button + 'changed', evt.detail.state);
  49343. },
  49344. onModelLoaded: function (evt) {
  49345. var controllerObject3D = evt.detail.model;
  49346. // our glb scale is too large.
  49347. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  49348. },
  49349. onAxisMoved: function (evt) {
  49350. emitIfAxesChanged(this, this.mapping.axes, evt);
  49351. },
  49352. updateModel: function (buttonName, evtName) {},
  49353. setButtonColor: function (buttonName, color) {}
  49354. });
  49355. },{"../core/component":132,"../utils/bind":200,"../utils/tracked-controls":215}],93:[function(_dereq_,module,exports){
  49356. /* global Promise */
  49357. var utils = _dereq_('../utils/');
  49358. var component = _dereq_('../core/component');
  49359. var THREE = _dereq_('../lib/three');
  49360. var shader = _dereq_('../core/shader');
  49361. var error = utils.debug('components:material:error');
  49362. var registerComponent = component.registerComponent;
  49363. var shaders = shader.shaders;
  49364. var shaderNames = shader.shaderNames;
  49365. /**
  49366. * Material component.
  49367. *
  49368. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  49369. * three.js's implementation of PBR. Another standard shading model is `flat` which
  49370. * uses MeshBasicMaterial.
  49371. */
  49372. module.exports.Component = registerComponent('material', {
  49373. schema: {
  49374. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  49375. depthTest: {default: true},
  49376. depthWrite: {default: true},
  49377. flatShading: {default: false},
  49378. npot: {default: false},
  49379. offset: {type: 'vec2', default: {x: 0, y: 0}},
  49380. opacity: {default: 1.0, min: 0.0, max: 1.0},
  49381. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  49382. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  49383. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  49384. transparent: {default: false},
  49385. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  49386. visible: {default: true},
  49387. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  49388. dithering: {default: true}
  49389. },
  49390. init: function () {
  49391. this.material = null;
  49392. },
  49393. /**
  49394. * Update or create material.
  49395. *
  49396. * @param {object|null} oldData
  49397. */
  49398. update: function (oldData) {
  49399. var data = this.data;
  49400. if (!this.shader || data.shader !== oldData.shader) {
  49401. this.updateShader(data.shader);
  49402. }
  49403. this.shader.update(this.data);
  49404. this.updateMaterial(oldData);
  49405. },
  49406. updateSchema: function (data) {
  49407. var currentShader;
  49408. var newShader;
  49409. var schema;
  49410. var shader;
  49411. newShader = data && data.shader;
  49412. currentShader = this.oldData && this.oldData.shader;
  49413. shader = newShader || currentShader;
  49414. schema = shaders[shader] && shaders[shader].schema;
  49415. if (!schema) { error('Unknown shader schema ' + shader); }
  49416. if (currentShader && newShader === currentShader) { return; }
  49417. this.extendSchema(schema);
  49418. this.updateBehavior();
  49419. },
  49420. updateBehavior: function () {
  49421. var key;
  49422. var sceneEl = this.el.sceneEl;
  49423. var schema = this.schema;
  49424. var self = this;
  49425. var tickProperties;
  49426. function tickTime (time, delta) {
  49427. var key;
  49428. for (key in tickProperties) {
  49429. tickProperties[key] = time;
  49430. }
  49431. self.shader.update(tickProperties);
  49432. }
  49433. this.tick = undefined;
  49434. tickProperties = {};
  49435. for (key in schema) {
  49436. if (schema[key].type === 'time') {
  49437. this.tick = tickTime;
  49438. tickProperties[key] = true;
  49439. }
  49440. }
  49441. if (!sceneEl) { return; }
  49442. if (this.tick) {
  49443. sceneEl.addBehavior(this);
  49444. } else {
  49445. sceneEl.removeBehavior(this);
  49446. }
  49447. },
  49448. updateShader: function (shaderName) {
  49449. var data = this.data;
  49450. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  49451. var shaderInstance;
  49452. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  49453. // Get material from A-Frame shader.
  49454. shaderInstance = this.shader = new Shader();
  49455. shaderInstance.el = this.el;
  49456. shaderInstance.init(data);
  49457. this.setMaterial(shaderInstance.material);
  49458. this.updateSchema(data);
  49459. },
  49460. /**
  49461. * Set and update base material properties.
  49462. * Set `needsUpdate` when needed.
  49463. */
  49464. updateMaterial: function (oldData) {
  49465. var data = this.data;
  49466. var material = this.material;
  49467. var oldDataHasKeys;
  49468. // Base material properties.
  49469. material.alphaTest = data.alphaTest;
  49470. material.depthTest = data.depthTest !== false;
  49471. material.depthWrite = data.depthWrite !== false;
  49472. material.opacity = data.opacity;
  49473. material.flatShading = data.flatShading;
  49474. material.side = parseSide(data.side);
  49475. material.transparent = data.transparent !== false || data.opacity < 1.0;
  49476. material.vertexColors = parseVertexColors(data.vertexColors);
  49477. material.visible = data.visible;
  49478. material.blending = parseBlending(data.blending);
  49479. material.dithering = data.dithering;
  49480. // Check if material needs update.
  49481. for (oldDataHasKeys in oldData) { break; }
  49482. if (oldDataHasKeys &&
  49483. (oldData.alphaTest !== data.alphaTest ||
  49484. oldData.side !== data.side ||
  49485. oldData.vertexColors !== data.vertexColors)) {
  49486. material.needsUpdate = true;
  49487. }
  49488. },
  49489. /**
  49490. * Remove material on remove (callback).
  49491. * Dispose of it from memory and unsubscribe from scene updates.
  49492. */
  49493. remove: function () {
  49494. var defaultMaterial = new THREE.MeshBasicMaterial();
  49495. var material = this.material;
  49496. var object3D = this.el.getObject3D('mesh');
  49497. if (object3D) { object3D.material = defaultMaterial; }
  49498. disposeMaterial(material, this.system);
  49499. },
  49500. /**
  49501. * (Re)create new material. Has side-effects of setting `this.material` and updating
  49502. * material registration in scene.
  49503. *
  49504. * @param {object} data - Material component data.
  49505. * @param {object} type - Material type to create.
  49506. * @returns {object} Material.
  49507. */
  49508. setMaterial: function (material) {
  49509. var el = this.el;
  49510. var mesh;
  49511. var system = this.system;
  49512. if (this.material) { disposeMaterial(this.material, system); }
  49513. this.material = material;
  49514. system.registerMaterial(material);
  49515. // Set on mesh. If mesh does not exist, wait for it.
  49516. mesh = el.getObject3D('mesh');
  49517. if (mesh) {
  49518. mesh.material = material;
  49519. } else {
  49520. el.addEventListener('object3dset', function waitForMesh (evt) {
  49521. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  49522. el.getObject3D('mesh').material = material;
  49523. el.removeEventListener('object3dset', waitForMesh);
  49524. });
  49525. }
  49526. }
  49527. });
  49528. /**
  49529. * Return a three.js constant determining which material face sides to render
  49530. * based on the side parameter (passed as a component property).
  49531. *
  49532. * @param {string} [side=front] - `front`, `back`, or `double`.
  49533. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  49534. */
  49535. function parseSide (side) {
  49536. switch (side) {
  49537. case 'back': {
  49538. return THREE.BackSide;
  49539. }
  49540. case 'double': {
  49541. return THREE.DoubleSide;
  49542. }
  49543. default: {
  49544. // Including case `front`.
  49545. return THREE.FrontSide;
  49546. }
  49547. }
  49548. }
  49549. /**
  49550. * Return a three.js constant determining vertex coloring.
  49551. */
  49552. function parseVertexColors (coloring) {
  49553. switch (coloring) {
  49554. case 'face': {
  49555. return THREE.FaceColors;
  49556. }
  49557. case 'vertex': {
  49558. return THREE.VertexColors;
  49559. }
  49560. default: {
  49561. return THREE.NoColors;
  49562. }
  49563. }
  49564. }
  49565. /**
  49566. * Return a three.js constant determining blending
  49567. *
  49568. * @param {string} [blending=normal]
  49569. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  49570. * @returns {number}
  49571. */
  49572. function parseBlending (blending) {
  49573. switch (blending) {
  49574. case 'none': {
  49575. return THREE.NoBlending;
  49576. }
  49577. case 'additive': {
  49578. return THREE.AdditiveBlending;
  49579. }
  49580. case 'subtractive': {
  49581. return THREE.SubtractiveBlending;
  49582. }
  49583. case 'multiply': {
  49584. return THREE.MultiplyBlending;
  49585. }
  49586. default: {
  49587. return THREE.NormalBlending;
  49588. }
  49589. }
  49590. }
  49591. /**
  49592. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  49593. */
  49594. function disposeMaterial (material, system) {
  49595. material.dispose();
  49596. system.unregisterMaterial(material);
  49597. }
  49598. },{"../core/component":132,"../core/shader":142,"../lib/three":180,"../utils/":206}],94:[function(_dereq_,module,exports){
  49599. var debug = _dereq_('../utils/debug');
  49600. var registerComponent = _dereq_('../core/component').registerComponent;
  49601. var THREE = _dereq_('../lib/three');
  49602. var warn = debug('components:obj-model:warn');
  49603. module.exports.Component = registerComponent('obj-model', {
  49604. schema: {
  49605. mtl: {type: 'model'},
  49606. obj: {type: 'model'}
  49607. },
  49608. init: function () {
  49609. var self = this;
  49610. this.model = null;
  49611. this.objLoader = new THREE.OBJLoader();
  49612. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  49613. // Allow cross-origin images to be loaded.
  49614. this.mtlLoader.crossOrigin = '';
  49615. this.el.addEventListener('componentinitialized', function (evt) {
  49616. if (!self.model) { return; }
  49617. if (evt.detail.name !== 'material') { return; }
  49618. self.applyMaterial();
  49619. });
  49620. },
  49621. update: function () {
  49622. var data = this.data;
  49623. if (!data.obj) { return; }
  49624. this.resetMesh();
  49625. this.loadObj(data.obj, data.mtl);
  49626. },
  49627. remove: function () {
  49628. if (!this.model) { return; }
  49629. this.resetMesh();
  49630. },
  49631. resetMesh: function () {
  49632. this.el.removeObject3D('mesh');
  49633. },
  49634. loadObj: function (objUrl, mtlUrl) {
  49635. var self = this;
  49636. var el = this.el;
  49637. var mtlLoader = this.mtlLoader;
  49638. var objLoader = this.objLoader;
  49639. var rendererSystem = this.el.sceneEl.systems.renderer;
  49640. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  49641. if (mtlUrl) {
  49642. // .OBJ with an .MTL.
  49643. if (el.hasAttribute('material')) {
  49644. warn('Material component properties are ignored when a .MTL is provided');
  49645. }
  49646. mtlLoader.setResourcePath(BASE_PATH);
  49647. mtlLoader.load(mtlUrl, function (materials) {
  49648. materials.preload();
  49649. objLoader.setMaterials(materials);
  49650. objLoader.load(objUrl, function (objModel) {
  49651. self.model = objModel;
  49652. self.model.traverse(function (object) {
  49653. if (object.isMesh) {
  49654. var material = object.material;
  49655. if (material.color) rendererSystem.applyColorCorrection(material.color);
  49656. if (material.map) rendererSystem.applyColorCorrection(material.map);
  49657. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  49658. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  49659. }
  49660. });
  49661. el.setObject3D('mesh', objModel);
  49662. el.emit('model-loaded', {format: 'obj', model: objModel});
  49663. });
  49664. });
  49665. return;
  49666. }
  49667. // .OBJ only.
  49668. objLoader.load(objUrl, function loadObjOnly (objModel) {
  49669. self.model = objModel;
  49670. self.applyMaterial();
  49671. el.setObject3D('mesh', objModel);
  49672. el.emit('model-loaded', {format: 'obj', model: objModel});
  49673. });
  49674. },
  49675. /**
  49676. * Apply material from material component recursively.
  49677. */
  49678. applyMaterial: function () {
  49679. var material = this.el.components.material;
  49680. if (!material) { return; }
  49681. this.model.traverse(function (child) {
  49682. if (child instanceof THREE.Mesh) {
  49683. child.material = material.material;
  49684. }
  49685. });
  49686. }
  49687. });
  49688. },{"../core/component":132,"../lib/three":180,"../utils/debug":202}],95:[function(_dereq_,module,exports){
  49689. var registerComponent = _dereq_('../core/component').registerComponent;
  49690. var bind = _dereq_('../utils/bind');
  49691. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49692. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49693. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49694. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49695. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49696. var GAMEPAD_ID_WEBXR = 'oculus-go';
  49697. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  49698. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  49699. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49700. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49701. /**
  49702. * Button indices:
  49703. * 0 - trackpad
  49704. * 1 - trigger
  49705. *
  49706. * Axis:
  49707. * 0 - trackpad x
  49708. * 1 - trackpad y
  49709. */
  49710. var INPUT_MAPPING_WEBVR = {
  49711. axes: {trackpad: [0, 1]},
  49712. buttons: ['trackpad', 'trigger']
  49713. };
  49714. /**
  49715. * Button indices:
  49716. * 0 - trigger
  49717. * 1 - none
  49718. * 2 - touchpad
  49719. *
  49720. * Axis:
  49721. * 0 - touchpad x
  49722. * 1 - touchpad y
  49723. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  49724. */
  49725. var INPUT_MAPPING_WEBXR = {
  49726. axes: {touchpad: [0, 1]},
  49727. buttons: ['trigger', 'none', 'touchpad']
  49728. };
  49729. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49730. /**
  49731. * Oculus Go controls.
  49732. * Interface with Oculus Go controller and map Gamepad events to
  49733. * controller buttons: trackpad, trigger
  49734. * Load a controller model and highlight the pressed buttons.
  49735. */
  49736. module.exports.Component = registerComponent('oculus-go-controls', {
  49737. schema: {
  49738. hand: {default: ''}, // This informs the degenerate arm model.
  49739. buttonColor: {type: 'color', default: '#FFFFFF'},
  49740. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  49741. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  49742. model: {default: true},
  49743. orientationOffset: {type: 'vec3'},
  49744. armModel: {default: true}
  49745. },
  49746. mapping: INPUT_MAPPING,
  49747. bindMethods: function () {
  49748. this.onModelLoaded = bind(this.onModelLoaded, this);
  49749. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49750. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49751. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49752. this.onAxisMoved = bind(this.onAxisMoved, this);
  49753. },
  49754. init: function () {
  49755. var self = this;
  49756. this.onButtonChanged = bind(this.onButtonChanged, this);
  49757. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49758. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49759. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49760. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49761. this.controllerPresent = false;
  49762. this.lastControllerCheck = 0;
  49763. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49764. this.bindMethods();
  49765. },
  49766. addEventListeners: function () {
  49767. var el = this.el;
  49768. el.addEventListener('buttonchanged', this.onButtonChanged);
  49769. el.addEventListener('buttondown', this.onButtonDown);
  49770. el.addEventListener('buttonup', this.onButtonUp);
  49771. el.addEventListener('touchstart', this.onButtonTouchStart);
  49772. el.addEventListener('touchend', this.onButtonTouchEnd);
  49773. el.addEventListener('model-loaded', this.onModelLoaded);
  49774. el.addEventListener('axismove', this.onAxisMoved);
  49775. this.controllerEventsActive = true;
  49776. },
  49777. removeEventListeners: function () {
  49778. var el = this.el;
  49779. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49780. el.removeEventListener('buttondown', this.onButtonDown);
  49781. el.removeEventListener('buttonup', this.onButtonUp);
  49782. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49783. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49784. el.removeEventListener('model-loaded', this.onModelLoaded);
  49785. el.removeEventListener('axismove', this.onAxisMoved);
  49786. this.controllerEventsActive = false;
  49787. },
  49788. checkIfControllerPresent: function () {
  49789. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  49790. this.data.hand ? {hand: this.data.hand} : {});
  49791. },
  49792. play: function () {
  49793. this.checkIfControllerPresent();
  49794. this.addControllersUpdateListener();
  49795. },
  49796. pause: function () {
  49797. this.removeEventListeners();
  49798. this.removeControllersUpdateListener();
  49799. },
  49800. injectTrackedControls: function () {
  49801. var el = this.el;
  49802. var data = this.data;
  49803. el.setAttribute('tracked-controls', {
  49804. armModel: data.armModel,
  49805. hand: data.hand,
  49806. idPrefix: GAMEPAD_ID_PREFIX,
  49807. orientationOffset: data.orientationOffset
  49808. });
  49809. if (!this.data.model) { return; }
  49810. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  49811. },
  49812. addControllersUpdateListener: function () {
  49813. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49814. },
  49815. removeControllersUpdateListener: function () {
  49816. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49817. },
  49818. onControllersUpdate: function () {
  49819. this.checkIfControllerPresent();
  49820. },
  49821. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  49822. onModelLoaded: function (evt) {
  49823. var controllerObject3D = evt.detail.model;
  49824. var buttonMeshes;
  49825. if (!this.data.model) { return; }
  49826. buttonMeshes = this.buttonMeshes = {};
  49827. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  49828. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49829. buttonMeshes.touchpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49830. },
  49831. onButtonChanged: function (evt) {
  49832. var button = this.mapping.buttons[evt.detail.id];
  49833. if (!button) return;
  49834. // Pass along changed event with button state, using button mapping for convenience.
  49835. this.el.emit(button + 'changed', evt.detail.state);
  49836. },
  49837. onAxisMoved: function (evt) {
  49838. emitIfAxesChanged(this, this.mapping.axes, evt);
  49839. },
  49840. updateModel: function (buttonName, evtName) {
  49841. if (!this.data.model) { return; }
  49842. this.updateButtonModel(buttonName, evtName);
  49843. },
  49844. updateButtonModel: function (buttonName, state) {
  49845. var buttonMeshes = this.buttonMeshes;
  49846. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  49847. var color;
  49848. var button;
  49849. switch (state) {
  49850. case 'down':
  49851. color = this.data.buttonHighlightColor;
  49852. break;
  49853. case 'touchstart':
  49854. color = this.data.buttonTouchedColor;
  49855. break;
  49856. default:
  49857. color = this.data.buttonColor;
  49858. }
  49859. button = buttonMeshes[buttonName];
  49860. button.material.color.set(color);
  49861. this.rendererSystem.applyColorCorrection(button.material.color);
  49862. }
  49863. });
  49864. },{"../core/component":132,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],96:[function(_dereq_,module,exports){
  49865. var bind = _dereq_('../utils/bind');
  49866. var registerComponent = _dereq_('../core/component').registerComponent;
  49867. var THREE = _dereq_('../lib/three');
  49868. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49869. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49870. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49871. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49872. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49873. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  49874. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  49875. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49876. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49877. // First generation model URL.
  49878. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  49879. var OCULUS_TOUCH_WEBVR = {
  49880. left: {
  49881. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49882. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49883. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  49884. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49885. },
  49886. right: {
  49887. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49888. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49889. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  49890. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49891. }
  49892. };
  49893. var OCULUS_TOUCH_WEBXR = {
  49894. left: {
  49895. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49896. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49897. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  49898. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49899. },
  49900. right: {
  49901. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49902. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49903. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  49904. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49905. }
  49906. };
  49907. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  49908. var CONTROLLER_DEFAULT = 'oculus-touch';
  49909. var CONTROLLER_PROPERTIES = {
  49910. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  49911. 'oculus-touch-v2': {
  49912. left: {
  49913. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  49914. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49915. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49916. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49917. },
  49918. right: {
  49919. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  49920. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49921. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49922. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49923. }
  49924. },
  49925. 'oculus-touch-v3': {
  49926. left: {
  49927. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-left.glb',
  49928. rayOrigin: {origin: {x: 0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49929. modelPivotOffset: new THREE.Vector3(0.01, -0.01, 0.05),
  49930. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49931. },
  49932. right: {
  49933. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-right.glb',
  49934. rayOrigin: {origin: {x: -0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49935. modelPivotOffset: new THREE.Vector3(-0.01, -0.01, 0.05),
  49936. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49937. }
  49938. }
  49939. };
  49940. /**
  49941. * Button indices:
  49942. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  49943. * 1 - trigger (with analog value, which goes up to 1)
  49944. * 2 - grip (with analog value, which goes up to 1)
  49945. * 3 - X (left) or A (right)
  49946. * 4 - Y (left) or B (right)
  49947. * 5 - surface (touch only)
  49948. */
  49949. var INPUT_MAPPING_WEBVR = {
  49950. left: {
  49951. axes: {thumbstick: [0, 1]},
  49952. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  49953. },
  49954. right: {
  49955. axes: {thumbstick: [0, 1]},
  49956. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  49957. }
  49958. };
  49959. /**
  49960. * Button indices:
  49961. * 0 - trigger
  49962. * 1 - grip
  49963. * 2 - none
  49964. * 3 - thumbstick
  49965. * 4 - X or A button
  49966. * 5 - Y or B button
  49967. * 6 - surface
  49968. *
  49969. * Axis:
  49970. * 0 - none
  49971. * 1 - none
  49972. * 2 - thumbstick
  49973. * 3 - thumbstick
  49974. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  49975. */
  49976. var INPUT_MAPPING_WEBXR = {
  49977. left: {
  49978. axes: {thumbstick: [2, 3]},
  49979. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  49980. },
  49981. right: {
  49982. axes: {thumbstick: [2, 3]},
  49983. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  49984. }
  49985. };
  49986. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49987. /**
  49988. * Oculus Touch controls.
  49989. * Interface with Oculus Touch controllers and map Gamepad events to
  49990. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  49991. * Load a controller model and highlight the pressed buttons.
  49992. */
  49993. module.exports.Component = registerComponent('oculus-touch-controls', {
  49994. schema: {
  49995. hand: {default: 'left'},
  49996. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  49997. buttonTouchColor: {type: 'color', default: '#8AB'},
  49998. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  49999. model: {default: true},
  50000. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2', 'oculus-touch-v3']},
  50001. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  50002. },
  50003. mapping: INPUT_MAPPING,
  50004. bindMethods: function () {
  50005. this.onModelLoaded = bind(this.onModelLoaded, this);
  50006. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  50007. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  50008. this.onAxisMoved = bind(this.onAxisMoved, this);
  50009. },
  50010. init: function () {
  50011. var self = this;
  50012. this.onButtonChanged = bind(this.onButtonChanged, this);
  50013. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  50014. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  50015. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  50016. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  50017. this.controllerPresent = false;
  50018. this.lastControllerCheck = 0;
  50019. this.previousButtonValues = {};
  50020. this.rendererSystem = this.el.sceneEl.systems.renderer;
  50021. this.bindMethods();
  50022. },
  50023. addEventListeners: function () {
  50024. var el = this.el;
  50025. el.addEventListener('buttonchanged', this.onButtonChanged);
  50026. el.addEventListener('buttondown', this.onButtonDown);
  50027. el.addEventListener('buttonup', this.onButtonUp);
  50028. el.addEventListener('touchstart', this.onButtonTouchStart);
  50029. el.addEventListener('touchend', this.onButtonTouchEnd);
  50030. el.addEventListener('axismove', this.onAxisMoved);
  50031. el.addEventListener('model-loaded', this.onModelLoaded);
  50032. this.controllerEventsActive = true;
  50033. },
  50034. removeEventListeners: function () {
  50035. var el = this.el;
  50036. el.removeEventListener('buttonchanged', this.onButtonChanged);
  50037. el.removeEventListener('buttondown', this.onButtonDown);
  50038. el.removeEventListener('buttonup', this.onButtonUp);
  50039. el.removeEventListener('touchstart', this.onButtonTouchStart);
  50040. el.removeEventListener('touchend', this.onButtonTouchEnd);
  50041. el.removeEventListener('axismove', this.onAxisMoved);
  50042. el.removeEventListener('model-loaded', this.onModelLoaded);
  50043. this.controllerEventsActive = false;
  50044. },
  50045. checkIfControllerPresent: function () {
  50046. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  50047. hand: this.data.hand
  50048. });
  50049. },
  50050. play: function () {
  50051. this.checkIfControllerPresent();
  50052. this.addControllersUpdateListener();
  50053. },
  50054. pause: function () {
  50055. this.removeEventListeners();
  50056. this.removeControllersUpdateListener();
  50057. },
  50058. loadModel: function (controller) {
  50059. var data = this.data;
  50060. var controllerId;
  50061. if (!data.model) { return; }
  50062. // Set the controller display model based on the data passed in.
  50063. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  50064. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  50065. // This only works for WebVR currently.
  50066. if (data.controllerType === 'auto') {
  50067. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  50068. // WebVR
  50069. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  50070. var displayName = trackedControlsSystem.vrDisplay.displayName;
  50071. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  50072. if (/^Oculus Quest$/.test(displayName)) {
  50073. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  50074. }
  50075. } else { // WebXR
  50076. controllerId = CONTROLLER_DEFAULT;
  50077. controllerId = controller.profiles.indexOf('oculus-touch-v2') !== -1 ? 'oculus-touch-v2' : controllerId;
  50078. controllerId = controller.profiles.indexOf('oculus-touch-v3') !== -1 ? 'oculus-touch-v3' : controllerId;
  50079. this.displayModel = CONTROLLER_PROPERTIES[controllerId];
  50080. }
  50081. }
  50082. var modelUrl = this.displayModel[data.hand].modelUrl;
  50083. this.el.setAttribute('gltf-model', modelUrl);
  50084. },
  50085. injectTrackedControls: function (controller) {
  50086. var data = this.data;
  50087. var webXRId = GAMEPAD_ID_WEBXR;
  50088. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  50089. var id = isWebXRAvailable ? webXRId : webVRId;
  50090. this.el.setAttribute('tracked-controls', {
  50091. id: id,
  50092. hand: data.hand,
  50093. orientationOffset: data.orientationOffset,
  50094. handTrackingEnabled: false
  50095. });
  50096. this.loadModel(controller);
  50097. },
  50098. addControllersUpdateListener: function () {
  50099. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  50100. },
  50101. removeControllersUpdateListener: function () {
  50102. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  50103. },
  50104. onControllersUpdate: function () {
  50105. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  50106. this.checkIfControllerPresent();
  50107. },
  50108. onButtonChanged: function (evt) {
  50109. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  50110. var buttonMeshes = this.buttonMeshes;
  50111. var analogValue;
  50112. if (!button) { return; }
  50113. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  50114. // Update trigger and/or grip meshes, if any.
  50115. if (buttonMeshes) {
  50116. if (button === 'trigger' && buttonMeshes.trigger) {
  50117. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  50118. }
  50119. if (button === 'grip' && buttonMeshes.grip) {
  50120. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  50121. }
  50122. }
  50123. // Pass along changed event with button state, using the buttom mapping for convenience.
  50124. this.el.emit(button + 'changed', evt.detail.state);
  50125. },
  50126. onModelLoaded: function (evt) {
  50127. var controllerObject3D = this.controllerObject3D = evt.detail.model;
  50128. var buttonMeshes;
  50129. if (!this.data.model) { return; }
  50130. buttonMeshes = this.buttonMeshes = {};
  50131. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  50132. this.originalXPositionGrip = buttonMeshes.grip && buttonMeshes.grip.position.x;
  50133. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  50134. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  50135. this.originalXRotationTrigger = buttonMeshes.trigger && buttonMeshes.trigger.rotation.x;
  50136. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  50137. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  50138. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  50139. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  50140. // Offset pivot point
  50141. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  50142. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  50143. this.el.emit('controllermodelready', {
  50144. name: 'oculus-touch-controls',
  50145. model: this.data.model,
  50146. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  50147. });
  50148. },
  50149. onAxisMoved: function (evt) {
  50150. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  50151. },
  50152. updateModel: function (buttonName, evtName) {
  50153. if (!this.data.model) { return; }
  50154. this.updateButtonModel(buttonName, evtName);
  50155. },
  50156. updateButtonModel: function (buttonName, state) {
  50157. var button;
  50158. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  50159. var buttonMeshes = this.buttonMeshes;
  50160. if (!this.data.model) { return; }
  50161. if (buttonMeshes && buttonMeshes[buttonName]) {
  50162. button = buttonMeshes[buttonName];
  50163. button.material.color.set(color);
  50164. this.rendererSystem.applyColorCorrection(button.material.color);
  50165. }
  50166. }
  50167. });
  50168. },{"../core/component":132,"../lib/three":180,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],97:[function(_dereq_,module,exports){
  50169. var registerComponent = _dereq_('../core/component').registerComponent;
  50170. module.exports.Component = registerComponent('position', {
  50171. schema: {type: 'vec3'},
  50172. update: function () {
  50173. var object3D = this.el.object3D;
  50174. var data = this.data;
  50175. object3D.position.set(data.x, data.y, data.z);
  50176. },
  50177. remove: function () {
  50178. // Pretty much for mixins.
  50179. this.el.object3D.position.set(0, 0, 0);
  50180. }
  50181. });
  50182. },{"../core/component":132}],98:[function(_dereq_,module,exports){
  50183. /* global MutationObserver */
  50184. var registerComponent = _dereq_('../core/component').registerComponent;
  50185. var THREE = _dereq_('../lib/three');
  50186. var utils = _dereq_('../utils/');
  50187. var warn = utils.debug('components:raycaster:warn');
  50188. // Defines selectors that should be 'safe' for the MutationObserver used to
  50189. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  50190. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  50191. // reliably detected and are therefore disallowed.
  50192. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  50193. // Configuration for the MutationObserver used to refresh the whitelist.
  50194. // Listens for addition/removal of elements and attributes within the scene.
  50195. var OBSERVER_CONFIG = {
  50196. childList: true,
  50197. attributes: true,
  50198. subtree: true
  50199. };
  50200. var EVENTS = {
  50201. INTERSECT: 'raycaster-intersected',
  50202. INTERSECTION: 'raycaster-intersection',
  50203. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  50204. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  50205. };
  50206. /**
  50207. * Raycaster component.
  50208. *
  50209. * Pass options to three.js Raycaster including which objects to test.
  50210. * Poll for intersections.
  50211. * Emit event on origin entity and on target entity on intersect.
  50212. *
  50213. * @member {array} intersectedEls - List of currently intersected entities.
  50214. * @member {array} objects - Cached list of meshes to intersect.
  50215. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  50216. * @member {object} raycaster - three.js Raycaster.
  50217. */
  50218. module.exports.Component = registerComponent('raycaster', {
  50219. schema: {
  50220. autoRefresh: {default: true},
  50221. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  50222. enabled: {default: true},
  50223. far: {default: 1000},
  50224. interval: {default: 0},
  50225. near: {default: 0},
  50226. objects: {default: ''},
  50227. origin: {type: 'vec3'},
  50228. showLine: {default: false},
  50229. lineColor: {default: 'white'},
  50230. lineOpacity: {default: 1},
  50231. useWorldCoordinates: {default: false}
  50232. },
  50233. multiple: true,
  50234. init: function () {
  50235. this.clearedIntersectedEls = [];
  50236. this.unitLineEndVec3 = new THREE.Vector3();
  50237. this.intersectedEls = [];
  50238. this.intersections = [];
  50239. this.newIntersectedEls = [];
  50240. this.newIntersections = [];
  50241. this.objects = [];
  50242. this.prevCheckTime = undefined;
  50243. this.prevIntersectedEls = [];
  50244. this.rawIntersections = [];
  50245. this.raycaster = new THREE.Raycaster();
  50246. this.updateOriginDirection();
  50247. this.setDirty = this.setDirty.bind(this);
  50248. this.updateLine = this.updateLine.bind(this);
  50249. this.observer = new MutationObserver(this.setDirty);
  50250. this.dirty = true;
  50251. this.lineEndVec3 = new THREE.Vector3();
  50252. this.otherLineEndVec3 = new THREE.Vector3();
  50253. this.lineData = {end: this.lineEndVec3};
  50254. this.getIntersection = this.getIntersection.bind(this);
  50255. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  50256. this.intersectedClearedDetail = {el: this.el};
  50257. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  50258. this.intersectionDetail = {};
  50259. },
  50260. /**
  50261. * Create or update raycaster object.
  50262. */
  50263. update: function (oldData) {
  50264. var data = this.data;
  50265. var el = this.el;
  50266. var raycaster = this.raycaster;
  50267. // Set raycaster properties.
  50268. raycaster.far = data.far;
  50269. raycaster.near = data.near;
  50270. // Draw line.
  50271. if (data.showLine &&
  50272. (data.far !== oldData.far || data.origin !== oldData.origin ||
  50273. data.direction !== oldData.direction || !oldData.showLine)) {
  50274. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  50275. // adjust line length.
  50276. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  50277. this.drawLine();
  50278. }
  50279. if (!data.showLine && oldData.showLine) {
  50280. el.removeAttribute('line');
  50281. }
  50282. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  50283. warn('[raycaster] Selector "' + data.objects +
  50284. '" may not update automatically with DOM changes.');
  50285. }
  50286. if (!data.objects) {
  50287. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  50288. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  50289. 'e.g., raycaster="objects: [data-raycastable]".');
  50290. }
  50291. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  50292. data.autoRefresh
  50293. ? this.addEventListeners()
  50294. : this.removeEventListeners();
  50295. }
  50296. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  50297. this.setDirty();
  50298. },
  50299. play: function () {
  50300. this.addEventListeners();
  50301. },
  50302. pause: function () {
  50303. this.removeEventListeners();
  50304. },
  50305. remove: function () {
  50306. if (this.data.showLine) {
  50307. this.el.removeAttribute('line');
  50308. }
  50309. this.clearAllIntersections();
  50310. },
  50311. addEventListeners: function () {
  50312. if (!this.data.autoRefresh) { return; }
  50313. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  50314. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  50315. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  50316. },
  50317. removeEventListeners: function () {
  50318. this.observer.disconnect();
  50319. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  50320. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  50321. },
  50322. /**
  50323. * Mark the object list as dirty, to be refreshed before next raycast.
  50324. */
  50325. setDirty: function () {
  50326. this.dirty = true;
  50327. },
  50328. /**
  50329. * Update list of objects to test for intersection.
  50330. */
  50331. refreshObjects: function () {
  50332. var data = this.data;
  50333. var els;
  50334. // If objects not defined, intersect with everything.
  50335. els = data.objects
  50336. ? this.el.sceneEl.querySelectorAll(data.objects)
  50337. : this.el.sceneEl.querySelectorAll('*');
  50338. this.objects = this.flattenObject3DMaps(els);
  50339. this.dirty = false;
  50340. },
  50341. /**
  50342. * Check for intersections and cleared intersections on an interval.
  50343. */
  50344. tock: function (time) {
  50345. var data = this.data;
  50346. var prevCheckTime = this.prevCheckTime;
  50347. if (!data.enabled) { return; }
  50348. // Only check for intersection if interval time has passed.
  50349. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  50350. // Update check time.
  50351. this.prevCheckTime = time;
  50352. this.checkIntersections();
  50353. },
  50354. /**
  50355. * Raycast for intersections and emit events for current and cleared intersections.
  50356. */
  50357. checkIntersections: function () {
  50358. var clearedIntersectedEls = this.clearedIntersectedEls;
  50359. var el = this.el;
  50360. var data = this.data;
  50361. var i;
  50362. var intersectedEls = this.intersectedEls;
  50363. var intersection;
  50364. var intersections = this.intersections;
  50365. var newIntersectedEls = this.newIntersectedEls;
  50366. var newIntersections = this.newIntersections;
  50367. var prevIntersectedEls = this.prevIntersectedEls;
  50368. var rawIntersections = this.rawIntersections;
  50369. // Refresh the object whitelist if needed.
  50370. if (this.dirty) { this.refreshObjects(); }
  50371. // Store old previously intersected entities.
  50372. copyArray(this.prevIntersectedEls, this.intersectedEls);
  50373. // Raycast.
  50374. this.updateOriginDirection();
  50375. rawIntersections.length = 0;
  50376. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  50377. // Only keep intersections against objects that have a reference to an entity.
  50378. intersections.length = 0;
  50379. intersectedEls.length = 0;
  50380. for (i = 0; i < rawIntersections.length; i++) {
  50381. intersection = rawIntersections[i];
  50382. // Don't intersect with own line.
  50383. if (data.showLine && intersection.object === el.getObject3D('line')) {
  50384. continue;
  50385. }
  50386. if (intersection.object.el) {
  50387. intersections.push(intersection);
  50388. intersectedEls.push(intersection.object.el);
  50389. }
  50390. }
  50391. // Get newly intersected entities.
  50392. newIntersections.length = 0;
  50393. newIntersectedEls.length = 0;
  50394. for (i = 0; i < intersections.length; i++) {
  50395. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  50396. newIntersections.push(intersections[i]);
  50397. newIntersectedEls.push(intersections[i].object.el);
  50398. }
  50399. }
  50400. // Emit intersection cleared on both entities per formerly intersected entity.
  50401. clearedIntersectedEls.length = 0;
  50402. for (i = 0; i < prevIntersectedEls.length; i++) {
  50403. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  50404. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50405. this.intersectedClearedDetail);
  50406. clearedIntersectedEls.push(prevIntersectedEls[i]);
  50407. }
  50408. if (clearedIntersectedEls.length) {
  50409. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50410. }
  50411. // Emit intersected on intersected entity per intersected entity.
  50412. for (i = 0; i < newIntersectedEls.length; i++) {
  50413. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  50414. }
  50415. // Emit all intersections at once on raycasting entity.
  50416. if (newIntersections.length) {
  50417. this.intersectionDetail.els = newIntersectedEls;
  50418. this.intersectionDetail.intersections = newIntersections;
  50419. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  50420. }
  50421. // Update line length.
  50422. if (data.showLine) { setTimeout(this.updateLine); }
  50423. },
  50424. updateLine: function () {
  50425. var el = this.el;
  50426. var intersections = this.intersections;
  50427. var lineLength;
  50428. if (intersections.length) {
  50429. if (intersections[0].object.el === el && intersections[1]) {
  50430. lineLength = intersections[1].distance;
  50431. } else {
  50432. lineLength = intersections[0].distance;
  50433. }
  50434. }
  50435. this.drawLine(lineLength);
  50436. },
  50437. /**
  50438. * Return the most recent intersection details for a given entity, if any.
  50439. * @param {AEntity} el
  50440. * @return {Object}
  50441. */
  50442. getIntersection: function (el) {
  50443. var i;
  50444. var intersection;
  50445. for (i = 0; i < this.intersections.length; i++) {
  50446. intersection = this.intersections[i];
  50447. if (intersection.object.el === el) { return intersection; }
  50448. }
  50449. return null;
  50450. },
  50451. /**
  50452. * Update origin and direction of raycaster using entity transforms and supplied origin or
  50453. * direction offsets.
  50454. */
  50455. updateOriginDirection: (function () {
  50456. var direction = new THREE.Vector3();
  50457. var originVec3 = new THREE.Vector3();
  50458. // Closure to make quaternion/vector3 objects private.
  50459. return function updateOriginDirection () {
  50460. var el = this.el;
  50461. var data = this.data;
  50462. if (data.useWorldCoordinates) {
  50463. this.raycaster.set(data.origin, data.direction);
  50464. return;
  50465. }
  50466. el.object3D.updateMatrixWorld();
  50467. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  50468. // If non-zero origin, translate the origin into world space.
  50469. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  50470. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  50471. }
  50472. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  50473. // provide. Apply the offset to the direction, then rotation from the object,
  50474. // and normalize.
  50475. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  50476. // Apply offset and direction, in world coordinates.
  50477. this.raycaster.set(originVec3, direction);
  50478. };
  50479. })(),
  50480. /**
  50481. * Create or update line to give raycaster visual representation.
  50482. * Customize the line through through line component.
  50483. * We draw the line in the raycaster component to customize the line to the
  50484. * raycaster's origin, direction, and far.
  50485. *
  50486. * Unlike the raycaster, we create the line as a child of the object. The line will
  50487. * be affected by the transforms of the objects, so we don't have to calculate transforms
  50488. * like we do with the raycaster.
  50489. *
  50490. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  50491. * point. If not provided, length will default to the max length, `raycaster.far`.
  50492. */
  50493. drawLine: function (length) {
  50494. var data = this.data;
  50495. var el = this.el;
  50496. var endVec3;
  50497. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  50498. endVec3 = this.lineData.end === this.lineEndVec3
  50499. ? this.otherLineEndVec3
  50500. : this.lineEndVec3;
  50501. // Treat Infinity as 1000m for the line.
  50502. if (length === undefined) {
  50503. length = data.far === Infinity ? 1000 : data.far;
  50504. }
  50505. // Update the length of the line if given. `unitLineEndVec3` is the direction
  50506. // given by data.direction, then we apply a scalar to give it a length.
  50507. this.lineData.start = data.origin;
  50508. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  50509. this.lineData.color = data.lineColor;
  50510. this.lineData.opacity = data.lineOpacity;
  50511. el.setAttribute('line', this.lineData);
  50512. },
  50513. /**
  50514. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  50515. * Children are flattened by one level, removing the THREE.Group wrapper,
  50516. * so that non-recursive raycasting remains useful.
  50517. *
  50518. * Only push children defined as component attachements (e.g., setObject3D),
  50519. * NOT actual children in the scene graph hierarchy.
  50520. *
  50521. * @param {Array<Element>} els
  50522. * @return {Array<THREE.Object3D>}
  50523. */
  50524. flattenObject3DMaps: function (els) {
  50525. var key;
  50526. var i;
  50527. var objects = this.objects;
  50528. // Push meshes and other attachments onto list of objects to intersect.
  50529. objects.length = 0;
  50530. for (i = 0; i < els.length; i++) {
  50531. if (els[i].isEntity && els[i].object3D) {
  50532. for (key in els[i].object3DMap) {
  50533. objects.push(els[i].getObject3D(key));
  50534. }
  50535. }
  50536. }
  50537. return objects;
  50538. },
  50539. clearAllIntersections: function () {
  50540. var i;
  50541. for (i = 0; i < this.intersectedEls.length; i++) {
  50542. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50543. this.intersectedClearedDetail);
  50544. }
  50545. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  50546. this.intersectedEls.length = 0;
  50547. this.intersections.length = 0;
  50548. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50549. }
  50550. });
  50551. /**
  50552. * Copy contents of one array to another without allocating new array.
  50553. */
  50554. function copyArray (a, b) {
  50555. var i;
  50556. a.length = b.length;
  50557. for (i = 0; i < b.length; i++) {
  50558. a[i] = b[i];
  50559. }
  50560. }
  50561. },{"../core/component":132,"../lib/three":180,"../utils/":206}],99:[function(_dereq_,module,exports){
  50562. var degToRad = _dereq_('../lib/three').Math.degToRad;
  50563. var registerComponent = _dereq_('../core/component').registerComponent;
  50564. module.exports.Component = registerComponent('rotation', {
  50565. schema: {type: 'vec3'},
  50566. /**
  50567. * Updates object3D rotation.
  50568. */
  50569. update: function () {
  50570. var data = this.data;
  50571. var object3D = this.el.object3D;
  50572. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  50573. object3D.rotation.order = 'YXZ';
  50574. },
  50575. remove: function () {
  50576. // Pretty much for mixins.
  50577. this.el.object3D.rotation.set(0, 0, 0);
  50578. }
  50579. });
  50580. },{"../core/component":132,"../lib/three":180}],100:[function(_dereq_,module,exports){
  50581. var registerComponent = _dereq_('../core/component').registerComponent;
  50582. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  50583. var zeroScale = 0.00001;
  50584. module.exports.Component = registerComponent('scale', {
  50585. schema: {
  50586. type: 'vec3',
  50587. default: {x: 1, y: 1, z: 1}
  50588. },
  50589. update: function () {
  50590. var data = this.data;
  50591. var object3D = this.el.object3D;
  50592. var x = data.x === 0 ? zeroScale : data.x;
  50593. var y = data.y === 0 ? zeroScale : data.y;
  50594. var z = data.z === 0 ? zeroScale : data.z;
  50595. object3D.scale.set(x, y, z);
  50596. },
  50597. remove: function () {
  50598. // Pretty much for mixins.
  50599. this.el.object3D.scale.set(1, 1, 1);
  50600. }
  50601. });
  50602. },{"../core/component":132}],101:[function(_dereq_,module,exports){
  50603. /* global THREE */
  50604. var register = _dereq_('../../core/component').registerComponent;
  50605. var COMPONENTS = _dereq_('../../core/component').components;
  50606. module.exports.Component = register('background', {
  50607. schema: {
  50608. color: {type: 'color', default: 'black'},
  50609. transparent: {default: false},
  50610. generateEnvironment: {default: true}
  50611. },
  50612. init: function () {
  50613. this.cubeRenderTarget = new THREE.WebGLCubeRenderTarget(128, { format: THREE.RGBFormat, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
  50614. this.cubeCamera = new THREE.CubeCamera(1, 100000, this.cubeRenderTarget);
  50615. this.needsEnvironmentUpdate = true;
  50616. },
  50617. update: function () {
  50618. var scene = this.el.sceneEl.object3D;
  50619. var data = this.data;
  50620. var object3D = this.el.object3D;
  50621. if (data.transparent) {
  50622. object3D.background = null;
  50623. } else {
  50624. object3D.background = new THREE.Color(data.color);
  50625. }
  50626. if (scene.environment && scene.environment !== this.cubeRenderTarget.texture) {
  50627. console.warn('Background will not overide predefined environment maps');
  50628. return;
  50629. }
  50630. if (data.generateEnvironment) {
  50631. scene.environment = this.cubeRenderTarget.texture;
  50632. } else {
  50633. scene.environment = null;
  50634. }
  50635. },
  50636. tick: function () {
  50637. if (!this.needsEnvironmentUpdate) return;
  50638. var scene = this.el.object3D;
  50639. var renderer = this.el.renderer;
  50640. var camera = this.el.camera;
  50641. this.el.object3D.add(this.cubeCamera);
  50642. this.cubeCamera.position.copy(camera.position);
  50643. this.cubeCamera.update(renderer, scene);
  50644. this.needsEnvironmentUpdate = false;
  50645. },
  50646. remove: function () {
  50647. var data = this.data;
  50648. var object3D = this.el.object3D;
  50649. if (data.transparent) {
  50650. object3D.background = null;
  50651. return;
  50652. }
  50653. if (object3D.environment === this.cubeRenderTarget.texture) {
  50654. object3D.environment = null;
  50655. }
  50656. object3D.background = COMPONENTS[this.name].schema.color.default;
  50657. }
  50658. });
  50659. },{"../../core/component":132}],102:[function(_dereq_,module,exports){
  50660. var register = _dereq_('../../core/component').registerComponent;
  50661. module.exports.Component = register('debug', {
  50662. schema: {default: true}
  50663. });
  50664. },{"../../core/component":132}],103:[function(_dereq_,module,exports){
  50665. /* global DeviceOrientationEvent, location */
  50666. var registerComponent = _dereq_('../../core/component').registerComponent;
  50667. var utils = _dereq_('../../utils/');
  50668. var bind = utils.bind;
  50669. var constants = _dereq_('../../constants/');
  50670. var MODAL_CLASS = 'a-modal';
  50671. var DIALOG_CLASS = 'a-dialog';
  50672. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  50673. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  50674. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  50675. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  50676. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  50677. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  50678. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  50679. /**
  50680. * UI for enabling device motion permission
  50681. */
  50682. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  50683. schema: {
  50684. enabled: {default: true},
  50685. deviceMotionMessage: {
  50686. default: 'This immersive website requires access to your device motion sensors.'
  50687. },
  50688. mobileDesktopMessage: {
  50689. default: 'Set your browser to request the mobile version of the site and reload the page to enjoy immersive mode.'
  50690. },
  50691. httpsMessage: {
  50692. default: 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.'
  50693. },
  50694. denyButtonText: {default: 'Deny'},
  50695. allowButtonText: {default: 'Allow'},
  50696. cancelButtonText: {default: 'Cancel'}
  50697. },
  50698. init: function () {
  50699. var self = this;
  50700. if (!this.data.enabled) { return; }
  50701. if (location.hostname !== 'localhost' &&
  50702. location.hostname !== '127.0.0.1' &&
  50703. location.protocol === 'http:') {
  50704. this.showHTTPAlert();
  50705. }
  50706. // Show alert on iPad if Safari is on desktop mode.
  50707. if (utils.device.isMobileDeviceRequestingDesktopSite()) {
  50708. this.showMobileDesktopModeAlert();
  50709. return;
  50710. }
  50711. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  50712. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  50713. this.permissionGranted = true;
  50714. return;
  50715. }
  50716. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  50717. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  50718. // Show dialog only if permission has not yet been granted.
  50719. DeviceOrientationEvent.requestPermission().catch(function () {
  50720. self.devicePermissionDialogEl = createPermissionDialog(
  50721. self.data.denyButtonText,
  50722. self.data.allowButtonText,
  50723. self.data.deviceMotionMessage,
  50724. self.onDeviceMotionDialogAllowClicked,
  50725. self.onDeviceMotionDialogDenyClicked);
  50726. self.el.appendChild(self.devicePermissionDialogEl);
  50727. }).then(function () {
  50728. self.el.emit('deviceorientationpermissiongranted');
  50729. self.permissionGranted = true;
  50730. });
  50731. },
  50732. remove: function () {
  50733. // This removes the modal screen
  50734. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  50735. },
  50736. onDeviceMotionDialogDenyClicked: function () {
  50737. this.remove();
  50738. },
  50739. showMobileDesktopModeAlert: function () {
  50740. var self = this;
  50741. var safariIpadAlertEl = createAlertDialog(
  50742. self.data.cancelButtonText,
  50743. self.data.mobileDesktopMessage,
  50744. function () { self.el.removeChild(safariIpadAlertEl); });
  50745. this.el.appendChild(safariIpadAlertEl);
  50746. },
  50747. showHTTPAlert: function () {
  50748. var self = this;
  50749. var httpAlertEl = createAlertDialog(
  50750. self.data.cancelButtonText,
  50751. self.data.httpsMessage,
  50752. function () { self.el.removeChild(httpAlertEl); });
  50753. this.el.appendChild(httpAlertEl);
  50754. },
  50755. /**
  50756. * Enable device motion permission when clicked.
  50757. */
  50758. onDeviceMotionDialogAllowClicked: function () {
  50759. var self = this;
  50760. this.el.emit('deviceorientationpermissionrequested');
  50761. DeviceOrientationEvent.requestPermission().then(function (response) {
  50762. if (response === 'granted') {
  50763. self.el.emit('deviceorientationpermissiongranted');
  50764. self.permissionGranted = true;
  50765. } else {
  50766. self.el.emit('deviceorientationpermissionrejected');
  50767. }
  50768. self.remove();
  50769. }).catch(console.error);
  50770. }
  50771. });
  50772. /**
  50773. * Create a modal dialog that request users permission to access the Device Motion API.
  50774. *
  50775. * @param {function} onAllowClicked - click event handler
  50776. * @param {function} onDenyClicked - click event handler
  50777. *
  50778. * @returns {Element} Wrapper <div>.
  50779. */
  50780. function createPermissionDialog (
  50781. denyText, allowText, dialogText, onAllowClicked, onDenyClicked) {
  50782. var buttonsContainer;
  50783. var denyButton;
  50784. var acceptButton;
  50785. buttonsContainer = document.createElement('div');
  50786. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50787. // Buttons
  50788. denyButton = document.createElement('button');
  50789. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  50790. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  50791. denyButton.innerHTML = denyText;
  50792. buttonsContainer.appendChild(denyButton);
  50793. acceptButton = document.createElement('button');
  50794. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  50795. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  50796. acceptButton.innerHTML = allowText;
  50797. buttonsContainer.appendChild(acceptButton);
  50798. // Ask for sensor events to be used
  50799. acceptButton.addEventListener('click', function (evt) {
  50800. evt.stopPropagation();
  50801. onAllowClicked();
  50802. });
  50803. denyButton.addEventListener('click', function (evt) {
  50804. evt.stopPropagation();
  50805. onDenyClicked();
  50806. });
  50807. return createDialog(dialogText, buttonsContainer);
  50808. }
  50809. function createAlertDialog (closeText, dialogText, onOkClicked) {
  50810. var buttonsContainer;
  50811. var okButton;
  50812. buttonsContainer = document.createElement('div');
  50813. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50814. // Buttons
  50815. okButton = document.createElement('button');
  50816. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  50817. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  50818. okButton.innerHTML = closeText;
  50819. buttonsContainer.appendChild(okButton);
  50820. // Ask for sensor events to be used
  50821. okButton.addEventListener('click', function (evt) {
  50822. evt.stopPropagation();
  50823. onOkClicked();
  50824. });
  50825. return createDialog(dialogText, buttonsContainer);
  50826. }
  50827. function createDialog (text, buttonsContainerEl) {
  50828. var modalContainer;
  50829. var dialog;
  50830. var dialogTextContainer;
  50831. var dialogText;
  50832. modalContainer = document.createElement('div');
  50833. modalContainer.classList.add(MODAL_CLASS);
  50834. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  50835. dialog = document.createElement('div');
  50836. dialog.className = DIALOG_CLASS;
  50837. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  50838. modalContainer.appendChild(dialog);
  50839. dialogTextContainer = document.createElement('div');
  50840. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  50841. dialog.appendChild(dialogTextContainer);
  50842. dialogText = document.createElement('div');
  50843. dialogText.classList.add(DIALOG_TEXT_CLASS);
  50844. dialogText.innerHTML = text;
  50845. dialogTextContainer.appendChild(dialogText);
  50846. dialog.appendChild(buttonsContainerEl);
  50847. return modalContainer;
  50848. }
  50849. },{"../../constants/":124,"../../core/component":132,"../../utils/":206}],104:[function(_dereq_,module,exports){
  50850. var registerComponent = _dereq_('../../core/component').registerComponent;
  50851. /**
  50852. * Component to embed an a-frame scene within the layout of a 2D page.
  50853. */
  50854. module.exports.Component = registerComponent('embedded', {
  50855. dependencies: ['vr-mode-ui'],
  50856. schema: {default: true},
  50857. update: function () {
  50858. var sceneEl = this.el;
  50859. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  50860. if (this.data === true) {
  50861. if (enterVREl) { enterVREl.classList.add('embedded'); }
  50862. sceneEl.removeFullScreenStyles();
  50863. } else {
  50864. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  50865. sceneEl.addFullScreenStyles();
  50866. }
  50867. }
  50868. });
  50869. },{"../../core/component":132}],105:[function(_dereq_,module,exports){
  50870. var register = _dereq_('../../core/component').registerComponent;
  50871. var THREE = _dereq_('../../lib/three');
  50872. var debug = _dereq_('../../utils/debug');
  50873. var warn = debug('components:fog:warn');
  50874. /**
  50875. * Fog component.
  50876. * Applies only to the scene entity.
  50877. */
  50878. module.exports.Component = register('fog', {
  50879. schema: {
  50880. color: {type: 'color', default: '#000'},
  50881. density: {default: 0.00025},
  50882. far: {default: 1000, min: 0},
  50883. near: {default: 1, min: 0},
  50884. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  50885. },
  50886. update: function () {
  50887. var data = this.data;
  50888. var el = this.el;
  50889. var fog = this.el.object3D.fog;
  50890. if (!el.isScene) {
  50891. warn('Fog component can only be applied to <a-scene>');
  50892. return;
  50893. }
  50894. // (Re)create fog if fog doesn't exist or fog type changed.
  50895. if (!fog || data.type !== fog.name) {
  50896. el.object3D.fog = getFog(data);
  50897. el.systems.material.updateMaterials();
  50898. return;
  50899. }
  50900. // Fog data changed. Update fog.
  50901. Object.keys(this.schema).forEach(function (key) {
  50902. var value = data[key];
  50903. if (key === 'color') { value = new THREE.Color(value); }
  50904. fog[key] = value;
  50905. });
  50906. },
  50907. /**
  50908. * Remove fog on remove (callback).
  50909. */
  50910. remove: function () {
  50911. var fog = this.el.object3D.fog;
  50912. if (!fog) { return; }
  50913. fog.far = 0;
  50914. fog.near = 0.1;
  50915. }
  50916. });
  50917. /**
  50918. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  50919. *
  50920. * @param {object} data - Fog data.
  50921. * @returns {object} fog
  50922. */
  50923. function getFog (data) {
  50924. var fog;
  50925. if (data.type === 'exponential') {
  50926. fog = new THREE.FogExp2(data.color, data.density);
  50927. } else {
  50928. fog = new THREE.Fog(data.color, data.near, data.far);
  50929. }
  50930. fog.name = data.type;
  50931. return fog;
  50932. }
  50933. },{"../../core/component":132,"../../lib/three":180,"../../utils/debug":202}],106:[function(_dereq_,module,exports){
  50934. (function (process){
  50935. /* global AFRAME */
  50936. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  50937. var pkg = _dereq_('../../../package');
  50938. var registerComponent = _dereq_('../../core/component').registerComponent;
  50939. var utils = _dereq_('../../utils/');
  50940. /**
  50941. * 0.4.2 to 0.4.x
  50942. * Will need to update this when A-Frame goes to 1.x.x.
  50943. */
  50944. function getFuzzyPatchVersion (version) {
  50945. var split = version.split('.');
  50946. split[2] = 'x';
  50947. return split.join('.');
  50948. }
  50949. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  50950. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  50951. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  50952. var LOADING_MESSAGE = 'Loading Inspector';
  50953. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  50954. module.exports.Component = registerComponent('inspector', {
  50955. schema: {
  50956. url: {default: INSPECTOR_URL}
  50957. },
  50958. init: function () {
  50959. this.firstPlay = true;
  50960. this.onKeydown = this.onKeydown.bind(this);
  50961. this.onMessage = this.onMessage.bind(this);
  50962. this.initOverlay();
  50963. window.addEventListener('keydown', this.onKeydown);
  50964. window.addEventListener('message', this.onMessage);
  50965. },
  50966. play: function () {
  50967. var urlParam;
  50968. if (!this.firstPlay) { return; }
  50969. urlParam = utils.getUrlParameter('inspector');
  50970. if (urlParam !== 'false' && !!urlParam) {
  50971. this.openInspector();
  50972. this.firstPlay = false;
  50973. }
  50974. },
  50975. initOverlay: function () {
  50976. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  50977. this.loadingMessageEl = document.createElement('div');
  50978. this.loadingMessageEl.classList.add('a-inspector-loader');
  50979. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  50980. },
  50981. remove: function () {
  50982. this.removeEventListeners();
  50983. },
  50984. /**
  50985. * <ctrl> + <alt> + i keyboard shortcut.
  50986. */
  50987. onKeydown: function (evt) {
  50988. var shortcutPressed = evt.keyCode === 73 && (evt.ctrlKey && evt.altKey || evt.getModifierState('AltGraph'));
  50989. if (!shortcutPressed) { return; }
  50990. this.openInspector();
  50991. },
  50992. showLoader: function () {
  50993. document.body.appendChild(this.loadingMessageEl);
  50994. },
  50995. hideLoader: function () {
  50996. document.body.removeChild(this.loadingMessageEl);
  50997. },
  50998. /**
  50999. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  51000. */
  51001. onMessage: function (evt) {
  51002. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  51003. },
  51004. openInspector: function (focusEl) {
  51005. var self = this;
  51006. var script;
  51007. // Already injected. Open.
  51008. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  51009. AFRAME.INSPECTOR.open(focusEl);
  51010. return;
  51011. }
  51012. this.showLoader();
  51013. // Inject.
  51014. script = document.createElement('script');
  51015. script.src = this.data.url;
  51016. script.setAttribute('data-name', 'aframe-inspector');
  51017. script.setAttribute(AFRAME_INJECTED, '');
  51018. script.onload = function () {
  51019. AFRAME.INSPECTOR.open(focusEl);
  51020. self.hideLoader();
  51021. self.removeEventListeners();
  51022. };
  51023. script.onerror = function () {
  51024. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  51025. };
  51026. document.head.appendChild(script);
  51027. AFRAME.inspectorInjected = true;
  51028. },
  51029. removeEventListeners: function () {
  51030. window.removeEventListener('keydown', this.onKeydown);
  51031. window.removeEventListener('message', this.onMessage);
  51032. }
  51033. });
  51034. }).call(this,_dereq_('_process'))
  51035. },{"../../../package":73,"../../constants":124,"../../core/component":132,"../../utils/":206,"_process":49}],107:[function(_dereq_,module,exports){
  51036. var registerComponent = _dereq_('../../core/component').registerComponent;
  51037. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  51038. module.exports.Component = registerComponent('keyboard-shortcuts', {
  51039. schema: {
  51040. enterVR: {default: true},
  51041. exitVR: {default: true}
  51042. },
  51043. init: function () {
  51044. this.onKeyup = this.onKeyup.bind(this);
  51045. },
  51046. update: function (oldData) {
  51047. var data = this.data;
  51048. this.enterVREnabled = data.enterVR;
  51049. },
  51050. play: function () {
  51051. window.addEventListener('keyup', this.onKeyup, false);
  51052. },
  51053. pause: function () {
  51054. window.removeEventListener('keyup', this.onKeyup);
  51055. },
  51056. onKeyup: function (evt) {
  51057. var scene = this.el;
  51058. if (!shouldCaptureKeyEvent(evt)) { return; }
  51059. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  51060. scene.enterVR();
  51061. }
  51062. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  51063. scene.exitVR();
  51064. }
  51065. }
  51066. });
  51067. },{"../../core/component":132,"../../utils/":206}],108:[function(_dereq_,module,exports){
  51068. var debug = _dereq_('../../utils/debug');
  51069. var registerComponent = _dereq_('../../core/component').registerComponent;
  51070. var warn = debug('components:pool:warn');
  51071. /**
  51072. * Pool component to reuse entities.
  51073. * Avoids creating and destroying the same kind of entities.
  51074. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  51075. *
  51076. * @member {array} availableEls - Available entities in the pool.
  51077. * @member {array} usedEls - Entities of the pool in use.
  51078. */
  51079. module.exports.Component = registerComponent('pool', {
  51080. schema: {
  51081. container: {default: ''},
  51082. mixin: {default: ''},
  51083. size: {default: 0},
  51084. dynamic: {default: false}
  51085. },
  51086. multiple: true,
  51087. initPool: function () {
  51088. var i;
  51089. this.availableEls = [];
  51090. this.usedEls = [];
  51091. if (!this.data.mixin) {
  51092. warn('No mixin provided for pool component.');
  51093. }
  51094. if (this.data.container) {
  51095. this.container = document.querySelector(this.data.container);
  51096. if (!this.container) {
  51097. warn('Container ' + this.data.container + ' not found.');
  51098. }
  51099. }
  51100. this.container = this.container || this.el;
  51101. for (i = 0; i < this.data.size; ++i) {
  51102. this.createEntity();
  51103. }
  51104. },
  51105. update: function (oldData) {
  51106. var data = this.data;
  51107. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  51108. this.initPool();
  51109. }
  51110. },
  51111. /**
  51112. * Add a new entity to the list of available entities.
  51113. */
  51114. createEntity: function () {
  51115. var el;
  51116. el = document.createElement('a-entity');
  51117. el.play = this.wrapPlay(el.play);
  51118. el.setAttribute('mixin', this.data.mixin);
  51119. el.object3D.visible = false;
  51120. el.pause();
  51121. this.container.appendChild(el);
  51122. this.availableEls.push(el);
  51123. },
  51124. /**
  51125. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  51126. * entities that are not in use.
  51127. */
  51128. wrapPlay: function (playMethod) {
  51129. var usedEls = this.usedEls;
  51130. return function () {
  51131. if (usedEls.indexOf(this) === -1) { return; }
  51132. playMethod.call(this);
  51133. };
  51134. },
  51135. /**
  51136. * Used to request one of the available entities of the pool.
  51137. */
  51138. requestEntity: function () {
  51139. var el;
  51140. if (this.availableEls.length === 0) {
  51141. if (this.data.dynamic === false) {
  51142. warn('Requested entity from empty pool: ' + this.attrName);
  51143. return;
  51144. } else {
  51145. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  51146. 'automatically. You might want to increase its initial size: ' + this.attrName);
  51147. }
  51148. this.createEntity();
  51149. }
  51150. el = this.availableEls.shift();
  51151. this.usedEls.push(el);
  51152. el.object3D.visible = true;
  51153. return el;
  51154. },
  51155. /**
  51156. * Used to return a used entity to the pool.
  51157. */
  51158. returnEntity: function (el) {
  51159. var index = this.usedEls.indexOf(el);
  51160. if (index === -1) {
  51161. warn('The returned entity was not previously pooled from ' + this.attrName);
  51162. return;
  51163. }
  51164. this.usedEls.splice(index, 1);
  51165. this.availableEls.push(el);
  51166. el.object3D.visible = false;
  51167. el.pause();
  51168. return el;
  51169. }
  51170. });
  51171. },{"../../core/component":132,"../../utils/debug":202}],109:[function(_dereq_,module,exports){
  51172. /* global ImageData, URL */
  51173. var registerComponent = _dereq_('../../core/component').registerComponent;
  51174. var THREE = _dereq_('../../lib/three');
  51175. var VERTEX_SHADER = [
  51176. 'attribute vec3 position;',
  51177. 'attribute vec2 uv;',
  51178. 'uniform mat4 projectionMatrix;',
  51179. 'uniform mat4 modelViewMatrix;',
  51180. 'varying vec2 vUv;',
  51181. 'void main() {',
  51182. ' vUv = vec2( 1.- uv.x, uv.y );',
  51183. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  51184. '}'
  51185. ].join('\n');
  51186. var FRAGMENT_SHADER = [
  51187. 'precision mediump float;',
  51188. 'uniform samplerCube map;',
  51189. 'varying vec2 vUv;',
  51190. '#define M_PI 3.141592653589793238462643383279',
  51191. 'void main() {',
  51192. ' vec2 uv = vUv;',
  51193. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  51194. ' float latitude = uv.y * M_PI;',
  51195. ' vec3 dir = vec3(',
  51196. ' - sin( longitude ) * sin( latitude ),',
  51197. ' cos( latitude ),',
  51198. ' - cos( longitude ) * sin( latitude )',
  51199. ' );',
  51200. ' normalize( dir );',
  51201. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  51202. '}'
  51203. ].join('\n');
  51204. /**
  51205. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  51206. * It can be configured to either take 360&deg; captures (`equirectangular`)
  51207. * or regular screenshots (`projection`)
  51208. *
  51209. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  51210. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  51211. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  51212. * WebGLRenderTarget with an ortographic camera.
  51213. */
  51214. module.exports.Component = registerComponent('screenshot', {
  51215. schema: {
  51216. width: {default: 4096},
  51217. height: {default: 2048},
  51218. camera: {type: 'selector'}
  51219. },
  51220. init: function () {
  51221. var el = this.el;
  51222. var self = this;
  51223. if (el.renderer) {
  51224. setup();
  51225. } else {
  51226. el.addEventListener('render-target-loaded', setup);
  51227. }
  51228. function setup () {
  51229. var gl = el.renderer.getContext();
  51230. if (!gl) { return; }
  51231. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  51232. self.material = new THREE.RawShaderMaterial({
  51233. uniforms: {map: {type: 't', value: null}},
  51234. vertexShader: VERTEX_SHADER,
  51235. fragmentShader: FRAGMENT_SHADER,
  51236. side: THREE.DoubleSide
  51237. });
  51238. self.quad = new THREE.Mesh(
  51239. new THREE.PlaneBufferGeometry(1, 1),
  51240. self.material
  51241. );
  51242. self.quad.visible = false;
  51243. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  51244. self.canvas = document.createElement('canvas');
  51245. self.ctx = self.canvas.getContext('2d');
  51246. el.object3D.add(self.quad);
  51247. self.onKeyDown = self.onKeyDown.bind(self);
  51248. }
  51249. },
  51250. getRenderTarget: function (width, height) {
  51251. return new THREE.WebGLRenderTarget(width, height, {
  51252. encoding: THREE.sRGBEncoding,
  51253. minFilter: THREE.LinearFilter,
  51254. magFilter: THREE.LinearFilter,
  51255. wrapS: THREE.ClampToEdgeWrapping,
  51256. wrapT: THREE.ClampToEdgeWrapping,
  51257. format: THREE.RGBAFormat,
  51258. type: THREE.UnsignedByteType
  51259. });
  51260. },
  51261. resize: function (width, height) {
  51262. // Resize quad.
  51263. this.quad.scale.set(width, height, 1);
  51264. // Resize camera.
  51265. this.camera.left = -1 * width / 2;
  51266. this.camera.right = width / 2;
  51267. this.camera.top = height / 2;
  51268. this.camera.bottom = -1 * height / 2;
  51269. this.camera.updateProjectionMatrix();
  51270. // Resize canvas.
  51271. this.canvas.width = width;
  51272. this.canvas.height = height;
  51273. },
  51274. play: function () {
  51275. window.addEventListener('keydown', this.onKeyDown);
  51276. },
  51277. /**
  51278. * <ctrl> + <alt> + s = Regular screenshot.
  51279. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  51280. */
  51281. onKeyDown: function (evt) {
  51282. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  51283. if (!this.data || !shortcutPressed) { return; }
  51284. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  51285. this.capture(projection);
  51286. },
  51287. /**
  51288. * Capture a screenshot of the scene.
  51289. *
  51290. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  51291. */
  51292. setCapture: function (projection) {
  51293. var el = this.el;
  51294. var size;
  51295. var camera;
  51296. var cubeCamera;
  51297. var cubeRenderTarget;
  51298. // Configure camera.
  51299. if (projection === 'perspective') {
  51300. // Quad is only used in equirectangular mode. Hide it in this case.
  51301. this.quad.visible = false;
  51302. // Use scene camera.
  51303. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  51304. size = {width: this.data.width, height: this.data.height};
  51305. } else {
  51306. // Use ortho camera.
  51307. camera = this.camera;
  51308. cubeRenderTarget = new THREE.WebGLCubeRenderTarget(
  51309. Math.min(this.cubeMapSize, 2048),
  51310. {
  51311. format: THREE.RGBFormat,
  51312. generateMipmaps: true,
  51313. minFilter: THREE.LinearMipmapLinearFilter,
  51314. encoding: THREE.sRGBEncoding
  51315. });
  51316. // Create cube camera and copy position from scene camera.
  51317. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, cubeRenderTarget);
  51318. // Copy camera position into cube camera;
  51319. el.camera.getWorldPosition(cubeCamera.position);
  51320. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  51321. // Render scene with cube camera.
  51322. cubeCamera.update(el.renderer, el.object3D);
  51323. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  51324. size = {width: this.data.width, height: this.data.height};
  51325. // Use quad to project image taken by the cube camera.
  51326. this.quad.visible = true;
  51327. }
  51328. return {
  51329. camera: camera,
  51330. size: size,
  51331. projection: projection
  51332. };
  51333. },
  51334. /**
  51335. * Maintained for backwards compatibility.
  51336. */
  51337. capture: function (projection) {
  51338. var isVREnabled = this.el.renderer.xr.enabled;
  51339. var renderer = this.el.renderer;
  51340. var params;
  51341. // Disable VR.
  51342. renderer.xr.enabled = false;
  51343. params = this.setCapture(projection);
  51344. this.renderCapture(params.camera, params.size, params.projection);
  51345. // Trigger file download.
  51346. this.saveCapture();
  51347. // Restore VR.
  51348. renderer.xr.enabled = isVREnabled;
  51349. },
  51350. /**
  51351. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  51352. */
  51353. getCanvas: function (projection) {
  51354. var isVREnabled = this.el.renderer.xr.enabled;
  51355. var renderer = this.el.renderer;
  51356. // Disable VR.
  51357. var params = this.setCapture(projection);
  51358. renderer.xr.enabled = false;
  51359. this.renderCapture(params.camera, params.size, params.projection);
  51360. // Restore VR.
  51361. renderer.xr.enabled = isVREnabled;
  51362. return this.canvas;
  51363. },
  51364. renderCapture: function (camera, size, projection) {
  51365. var autoClear = this.el.renderer.autoClear;
  51366. var el = this.el;
  51367. var imageData;
  51368. var output;
  51369. var pixels;
  51370. var renderer = el.renderer;
  51371. // Create rendering target and buffer to store the read pixels.
  51372. output = this.getRenderTarget(size.width, size.height);
  51373. pixels = new Uint8Array(4 * size.width * size.height);
  51374. // Resize quad, camera, and canvas.
  51375. this.resize(size.width, size.height);
  51376. // Render scene to render target.
  51377. renderer.autoClear = true;
  51378. renderer.clear();
  51379. renderer.setRenderTarget(output);
  51380. renderer.render(el.object3D, camera);
  51381. renderer.autoClear = autoClear;
  51382. // Read image pizels back.
  51383. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  51384. renderer.setRenderTarget(null);
  51385. if (projection === 'perspective') {
  51386. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  51387. }
  51388. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  51389. // Hide quad after projecting the image.
  51390. this.quad.visible = false;
  51391. // Copy pixels into canvas.
  51392. this.ctx.putImageData(imageData, 0, 0);
  51393. },
  51394. flipPixelsVertically: function (pixels, width, height) {
  51395. var flippedPixels = pixels.slice(0);
  51396. for (var x = 0; x < width; ++x) {
  51397. for (var y = 0; y < height; ++y) {
  51398. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  51399. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  51400. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  51401. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  51402. }
  51403. }
  51404. return flippedPixels;
  51405. },
  51406. /**
  51407. * Download capture to file.
  51408. */
  51409. saveCapture: function () {
  51410. this.canvas.toBlob(function (blob) {
  51411. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  51412. var linkEl = document.createElement('a');
  51413. var url = URL.createObjectURL(blob);
  51414. linkEl.href = url;
  51415. linkEl.setAttribute('download', fileName);
  51416. linkEl.innerHTML = 'downloading...';
  51417. linkEl.style.display = 'none';
  51418. document.body.appendChild(linkEl);
  51419. setTimeout(function () {
  51420. linkEl.click();
  51421. document.body.removeChild(linkEl);
  51422. }, 1);
  51423. }, 'image/png');
  51424. }
  51425. });
  51426. },{"../../core/component":132,"../../lib/three":180}],110:[function(_dereq_,module,exports){
  51427. var registerComponent = _dereq_('../../core/component').registerComponent;
  51428. var RStats = _dereq_('../../../vendor/rStats');
  51429. var utils = _dereq_('../../utils');
  51430. _dereq_('../../../vendor/rStats.extras');
  51431. _dereq_('../../lib/rStatsAframe');
  51432. var AFrameStats = window.aframeStats;
  51433. var bind = utils.bind;
  51434. var HIDDEN_CLASS = 'a-hidden';
  51435. var ThreeStats = window.threeStats;
  51436. /**
  51437. * Stats appended to document.body by RStats.
  51438. */
  51439. module.exports.Component = registerComponent('stats', {
  51440. schema: {default: true},
  51441. init: function () {
  51442. var scene = this.el;
  51443. if (utils.getUrlParameter('stats') === 'false') { return; }
  51444. this.stats = createStats(scene);
  51445. this.statsEl = document.querySelector('.rs-base');
  51446. this.hideBound = bind(this.hide, this);
  51447. this.showBound = bind(this.show, this);
  51448. scene.addEventListener('enter-vr', this.hideBound);
  51449. scene.addEventListener('exit-vr', this.showBound);
  51450. },
  51451. update: function () {
  51452. if (!this.stats) { return; }
  51453. return (!this.data) ? this.hide() : this.show();
  51454. },
  51455. remove: function () {
  51456. this.el.removeEventListener('enter-vr', this.hideBound);
  51457. this.el.removeEventListener('exit-vr', this.showBound);
  51458. if (!this.statsEl) { return; } // Scene detached.
  51459. this.statsEl.parentNode.removeChild(this.statsEl);
  51460. },
  51461. tick: function () {
  51462. var stats = this.stats;
  51463. if (!stats) { return; }
  51464. stats('rAF').tick();
  51465. stats('FPS').frame();
  51466. stats().update();
  51467. },
  51468. hide: function () {
  51469. this.statsEl.classList.add(HIDDEN_CLASS);
  51470. },
  51471. show: function () {
  51472. this.statsEl.classList.remove(HIDDEN_CLASS);
  51473. }
  51474. });
  51475. function createStats (scene) {
  51476. var threeStats = new ThreeStats(scene.renderer);
  51477. var aframeStats = new AFrameStats(scene);
  51478. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  51479. return new RStats({
  51480. css: [], // Our stylesheet is injected from `src/index.js`.
  51481. values: {
  51482. fps: {caption: 'fps', below: 30}
  51483. },
  51484. groups: [
  51485. {caption: 'Framerate', values: ['fps', 'raf']}
  51486. ],
  51487. plugins: plugins
  51488. });
  51489. }
  51490. },{"../../../vendor/rStats":218,"../../../vendor/rStats.extras":217,"../../core/component":132,"../../lib/rStatsAframe":179,"../../utils":206}],111:[function(_dereq_,module,exports){
  51491. var registerComponent = _dereq_('../../core/component').registerComponent;
  51492. var constants = _dereq_('../../constants/');
  51493. var utils = _dereq_('../../utils/');
  51494. var bind = utils.bind;
  51495. var ENTER_VR_CLASS = 'a-enter-vr';
  51496. var ENTER_AR_CLASS = 'a-enter-ar';
  51497. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  51498. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  51499. var HIDDEN_CLASS = 'a-hidden';
  51500. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  51501. /**
  51502. * UI for entering VR mode.
  51503. */
  51504. module.exports.Component = registerComponent('vr-mode-ui', {
  51505. dependencies: ['canvas'],
  51506. schema: {
  51507. enabled: {default: true},
  51508. enterVRButton: {default: ''},
  51509. enterARButton: {default: ''}
  51510. },
  51511. init: function () {
  51512. var self = this;
  51513. var sceneEl = this.el;
  51514. if (utils.getUrlParameter('ui') === 'false') { return; }
  51515. this.insideLoader = false;
  51516. this.enterVREl = null;
  51517. this.enterAREl = null;
  51518. this.orientationModalEl = null;
  51519. this.bindMethods();
  51520. // Hide/show VR UI when entering/exiting VR mode.
  51521. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  51522. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  51523. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  51524. window.addEventListener('message', function (event) {
  51525. if (event.data.type === 'loaderReady') {
  51526. self.insideLoader = true;
  51527. self.remove();
  51528. }
  51529. });
  51530. // Modal that tells the user to change orientation if in portrait.
  51531. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  51532. },
  51533. bindMethods: function () {
  51534. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  51535. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  51536. this.onModalClick = bind(this.onModalClick, this);
  51537. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  51538. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  51539. },
  51540. /**
  51541. * Exit VR when modal clicked.
  51542. */
  51543. onModalClick: function () {
  51544. this.el.exitVR();
  51545. },
  51546. /**
  51547. * Enter VR when clicked.
  51548. */
  51549. onEnterVRButtonClick: function () {
  51550. this.el.enterVR();
  51551. },
  51552. /**
  51553. * Enter AR when clicked.
  51554. */
  51555. onEnterARButtonClick: function () {
  51556. this.el.enterAR();
  51557. },
  51558. update: function () {
  51559. var data = this.data;
  51560. var sceneEl = this.el;
  51561. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  51562. return this.remove();
  51563. }
  51564. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  51565. // Add UI if enabled and not already present.
  51566. if (data.enterVRButton) {
  51567. // Custom button.
  51568. this.enterVREl = document.querySelector(data.enterVRButton);
  51569. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  51570. } else {
  51571. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  51572. sceneEl.appendChild(this.enterVREl);
  51573. }
  51574. if (data.enterARButton) {
  51575. // Custom button.
  51576. this.enterAREl = document.querySelector(data.enterARButton);
  51577. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  51578. } else {
  51579. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  51580. sceneEl.appendChild(this.enterAREl);
  51581. }
  51582. this.orientationModalEl = createOrientationModal(this.onModalClick);
  51583. sceneEl.appendChild(this.orientationModalEl);
  51584. this.updateEnterInterfaces();
  51585. },
  51586. remove: function () {
  51587. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  51588. if (uiElement && uiElement.parentNode) {
  51589. uiElement.parentNode.removeChild(uiElement);
  51590. }
  51591. });
  51592. this.enterVREl = undefined;
  51593. this.enterAREl = undefined;
  51594. this.orientationModalEl = undefined;
  51595. },
  51596. updateEnterInterfaces: function () {
  51597. this.toggleEnterVRButtonIfNeeded();
  51598. this.toggleEnterARButtonIfNeeded();
  51599. this.toggleOrientationModalIfNeeded();
  51600. },
  51601. toggleEnterVRButtonIfNeeded: function () {
  51602. var sceneEl = this.el;
  51603. if (!this.enterVREl) { return; }
  51604. if (sceneEl.is('vr-mode')) {
  51605. this.enterVREl.classList.add(HIDDEN_CLASS);
  51606. } else {
  51607. this.enterVREl.classList.remove(HIDDEN_CLASS);
  51608. }
  51609. },
  51610. toggleEnterARButtonIfNeeded: function () {
  51611. var sceneEl = this.el;
  51612. if (!this.enterAREl) { return; }
  51613. // Hide the button while in a session, or if AR is not supported.
  51614. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  51615. this.enterAREl.classList.add(HIDDEN_CLASS);
  51616. } else {
  51617. this.enterAREl.classList.remove(HIDDEN_CLASS);
  51618. }
  51619. },
  51620. toggleOrientationModalIfNeeded: function () {
  51621. var sceneEl = this.el;
  51622. var orientationModalEl = this.orientationModalEl;
  51623. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  51624. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  51625. // Show if in VR mode on portrait.
  51626. orientationModalEl.classList.remove(HIDDEN_CLASS);
  51627. } else {
  51628. orientationModalEl.classList.add(HIDDEN_CLASS);
  51629. }
  51630. }
  51631. });
  51632. /**
  51633. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  51634. *
  51635. * Structure: <div><button></div>
  51636. *
  51637. * @param {function} onClick - click event handler
  51638. * @returns {Element} Wrapper <div>.
  51639. */
  51640. function createEnterVRButton (onClick) {
  51641. var vrButton;
  51642. var wrapper;
  51643. // Create elements.
  51644. wrapper = document.createElement('div');
  51645. wrapper.classList.add(ENTER_VR_CLASS);
  51646. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51647. vrButton = document.createElement('button');
  51648. vrButton.className = ENTER_VR_BTN_CLASS;
  51649. vrButton.setAttribute('title',
  51650. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  51651. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51652. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  51653. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  51654. // Insert elements.
  51655. wrapper.appendChild(vrButton);
  51656. vrButton.addEventListener('click', function (evt) {
  51657. onClick();
  51658. evt.stopPropagation();
  51659. });
  51660. return wrapper;
  51661. }
  51662. /**
  51663. * Create a button that when clicked will enter into AR mode
  51664. *
  51665. * Structure: <div><button></div>
  51666. *
  51667. * @param {function} onClick - click event handler
  51668. * @returns {Element} Wrapper <div>.
  51669. */
  51670. function createEnterARButton (onClick) {
  51671. var arButton;
  51672. var wrapper;
  51673. // Create elements.
  51674. wrapper = document.createElement('div');
  51675. wrapper.classList.add(ENTER_AR_CLASS);
  51676. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51677. arButton = document.createElement('button');
  51678. arButton.className = ENTER_AR_BTN_CLASS;
  51679. arButton.setAttribute('title',
  51680. 'Enter AR mode with a headset or handheld device. ' +
  51681. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51682. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  51683. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  51684. // Insert elements.
  51685. wrapper.appendChild(arButton);
  51686. arButton.addEventListener('click', function (evt) {
  51687. onClick();
  51688. evt.stopPropagation();
  51689. });
  51690. return wrapper;
  51691. }
  51692. /**
  51693. * Creates a modal dialog to request the user to switch to landscape orientation.
  51694. *
  51695. * @param {function} onClick - click event handler
  51696. * @returns {Element} Wrapper <div>.
  51697. */
  51698. function createOrientationModal (onClick) {
  51699. var modal = document.createElement('div');
  51700. modal.className = ORIENTATION_MODAL_CLASS;
  51701. modal.classList.add(HIDDEN_CLASS);
  51702. modal.setAttribute(constants.AFRAME_INJECTED, '');
  51703. var exit = document.createElement('button');
  51704. exit.setAttribute(constants.AFRAME_INJECTED, '');
  51705. exit.innerHTML = 'Exit VR';
  51706. // Exit VR on close.
  51707. exit.addEventListener('click', onClick);
  51708. modal.appendChild(exit);
  51709. return modal;
  51710. }
  51711. /**
  51712. * CSS hover state is sticky in iOS (as in 12/18/2019)
  51713. * They are not removed on mouseleave and this function applies a class
  51714. * to resets the style.
  51715. *
  51716. * @param {function} buttonEl - Button element
  51717. */
  51718. function applyStickyHoverFix (buttonEl) {
  51719. buttonEl.addEventListener('touchstart', function () {
  51720. buttonEl.classList.remove('resethover');
  51721. });
  51722. buttonEl.addEventListener('touchend', function () {
  51723. buttonEl.classList.add('resethover');
  51724. });
  51725. }
  51726. },{"../../constants/":124,"../../core/component":132,"../../utils/":206}],112:[function(_dereq_,module,exports){
  51727. var component = _dereq_('../core/component');
  51728. var THREE = _dereq_('../lib/three');
  51729. var bind = _dereq_('../utils/bind');
  51730. var registerComponent = component.registerComponent;
  51731. /**
  51732. * Shadow component.
  51733. *
  51734. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  51735. * shadows as specified by the `cast` and `receive` properties.
  51736. */
  51737. module.exports.Component = registerComponent('shadow', {
  51738. schema: {
  51739. cast: {default: true},
  51740. receive: {default: true}
  51741. },
  51742. init: function () {
  51743. this.onMeshChanged = bind(this.update, this);
  51744. this.el.addEventListener('object3dset', this.onMeshChanged);
  51745. this.system.setShadowMapEnabled(true);
  51746. },
  51747. update: function () {
  51748. var data = this.data;
  51749. this.updateDescendants(data.cast, data.receive);
  51750. },
  51751. remove: function () {
  51752. var el = this.el;
  51753. el.removeEventListener('object3dset', this.onMeshChanged);
  51754. this.updateDescendants(false, false);
  51755. },
  51756. updateDescendants: function (cast, receive) {
  51757. var sceneEl = this.el.sceneEl;
  51758. this.el.object3D.traverse(function (node) {
  51759. if (!(node instanceof THREE.Mesh)) { return; }
  51760. node.castShadow = cast;
  51761. node.receiveShadow = receive;
  51762. // If scene has already rendered, materials must be updated.
  51763. if (sceneEl.hasLoaded && node.material) {
  51764. var materials = Array.isArray(node.material) ? node.material : [node.material];
  51765. for (var i = 0; i < materials.length; i++) {
  51766. materials[i].needsUpdate = true;
  51767. }
  51768. }
  51769. });
  51770. }
  51771. });
  51772. },{"../core/component":132,"../lib/three":180,"../utils/bind":200}],113:[function(_dereq_,module,exports){
  51773. var registerComponent = _dereq_('../core/component').registerComponent;
  51774. var debug = _dereq_('../utils/debug');
  51775. var THREE = _dereq_('../lib/three');
  51776. var warn = debug('components:sound:warn');
  51777. /**
  51778. * Sound component.
  51779. */
  51780. module.exports.Component = registerComponent('sound', {
  51781. schema: {
  51782. autoplay: {default: false},
  51783. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  51784. loop: {default: false},
  51785. maxDistance: {default: 10000},
  51786. on: {default: ''},
  51787. poolSize: {default: 1},
  51788. positional: {default: true},
  51789. refDistance: {default: 1},
  51790. rolloffFactor: {default: 1},
  51791. src: {type: 'audio'},
  51792. volume: {default: 1}
  51793. },
  51794. multiple: true,
  51795. init: function () {
  51796. var self = this;
  51797. this.listener = null;
  51798. this.audioLoader = new THREE.AudioLoader();
  51799. this.pool = new THREE.Group();
  51800. this.loaded = false;
  51801. this.mustPlay = false;
  51802. // Don't pass evt because playSound takes a function as parameter.
  51803. this.playSoundBound = function () { self.playSound(); };
  51804. },
  51805. update: function (oldData) {
  51806. var data = this.data;
  51807. var i;
  51808. var sound;
  51809. var srcChanged = data.src !== oldData.src;
  51810. // Create new sound if not yet created or changing `src`.
  51811. if (srcChanged) {
  51812. if (!data.src) { return; }
  51813. this.setupSound();
  51814. }
  51815. for (i = 0; i < this.pool.children.length; i++) {
  51816. sound = this.pool.children[i];
  51817. if (data.positional) {
  51818. sound.setDistanceModel(data.distanceModel);
  51819. sound.setMaxDistance(data.maxDistance);
  51820. sound.setRefDistance(data.refDistance);
  51821. sound.setRolloffFactor(data.rolloffFactor);
  51822. }
  51823. sound.setLoop(data.loop);
  51824. sound.setVolume(data.volume);
  51825. sound.isPaused = false;
  51826. }
  51827. if (data.on !== oldData.on) {
  51828. this.updateEventListener(oldData.on);
  51829. }
  51830. // All sound values set. Load in `src`.
  51831. if (srcChanged) {
  51832. var self = this;
  51833. this.loaded = false;
  51834. this.audioLoader.load(data.src, function (buffer) {
  51835. for (i = 0; i < self.pool.children.length; i++) {
  51836. sound = self.pool.children[i];
  51837. sound.setBuffer(buffer);
  51838. }
  51839. self.loaded = true;
  51840. // Remove this key from cache, otherwise we can't play it again
  51841. THREE.Cache.remove(data.src);
  51842. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  51843. self.el.emit('sound-loaded', self.evtDetail, false);
  51844. });
  51845. }
  51846. },
  51847. pause: function () {
  51848. this.stopSound();
  51849. this.removeEventListener();
  51850. },
  51851. play: function () {
  51852. if (this.data.autoplay) { this.playSound(); }
  51853. this.updateEventListener();
  51854. },
  51855. remove: function () {
  51856. var i;
  51857. var sound;
  51858. this.removeEventListener();
  51859. if (this.el.getObject3D(this.attrName)) {
  51860. this.el.removeObject3D(this.attrName);
  51861. }
  51862. try {
  51863. for (i = 0; i < this.pool.children.length; i++) {
  51864. sound = this.pool.children[i];
  51865. sound.disconnect();
  51866. }
  51867. } catch (e) {
  51868. // disconnect() will throw if it was never connected initially.
  51869. warn('Audio source not properly disconnected');
  51870. }
  51871. },
  51872. /**
  51873. * Update listener attached to the user defined on event.
  51874. */
  51875. updateEventListener: function (oldEvt) {
  51876. var el = this.el;
  51877. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  51878. el.addEventListener(this.data.on, this.playSoundBound);
  51879. },
  51880. removeEventListener: function () {
  51881. this.el.removeEventListener(this.data.on, this.playSoundBound);
  51882. },
  51883. /**
  51884. * Removes current sound object, creates new sound object, adds to entity.
  51885. *
  51886. * @returns {object} sound
  51887. */
  51888. setupSound: function () {
  51889. var el = this.el;
  51890. var i;
  51891. var sceneEl = el.sceneEl;
  51892. var self = this;
  51893. var sound;
  51894. if (this.pool.children.length > 0) {
  51895. this.stopSound();
  51896. el.removeObject3D('sound');
  51897. }
  51898. // Only want one AudioListener. Cache it on the scene.
  51899. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  51900. sceneEl.audioListener = listener;
  51901. if (sceneEl.camera) {
  51902. sceneEl.camera.add(listener);
  51903. }
  51904. // Wait for camera if necessary.
  51905. sceneEl.addEventListener('camera-set-active', function (evt) {
  51906. evt.detail.cameraEl.getObject3D('camera').add(listener);
  51907. });
  51908. // Create [poolSize] audio instances and attach them to pool
  51909. this.pool = new THREE.Group();
  51910. for (i = 0; i < this.data.poolSize; i++) {
  51911. sound = this.data.positional
  51912. ? new THREE.PositionalAudio(listener)
  51913. : new THREE.Audio(listener);
  51914. this.pool.add(sound);
  51915. }
  51916. el.setObject3D(this.attrName, this.pool);
  51917. for (i = 0; i < this.pool.children.length; i++) {
  51918. sound = this.pool.children[i];
  51919. sound.onEnded = function () {
  51920. this.isPlaying = false;
  51921. self.el.emit('sound-ended', self.evtDetail, false);
  51922. };
  51923. }
  51924. },
  51925. /**
  51926. * Pause all the sounds in the pool.
  51927. */
  51928. pauseSound: function () {
  51929. var i;
  51930. var sound;
  51931. this.isPlaying = false;
  51932. for (i = 0; i < this.pool.children.length; i++) {
  51933. sound = this.pool.children[i];
  51934. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  51935. continue;
  51936. }
  51937. sound.isPaused = true;
  51938. sound.pause();
  51939. }
  51940. },
  51941. /**
  51942. * Look for an unused sound in the pool and play it if found.
  51943. */
  51944. playSound: function (processSound) {
  51945. var found;
  51946. var i;
  51947. var sound;
  51948. if (!this.loaded) {
  51949. warn('Sound not loaded yet. It will be played once it finished loading');
  51950. this.mustPlay = true;
  51951. return;
  51952. }
  51953. found = false;
  51954. this.isPlaying = true;
  51955. for (i = 0; i < this.pool.children.length; i++) {
  51956. sound = this.pool.children[i];
  51957. if (!sound.isPlaying && sound.buffer && !found) {
  51958. if (processSound) { processSound(sound); }
  51959. sound.play();
  51960. sound.isPaused = false;
  51961. found = true;
  51962. continue;
  51963. }
  51964. }
  51965. if (!found) {
  51966. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  51967. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  51968. return;
  51969. }
  51970. this.mustPlay = false;
  51971. },
  51972. /**
  51973. * Stop all the sounds in the pool.
  51974. */
  51975. stopSound: function () {
  51976. var i;
  51977. var sound;
  51978. this.isPlaying = false;
  51979. for (i = 0; i < this.pool.children.length; i++) {
  51980. sound = this.pool.children[i];
  51981. if (!sound.source || !sound.source.buffer) { return; }
  51982. sound.stop();
  51983. }
  51984. }
  51985. });
  51986. },{"../core/component":132,"../lib/three":180,"../utils/debug":202}],114:[function(_dereq_,module,exports){
  51987. var createTextGeometry = _dereq_('three-bmfont-text');
  51988. var loadBMFont = _dereq_('load-bmfont');
  51989. var registerComponent = _dereq_('../core/component').registerComponent;
  51990. var coreShader = _dereq_('../core/shader');
  51991. var THREE = _dereq_('../lib/three');
  51992. var utils = _dereq_('../utils/');
  51993. var error = utils.debug('components:text:error');
  51994. var shaders = coreShader.shaders;
  51995. var warn = utils.debug('components:text:warn');
  51996. // 1 to match other A-Frame default widths.
  51997. var DEFAULT_WIDTH = 1;
  51998. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  51999. var MAX_ANISOTROPY = 16;
  52000. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  52001. var FONTS = {
  52002. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  52003. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  52004. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  52005. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  52006. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  52007. monoid: FONT_BASE_URL + 'Monoid.fnt',
  52008. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  52009. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  52010. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  52011. };
  52012. var MSDF_FONTS = ['roboto'];
  52013. var DEFAULT_FONT = 'roboto';
  52014. module.exports.FONTS = FONTS;
  52015. var cache = new PromiseCache();
  52016. var fontWidthFactors = {};
  52017. var textures = {};
  52018. // Regular expression for detecting a URLs with a protocol prefix.
  52019. var protocolRe = /^\w+:/;
  52020. /**
  52021. * SDF-based text component.
  52022. * Based on https://github.com/Jam3/three-bmfont-text.
  52023. *
  52024. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  52025. * original `sdf` shader.
  52026. */
  52027. module.exports.Component = registerComponent('text', {
  52028. multiple: true,
  52029. schema: {
  52030. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  52031. alphaTest: {default: 0.5},
  52032. // `anchor` defaults to center to match geometries.
  52033. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  52034. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  52035. color: {type: 'color', default: '#FFF'},
  52036. font: {type: 'string', default: DEFAULT_FONT},
  52037. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  52038. fontImage: {type: 'string'},
  52039. // `height` has no default, will be populated at layout.
  52040. height: {type: 'number'},
  52041. letterSpacing: {type: 'number', default: 0},
  52042. // `lineHeight` defaults to font's `lineHeight` value.
  52043. lineHeight: {type: 'number'},
  52044. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  52045. negate: {type: 'boolean', default: true},
  52046. opacity: {type: 'number', default: 1.0},
  52047. shader: {default: 'sdf', oneOf: shaders},
  52048. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  52049. tabSize: {default: 4},
  52050. transparent: {default: true},
  52051. value: {type: 'string'},
  52052. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  52053. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  52054. width: {type: 'number'},
  52055. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  52056. wrapCount: {type: 'number', default: 40},
  52057. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  52058. wrapPixels: {type: 'number'},
  52059. // `xOffset` to add padding.
  52060. xOffset: {type: 'number', default: 0},
  52061. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  52062. yOffset: {type: 'number', default: 0},
  52063. // `zOffset` will provide a small z offset to avoid z-fighting.
  52064. zOffset: {type: 'number', default: 0.001}
  52065. },
  52066. init: function () {
  52067. this.shaderData = {};
  52068. this.geometry = createTextGeometry();
  52069. this.createOrUpdateMaterial();
  52070. },
  52071. update: function (oldData) {
  52072. var data = this.data;
  52073. var font = this.currentFont;
  52074. if (textures[data.font]) {
  52075. this.texture = textures[data.font];
  52076. } else {
  52077. // Create texture per font.
  52078. this.texture = textures[data.font] = new THREE.Texture();
  52079. this.texture.anisotropy = MAX_ANISOTROPY;
  52080. }
  52081. // Update material.
  52082. this.createOrUpdateMaterial();
  52083. // New font. `updateFont` will later change data and layout.
  52084. if (oldData.font !== data.font) {
  52085. this.updateFont();
  52086. return;
  52087. }
  52088. // Update geometry and layout.
  52089. if (font) {
  52090. this.updateGeometry(this.geometry, font);
  52091. this.updateLayout();
  52092. }
  52093. },
  52094. /**
  52095. * Clean up geometry, material, texture, mesh, objects.
  52096. */
  52097. remove: function () {
  52098. this.geometry.dispose();
  52099. this.geometry = null;
  52100. this.el.removeObject3D(this.attrName);
  52101. this.material.dispose();
  52102. this.material = null;
  52103. this.texture.dispose();
  52104. this.texture = null;
  52105. if (this.shaderObject) { delete this.shaderObject; }
  52106. },
  52107. /**
  52108. * Update the shader of the material.
  52109. */
  52110. createOrUpdateMaterial: function () {
  52111. var data = this.data;
  52112. var hasChangedShader;
  52113. var material = this.material;
  52114. var NewShader;
  52115. var shaderData = this.shaderData;
  52116. var shaderName;
  52117. // Infer shader if using a stock font (or from `-msdf` filename convention).
  52118. shaderName = data.shader;
  52119. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  52120. shaderName = 'msdf';
  52121. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  52122. shaderName = 'sdf';
  52123. }
  52124. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  52125. shaderData.alphaTest = data.alphaTest;
  52126. shaderData.color = data.color;
  52127. shaderData.map = this.texture;
  52128. shaderData.opacity = data.opacity;
  52129. shaderData.side = parseSide(data.side);
  52130. shaderData.transparent = data.transparent;
  52131. shaderData.negate = data.negate;
  52132. // Shader has not changed, do an update.
  52133. if (!hasChangedShader) {
  52134. // Update shader material.
  52135. this.shaderObject.update(shaderData);
  52136. // Apparently, was not set on `init` nor `update`.
  52137. material.transparent = shaderData.transparent;
  52138. material.side = shaderData.side;
  52139. return;
  52140. }
  52141. // Shader has changed. Create a shader material.
  52142. NewShader = createShader(this.el, shaderName, shaderData);
  52143. this.material = NewShader.material;
  52144. this.shaderObject = NewShader.shader;
  52145. // Set new shader material.
  52146. this.material.side = shaderData.side;
  52147. if (this.mesh) { this.mesh.material = this.material; }
  52148. },
  52149. /**
  52150. * Load font for geometry, load font image for material, and apply.
  52151. */
  52152. updateFont: function () {
  52153. var data = this.data;
  52154. var el = this.el;
  52155. var fontSrc;
  52156. var geometry = this.geometry;
  52157. var self = this;
  52158. if (!data.font) { warn('No font specified. Using the default font.'); }
  52159. // Make invisible during font swap.
  52160. if (this.mesh) { this.mesh.visible = false; }
  52161. // Look up font URL to use, and perform cached load.
  52162. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  52163. cache.get(fontSrc, function doLoadFont () {
  52164. return loadFont(fontSrc, data.yOffset);
  52165. }).then(function setFont (font) {
  52166. var fontImgSrc;
  52167. if (font.pages.length !== 1) {
  52168. throw new Error('Currently only single-page bitmap fonts are supported.');
  52169. }
  52170. if (!fontWidthFactors[fontSrc]) {
  52171. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  52172. }
  52173. self.currentFont = font;
  52174. // Look up font image URL to use, and perform cached load.
  52175. fontImgSrc = self.getFontImageSrc();
  52176. cache.get(fontImgSrc, function () {
  52177. return loadTexture(fontImgSrc);
  52178. }).then(function (image) {
  52179. // Make mesh visible and apply font image as texture.
  52180. var texture = self.texture;
  52181. texture.image = image;
  52182. texture.needsUpdate = true;
  52183. textures[data.font] = texture;
  52184. self.texture = texture;
  52185. self.initMesh();
  52186. self.currentFont = font;
  52187. // Update geometry given font metrics.
  52188. self.updateGeometry(geometry, font);
  52189. self.updateLayout();
  52190. self.mesh.visible = true;
  52191. el.emit('textfontset', {font: data.font, fontObj: font});
  52192. }).catch(function (err) {
  52193. error(err.message);
  52194. error(err.stack);
  52195. });
  52196. }).catch(function (err) {
  52197. error(err.message);
  52198. error(err.stack);
  52199. });
  52200. },
  52201. initMesh: function () {
  52202. if (this.mesh) { return; }
  52203. this.mesh = new THREE.Mesh(this.geometry, this.material);
  52204. this.el.setObject3D(this.attrName, this.mesh);
  52205. },
  52206. getFontImageSrc: function () {
  52207. if (this.data.fontImage) { return this.data.fontImage; }
  52208. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  52209. var imageSrc = this.currentFont.pages[0];
  52210. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  52211. // path on disk and try to infer the path from the font source instead.
  52212. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  52213. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  52214. }
  52215. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  52216. },
  52217. /**
  52218. * Update layout with anchor, alignment, baseline, and considering any meshes.
  52219. */
  52220. updateLayout: function () {
  52221. var anchor;
  52222. var baseline;
  52223. var el = this.el;
  52224. var data = this.data;
  52225. var geometry = this.geometry;
  52226. var geometryComponent;
  52227. var height;
  52228. var layout;
  52229. var mesh = this.mesh;
  52230. var textRenderWidth;
  52231. var textScale;
  52232. var width;
  52233. var x;
  52234. var y;
  52235. if (!mesh || !geometry.layout) { return; }
  52236. // Determine width to use (defined width, geometry's width, or default width).
  52237. geometryComponent = el.getAttribute('geometry');
  52238. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  52239. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  52240. // Note that experimental factor will never be correct for variable width fonts.
  52241. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  52242. this.currentFont.widthFactor);
  52243. textScale = width / textRenderWidth;
  52244. // Determine height to use.
  52245. layout = geometry.layout;
  52246. height = textScale * (layout.height + layout.descender);
  52247. // Update geometry dimensions to match text layout if width and height are set to 0.
  52248. // For example, scales a plane to fit text.
  52249. if (geometryComponent && geometryComponent.primitive === 'plane') {
  52250. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  52251. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  52252. }
  52253. // Calculate X position to anchor text left, center, or right.
  52254. anchor = data.anchor === 'align' ? data.align : data.anchor;
  52255. if (anchor === 'left') {
  52256. x = 0;
  52257. } else if (anchor === 'right') {
  52258. x = -1 * layout.width;
  52259. } else if (anchor === 'center') {
  52260. x = -1 * layout.width / 2;
  52261. } else {
  52262. throw new TypeError('Invalid text.anchor property value', anchor);
  52263. }
  52264. // Calculate Y position to anchor text top, center, or bottom.
  52265. baseline = data.baseline;
  52266. if (baseline === 'bottom') {
  52267. y = 0;
  52268. } else if (baseline === 'top') {
  52269. y = -1 * layout.height + layout.ascender;
  52270. } else if (baseline === 'center') {
  52271. y = -1 * layout.height / 2;
  52272. } else {
  52273. throw new TypeError('Invalid text.baseline property value', baseline);
  52274. }
  52275. // Position and scale mesh to apply layout.
  52276. mesh.position.x = x * textScale + data.xOffset;
  52277. mesh.position.y = y * textScale;
  52278. // Place text slightly in front to avoid Z-fighting.
  52279. mesh.position.z = data.zOffset;
  52280. mesh.scale.set(textScale, -1 * textScale, textScale);
  52281. },
  52282. /**
  52283. * Grab font from the constant.
  52284. * Set as a method for test stubbing purposes.
  52285. */
  52286. lookupFont: function (key) {
  52287. return FONTS[key];
  52288. },
  52289. /**
  52290. * Update the text geometry using `three-bmfont-text.update`.
  52291. */
  52292. updateGeometry: (function () {
  52293. var geometryUpdateBase = {};
  52294. var geometryUpdateData = {};
  52295. var newLineRegex = /\\n/g;
  52296. var tabRegex = /\\t/g;
  52297. return function (geometry, font) {
  52298. var data = this.data;
  52299. geometryUpdateData.font = font;
  52300. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  52301. ? data.lineHeight
  52302. : font.common.lineHeight;
  52303. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  52304. .replace(tabRegex, '\t');
  52305. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  52306. font.widthFactor);
  52307. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  52308. };
  52309. })()
  52310. });
  52311. /**
  52312. * Due to using negative scale, we return the opposite side specified.
  52313. * https://github.com/mrdoob/three.js/pull/12787/
  52314. */
  52315. function parseSide (side) {
  52316. switch (side) {
  52317. case 'back': {
  52318. return THREE.FrontSide;
  52319. }
  52320. case 'double': {
  52321. return THREE.DoubleSide;
  52322. }
  52323. default: {
  52324. return THREE.BackSide;
  52325. }
  52326. }
  52327. }
  52328. /**
  52329. * @returns {Promise}
  52330. */
  52331. function loadFont (src, yOffset) {
  52332. return new Promise(function (resolve, reject) {
  52333. loadBMFont(src, function (err, font) {
  52334. if (err) {
  52335. error('Error loading font', src);
  52336. reject(err);
  52337. return;
  52338. }
  52339. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  52340. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  52341. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  52342. resolve(font);
  52343. });
  52344. });
  52345. }
  52346. /**
  52347. * @returns {Promise}
  52348. */
  52349. function loadTexture (src) {
  52350. return new Promise(function (resolve, reject) {
  52351. new THREE.ImageLoader().load(src, function (image) {
  52352. resolve(image);
  52353. }, undefined, function () {
  52354. error('Error loading font image', src);
  52355. reject(null);
  52356. });
  52357. });
  52358. }
  52359. function createShader (el, shaderName, data) {
  52360. var shader;
  52361. var shaderObject;
  52362. // Set up Shader.
  52363. shaderObject = new shaders[shaderName].Shader();
  52364. shaderObject.el = el;
  52365. shaderObject.init(data);
  52366. shaderObject.update(data);
  52367. // Get material.
  52368. shader = shaderObject.material;
  52369. // Apparently, was not set on `init` nor `update`.
  52370. shader.transparent = data.transparent;
  52371. return {
  52372. material: shader,
  52373. shader: shaderObject
  52374. };
  52375. }
  52376. /**
  52377. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  52378. * Note that experimental factor will never be correct for variable width fonts.
  52379. */
  52380. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  52381. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  52382. }
  52383. /**
  52384. * Compute default font width factor to use.
  52385. */
  52386. function computeFontWidthFactor (font) {
  52387. var sum = 0;
  52388. var digitsum = 0;
  52389. var digits = 0;
  52390. font.chars.map(function (ch) {
  52391. sum += ch.xadvance;
  52392. if (ch.id >= 48 && ch.id <= 57) {
  52393. digits++;
  52394. digitsum += ch.xadvance;
  52395. }
  52396. });
  52397. return digits ? digitsum / digits : sum / font.chars.length;
  52398. }
  52399. /**
  52400. * Get or create a promise given a key and promise generator.
  52401. * @todo Move to a utility and use in other parts of A-Frame.
  52402. */
  52403. function PromiseCache () {
  52404. var cache = this.cache = {};
  52405. this.get = function (key, promiseGenerator) {
  52406. if (key in cache) {
  52407. return cache[key];
  52408. }
  52409. cache[key] = promiseGenerator();
  52410. return cache[key];
  52411. };
  52412. }
  52413. },{"../core/component":132,"../core/shader":142,"../lib/three":180,"../utils/":206,"load-bmfont":37,"three-bmfont-text":63}],115:[function(_dereq_,module,exports){
  52414. var registerComponent = _dereq_('../core/component').registerComponent;
  52415. var controllerUtils = _dereq_('../utils/tracked-controls');
  52416. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  52417. var THREE = _dereq_('../lib/three');
  52418. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  52419. // Vector from eyes to elbow (divided by user height).
  52420. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  52421. // Vector from eyes to elbow (divided by user height).
  52422. var FOREARM = {x: 0, y: 0, z: -0.175};
  52423. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  52424. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  52425. var EVENTS = {
  52426. AXISMOVE: 'axismove',
  52427. BUTTONCHANGED: 'buttonchanged',
  52428. BUTTONDOWN: 'buttondown',
  52429. BUTTONUP: 'buttonup',
  52430. TOUCHSTART: 'touchstart',
  52431. TOUCHEND: 'touchend'
  52432. };
  52433. /**
  52434. * Tracked controls component.
  52435. * Wrap the gamepad API for pose and button states.
  52436. * Select the appropriate controller and apply pose to the entity.
  52437. * Observe button states and emit appropriate events.
  52438. *
  52439. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52440. * Only used if hand property is not set.
  52441. * @property {string} id - Selected controller among those returned by Gamepad API.
  52442. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52443. * given value for hand. If set, we ignore 'controller' property
  52444. */
  52445. module.exports.Component = registerComponent('tracked-controls-webvr', {
  52446. schema: {
  52447. autoHide: {default: true},
  52448. controller: {default: 0},
  52449. id: {type: 'string', default: ''},
  52450. hand: {type: 'string', default: ''},
  52451. idPrefix: {type: 'string', default: ''},
  52452. orientationOffset: {type: 'vec3'},
  52453. // Arm model parameters when not 6DoF.
  52454. armModel: {default: false},
  52455. headElement: {type: 'selector'}
  52456. },
  52457. init: function () {
  52458. // Copy variables back to tracked-controls for backwards compatibility.
  52459. // Some 3rd components rely on them.
  52460. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52461. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52462. this.changedAxes = [];
  52463. this.targetControllerNumber = this.data.controller;
  52464. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52465. this.deltaControllerPosition = new THREE.Vector3();
  52466. this.controllerQuaternion = new THREE.Quaternion();
  52467. this.controllerEuler = new THREE.Euler();
  52468. this.updateGamepad();
  52469. this.buttonEventDetails = {};
  52470. },
  52471. tick: function (time, delta) {
  52472. var mesh = this.el.getObject3D('mesh');
  52473. // Update mesh animations.
  52474. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  52475. this.updateGamepad();
  52476. this.updatePose();
  52477. this.updateButtons();
  52478. },
  52479. /**
  52480. * Return default user height to use for non-6DOF arm model.
  52481. */
  52482. defaultUserHeight: function () {
  52483. return DEFAULT_CAMERA_HEIGHT;
  52484. },
  52485. /**
  52486. * Return head element to use for non-6DOF arm model.
  52487. */
  52488. getHeadElement: function () {
  52489. return this.data.headElement || this.el.sceneEl.camera.el;
  52490. },
  52491. /**
  52492. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52493. */
  52494. updateGamepad: function () {
  52495. var data = this.data;
  52496. var controller = controllerUtils.findMatchingControllerWebVR(
  52497. this.system.controllers,
  52498. data.id,
  52499. data.idPrefix,
  52500. data.hand,
  52501. data.controller
  52502. );
  52503. this.controller = controller;
  52504. // Legacy handle to the controller for old components.
  52505. this.el.components['tracked-controls'].controller = controller;
  52506. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52507. },
  52508. /**
  52509. * Applies an artificial arm model to simulate elbow to wrist positioning
  52510. * based on the orientation of the controller.
  52511. *
  52512. * @param {object} controllerPosition - Existing vector to update with controller position.
  52513. */
  52514. applyArmModel: function (controllerPosition) {
  52515. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  52516. var controller = this.controller;
  52517. var controllerEuler = this.controllerEuler;
  52518. var controllerQuaternion = this.controllerQuaternion;
  52519. var deltaControllerPosition = this.deltaControllerPosition;
  52520. var hand;
  52521. var headEl;
  52522. var headObject3D;
  52523. var pose;
  52524. var userHeight;
  52525. headEl = this.getHeadElement();
  52526. headObject3D = headEl.object3D;
  52527. userHeight = this.defaultUserHeight();
  52528. pose = controller.pose;
  52529. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  52530. // Use camera position as head position.
  52531. controllerPosition.copy(headObject3D.position);
  52532. // Set offset for degenerate "arm model" to elbow.
  52533. deltaControllerPosition.set(
  52534. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  52535. EYES_TO_ELBOW.y, // Lower than our eyes.
  52536. EYES_TO_ELBOW.z); // Slightly out in front.
  52537. // Scale offset by user height.
  52538. deltaControllerPosition.multiplyScalar(userHeight);
  52539. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  52540. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  52541. // Apply rotated offset to position.
  52542. controllerPosition.add(deltaControllerPosition);
  52543. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  52544. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  52545. // Scale offset by user height.
  52546. deltaControllerPosition.multiplyScalar(userHeight);
  52547. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  52548. if (pose.orientation) {
  52549. controllerQuaternion.fromArray(pose.orientation);
  52550. } else {
  52551. controllerQuaternion.copy(headObject3D.quaternion);
  52552. }
  52553. controllerEuler.setFromQuaternion(controllerQuaternion);
  52554. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  52555. deltaControllerPosition.applyEuler(controllerEuler);
  52556. // Apply rotated offset to position.
  52557. controllerPosition.add(deltaControllerPosition);
  52558. },
  52559. /**
  52560. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  52561. */
  52562. updatePose: function () {
  52563. var controller = this.controller;
  52564. var data = this.data;
  52565. var object3D = this.el.object3D;
  52566. var pose;
  52567. var vrDisplay = this.system.vrDisplay;
  52568. var standingMatrix;
  52569. if (!controller) { return; }
  52570. // Compose pose from Gamepad.
  52571. pose = controller.pose;
  52572. if (pose.position) {
  52573. object3D.position.fromArray(pose.position);
  52574. } else {
  52575. // Controller not 6DOF, apply arm model.
  52576. if (data.armModel) { this.applyArmModel(object3D.position); }
  52577. }
  52578. if (pose.orientation) {
  52579. object3D.quaternion.fromArray(pose.orientation);
  52580. }
  52581. // Apply transforms, if 6DOF and in VR.
  52582. if (vrDisplay && pose.position) {
  52583. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  52584. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  52585. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  52586. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  52587. }
  52588. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  52589. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  52590. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  52591. },
  52592. /**
  52593. * Handle button changes including axes, presses, touches, values.
  52594. */
  52595. updateButtons: function () {
  52596. var buttonState;
  52597. var controller = this.controller;
  52598. var id;
  52599. if (!controller) { return; }
  52600. // Check every button.
  52601. for (id = 0; id < controller.buttons.length; ++id) {
  52602. // Initialize button state.
  52603. if (!this.buttonStates[id]) {
  52604. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52605. }
  52606. if (!this.buttonEventDetails[id]) {
  52607. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52608. }
  52609. buttonState = controller.buttons[id];
  52610. this.handleButton(id, buttonState);
  52611. }
  52612. // Check axes.
  52613. this.handleAxes();
  52614. },
  52615. /**
  52616. * Handle presses and touches for a single button.
  52617. *
  52618. * @param {number} id - Index of button in Gamepad button array.
  52619. * @param {number} buttonState - Value of button state from 0 to 1.
  52620. * @returns {boolean} Whether button has changed in any way.
  52621. */
  52622. handleButton: function (id, buttonState) {
  52623. var changed;
  52624. changed = this.handlePress(id, buttonState) |
  52625. this.handleTouch(id, buttonState) |
  52626. this.handleValue(id, buttonState);
  52627. if (!changed) { return false; }
  52628. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52629. return true;
  52630. },
  52631. /**
  52632. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52633. * Compare each component of the axis to the previous value to determine change.
  52634. *
  52635. * @returns {boolean} Whether axes changed.
  52636. */
  52637. handleAxes: function () {
  52638. var changed = false;
  52639. var controllerAxes = this.controller.axes;
  52640. var i;
  52641. var previousAxis = this.axis;
  52642. var changedAxes = this.changedAxes;
  52643. // Check if axis changed.
  52644. this.changedAxes.splice(0, this.changedAxes.length);
  52645. for (i = 0; i < controllerAxes.length; ++i) {
  52646. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52647. if (changedAxes[i]) { changed = true; }
  52648. }
  52649. if (!changed) { return false; }
  52650. this.axis.splice(0, this.axis.length);
  52651. for (i = 0; i < controllerAxes.length; i++) {
  52652. this.axis.push(controllerAxes[i]);
  52653. }
  52654. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52655. return true;
  52656. },
  52657. /**
  52658. * Determine whether a button press has occured and emit events as appropriate.
  52659. *
  52660. * @param {string} id - ID of the button to check.
  52661. * @param {object} buttonState - State of the button to check.
  52662. * @returns {boolean} Whether button press state changed.
  52663. */
  52664. handlePress: function (id, buttonState) {
  52665. var evtName;
  52666. var previousButtonState = this.buttonStates[id];
  52667. // Not changed.
  52668. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52669. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52670. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52671. previousButtonState.pressed = buttonState.pressed;
  52672. return true;
  52673. },
  52674. /**
  52675. * Determine whether a button touch has occured and emit events as appropriate.
  52676. *
  52677. * @param {string} id - ID of the button to check.
  52678. * @param {object} buttonState - State of the button to check.
  52679. * @returns {boolean} Whether button touch state changed.
  52680. */
  52681. handleTouch: function (id, buttonState) {
  52682. var evtName;
  52683. var previousButtonState = this.buttonStates[id];
  52684. // Not changed.
  52685. if (buttonState.touched === previousButtonState.touched) { return false; }
  52686. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52687. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  52688. previousButtonState.touched = buttonState.touched;
  52689. return true;
  52690. },
  52691. /**
  52692. * Determine whether a button value has changed.
  52693. *
  52694. * @param {string} id - Id of the button to check.
  52695. * @param {object} buttonState - State of the button to check.
  52696. * @returns {boolean} Whether button value changed.
  52697. */
  52698. handleValue: function (id, buttonState) {
  52699. var previousButtonState = this.buttonStates[id];
  52700. // Not changed.
  52701. if (buttonState.value === previousButtonState.value) { return false; }
  52702. previousButtonState.value = buttonState.value;
  52703. return true;
  52704. }
  52705. });
  52706. },{"../constants":124,"../core/component":132,"../lib/three":180,"../utils/tracked-controls":215}],116:[function(_dereq_,module,exports){
  52707. var controllerUtils = _dereq_('../utils/tracked-controls');
  52708. var registerComponent = _dereq_('../core/component').registerComponent;
  52709. var EVENTS = {
  52710. AXISMOVE: 'axismove',
  52711. BUTTONCHANGED: 'buttonchanged',
  52712. BUTTONDOWN: 'buttondown',
  52713. BUTTONUP: 'buttonup',
  52714. TOUCHSTART: 'touchstart',
  52715. TOUCHEND: 'touchend'
  52716. };
  52717. module.exports.Component = registerComponent('tracked-controls-webxr', {
  52718. schema: {
  52719. id: {type: 'string', default: ''},
  52720. hand: {type: 'string', default: ''},
  52721. handTrackingEnabled: {default: false},
  52722. index: {type: 'int', default: -1},
  52723. iterateControllerProfiles: {default: false}
  52724. },
  52725. init: function () {
  52726. this.updateController = this.updateController.bind(this);
  52727. this.buttonEventDetails = {};
  52728. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52729. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52730. this.changedAxes = [];
  52731. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52732. },
  52733. update: function () {
  52734. this.updateController();
  52735. },
  52736. play: function () {
  52737. var sceneEl = this.el.sceneEl;
  52738. this.updateController();
  52739. sceneEl.addEventListener('controllersupdated', this.updateController);
  52740. },
  52741. pause: function () {
  52742. var sceneEl = this.el.sceneEl;
  52743. sceneEl.removeEventListener('controllersupdated', this.updateController);
  52744. },
  52745. isControllerPresent: function (evt) {
  52746. if (!this.controller || this.controller.gamepad) { return false; }
  52747. if (evt.inputSource.handedness !== 'none' &&
  52748. evt.inputSource.handedness !== this.data.hand) {
  52749. return false;
  52750. }
  52751. return true;
  52752. },
  52753. /**
  52754. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52755. */
  52756. updateController: function () {
  52757. this.controller = controllerUtils.findMatchingControllerWebXR(
  52758. this.system.controllers,
  52759. this.data.id,
  52760. this.data.hand,
  52761. this.data.index,
  52762. this.data.iterateControllerProfiles,
  52763. this.data.handTrackingEnabled
  52764. );
  52765. // Legacy handle to the controller for old components.
  52766. this.el.components['tracked-controls'].controller = this.controller;
  52767. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52768. },
  52769. tick: function () {
  52770. var sceneEl = this.el.sceneEl;
  52771. var controller = this.controller;
  52772. var frame = sceneEl.frame;
  52773. if (!controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  52774. if (!controller.hand) {
  52775. this.pose = frame.getPose(controller.targetRaySpace, this.system.referenceSpace);
  52776. this.updatePose();
  52777. this.updateButtons();
  52778. }
  52779. },
  52780. updatePose: function () {
  52781. var object3D = this.el.object3D;
  52782. var pose = this.pose;
  52783. if (!pose) { return; }
  52784. object3D.matrix.elements = pose.transform.matrix;
  52785. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  52786. },
  52787. /**
  52788. * Handle button changes including axes, presses, touches, values.
  52789. */
  52790. updateButtons: function () {
  52791. var buttonState;
  52792. var id;
  52793. var controller = this.controller;
  52794. var gamepad;
  52795. if (!controller || !controller.gamepad) { return; }
  52796. gamepad = controller.gamepad;
  52797. // Check every button.
  52798. for (id = 0; id < gamepad.buttons.length; ++id) {
  52799. // Initialize button state.
  52800. if (!this.buttonStates[id]) {
  52801. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52802. }
  52803. if (!this.buttonEventDetails[id]) {
  52804. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52805. }
  52806. buttonState = gamepad.buttons[id];
  52807. this.handleButton(id, buttonState);
  52808. }
  52809. // Check axes.
  52810. this.handleAxes();
  52811. },
  52812. /**
  52813. * Handle presses and touches for a single button.
  52814. *
  52815. * @param {number} id - Index of button in Gamepad button array.
  52816. * @param {number} buttonState - Value of button state from 0 to 1.
  52817. * @returns {boolean} Whether button has changed in any way.
  52818. */
  52819. handleButton: function (id, buttonState) {
  52820. var changed;
  52821. changed = this.handlePress(id, buttonState) |
  52822. this.handleTouch(id, buttonState) |
  52823. this.handleValue(id, buttonState);
  52824. if (!changed) { return false; }
  52825. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52826. return true;
  52827. },
  52828. /**
  52829. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52830. * Compare each component of the axis to the previous value to determine change.
  52831. *
  52832. * @returns {boolean} Whether axes changed.
  52833. */
  52834. handleAxes: function () {
  52835. var changed = false;
  52836. var controllerAxes = this.controller.gamepad.axes;
  52837. var i;
  52838. var previousAxis = this.axis;
  52839. var changedAxes = this.changedAxes;
  52840. // Check if axis changed.
  52841. this.changedAxes.splice(0, this.changedAxes.length);
  52842. for (i = 0; i < controllerAxes.length; ++i) {
  52843. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52844. if (changedAxes[i]) { changed = true; }
  52845. }
  52846. if (!changed) { return false; }
  52847. this.axis.splice(0, this.axis.length);
  52848. for (i = 0; i < controllerAxes.length; i++) {
  52849. this.axis.push(controllerAxes[i]);
  52850. }
  52851. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52852. return true;
  52853. },
  52854. /**
  52855. * Determine whether a button press has occured and emit events as appropriate.
  52856. *
  52857. * @param {string} id - ID of the button to check.
  52858. * @param {object} buttonState - State of the button to check.
  52859. * @returns {boolean} Whether button press state changed.
  52860. */
  52861. handlePress: function (id, buttonState) {
  52862. var evtName;
  52863. var previousButtonState = this.buttonStates[id];
  52864. // Not changed.
  52865. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52866. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52867. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52868. previousButtonState.pressed = buttonState.pressed;
  52869. return true;
  52870. },
  52871. /**
  52872. * Determine whether a button touch has occured and emit events as appropriate.
  52873. *
  52874. * @param {string} id - ID of the button to check.
  52875. * @param {object} buttonState - State of the button to check.
  52876. * @returns {boolean} Whether button touch state changed.
  52877. */
  52878. handleTouch: function (id, buttonState) {
  52879. var evtName;
  52880. var previousButtonState = this.buttonStates[id];
  52881. // Not changed.
  52882. if (buttonState.touched === previousButtonState.touched) { return false; }
  52883. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52884. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52885. previousButtonState.touched = buttonState.touched;
  52886. return true;
  52887. },
  52888. /**
  52889. * Determine whether a button value has changed.
  52890. *
  52891. * @param {string} id - Id of the button to check.
  52892. * @param {object} buttonState - State of the button to check.
  52893. * @returns {boolean} Whether button value changed.
  52894. */
  52895. handleValue: function (id, buttonState) {
  52896. var previousButtonState = this.buttonStates[id];
  52897. // Not changed.
  52898. if (buttonState.value === previousButtonState.value) { return false; }
  52899. previousButtonState.value = buttonState.value;
  52900. return true;
  52901. }
  52902. });
  52903. },{"../core/component":132,"../utils/tracked-controls":215}],117:[function(_dereq_,module,exports){
  52904. var registerComponent = _dereq_('../core/component').registerComponent;
  52905. /**
  52906. * Tracked controls.
  52907. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  52908. *
  52909. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52910. * Only used if hand property is not set.
  52911. * @property {string} id - Selected controller among those returned by Gamepad API.
  52912. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52913. * given value for hand. If set, we ignore 'controller' property
  52914. */
  52915. module.exports.Component = registerComponent('tracked-controls', {
  52916. schema: {
  52917. autoHide: {default: true},
  52918. controller: {default: -1},
  52919. id: {type: 'string', default: ''},
  52920. hand: {type: 'string', default: ''},
  52921. idPrefix: {type: 'string', default: ''},
  52922. handTrackingEnabled: {default: false},
  52923. orientationOffset: {type: 'vec3'},
  52924. // Arm model parameters when not 6DoF.
  52925. armModel: {default: false},
  52926. headElement: {type: 'selector'},
  52927. iterateControllerProfiles: {default: false}
  52928. },
  52929. update: function () {
  52930. var data = this.data;
  52931. var el = this.el;
  52932. if (el.sceneEl.hasWebXR) {
  52933. el.setAttribute('tracked-controls-webxr', {
  52934. id: data.id,
  52935. hand: data.hand,
  52936. index: data.controller,
  52937. iterateControllerProfiles: data.iterateControllerProfiles,
  52938. handTrackingEnabled: data.handTrackingEnabled
  52939. });
  52940. } else {
  52941. el.setAttribute('tracked-controls-webvr', data);
  52942. }
  52943. }
  52944. });
  52945. },{"../core/component":132}],118:[function(_dereq_,module,exports){
  52946. var registerComponent = _dereq_('../core/component').registerComponent;
  52947. var bind = _dereq_('../utils/bind');
  52948. var THREE = _dereq_('../lib/three');
  52949. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  52950. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52951. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52952. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52953. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve-index-';
  52954. var INDEX_CONTROLLER_MODEL_URL = {
  52955. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.glb',
  52956. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.glb'
  52957. };
  52958. var GAMEPAD_ID_PREFIX = 'valve';
  52959. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  52960. var INDEX_CONTROLLER_POSITION_OFFSET_WEBVR = {
  52961. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  52962. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  52963. };
  52964. var INDEX_CONTROLLER_POSITION_OFFSET_WEBXR = {
  52965. left: {x: 0, y: -0.05, z: 0.06},
  52966. right: {x: 0, y: -0.05, z: 0.06}
  52967. };
  52968. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR = {
  52969. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  52970. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  52971. };
  52972. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR = {
  52973. left: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'},
  52974. right: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'}
  52975. };
  52976. var INDEX_CONTROLLER_ROTATION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR : INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR;
  52977. var INDEX_CONTROLLER_POSITION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_POSITION_OFFSET_WEBXR : INDEX_CONTROLLER_POSITION_OFFSET_WEBVR;
  52978. /**
  52979. * Vive controls.
  52980. * Interface with Vive controllers and map Gamepad events to controller buttons:
  52981. * trackpad, trigger, grip, menu, system
  52982. * Load a controller model and highlight the pressed buttons.
  52983. */
  52984. module.exports.Component = registerComponent('valve-index-controls', {
  52985. schema: {
  52986. hand: {default: 'left'},
  52987. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  52988. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  52989. model: {default: true},
  52990. orientationOffset: {type: 'vec3'}
  52991. },
  52992. mapping: {
  52993. axes: {
  52994. trackpad: [0, 1],
  52995. thumbstick: [2, 3]
  52996. },
  52997. buttons: ['trigger', 'grip', 'trackpad', 'thumbstick', 'abutton']
  52998. },
  52999. init: function () {
  53000. var self = this;
  53001. this.controllerPresent = false;
  53002. this.lastControllerCheck = 0;
  53003. this.onButtonChanged = bind(this.onButtonChanged, this);
  53004. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53005. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53006. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53007. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53008. this.previousButtonValues = {};
  53009. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53010. this.bindMethods();
  53011. },
  53012. play: function () {
  53013. this.checkIfControllerPresent();
  53014. this.addControllersUpdateListener();
  53015. },
  53016. pause: function () {
  53017. this.removeEventListeners();
  53018. this.removeControllersUpdateListener();
  53019. },
  53020. bindMethods: function () {
  53021. this.onModelLoaded = bind(this.onModelLoaded, this);
  53022. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53023. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53024. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53025. this.onAxisMoved = bind(this.onAxisMoved, this);
  53026. },
  53027. addEventListeners: function () {
  53028. var el = this.el;
  53029. el.addEventListener('buttonchanged', this.onButtonChanged);
  53030. el.addEventListener('buttondown', this.onButtonDown);
  53031. el.addEventListener('buttonup', this.onButtonUp);
  53032. el.addEventListener('touchend', this.onButtonTouchEnd);
  53033. el.addEventListener('touchstart', this.onButtonTouchStart);
  53034. el.addEventListener('model-loaded', this.onModelLoaded);
  53035. el.addEventListener('axismove', this.onAxisMoved);
  53036. this.controllerEventsActive = true;
  53037. },
  53038. removeEventListeners: function () {
  53039. var el = this.el;
  53040. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53041. el.removeEventListener('buttondown', this.onButtonDown);
  53042. el.removeEventListener('buttonup', this.onButtonUp);
  53043. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53044. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53045. el.removeEventListener('model-loaded', this.onModelLoaded);
  53046. el.removeEventListener('axismove', this.onAxisMoved);
  53047. this.controllerEventsActive = false;
  53048. },
  53049. /**
  53050. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  53051. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  53052. { hand: data.hand });
  53053. * Until then, use hardcoded index.
  53054. */
  53055. checkIfControllerPresent: function () {
  53056. var data = this.data;
  53057. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  53058. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  53059. },
  53060. injectTrackedControls: function () {
  53061. var el = this.el;
  53062. var data = this.data;
  53063. // If we have an OpenVR Gamepad, use the fixed mapping.
  53064. el.setAttribute('tracked-controls', {
  53065. idPrefix: GAMEPAD_ID_PREFIX,
  53066. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  53067. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  53068. hand: data.hand,
  53069. orientationOffset: data.orientationOffset
  53070. });
  53071. this.loadModel();
  53072. },
  53073. loadModel: function () {
  53074. var data = this.data;
  53075. if (!data.model) { return; }
  53076. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  53077. },
  53078. addControllersUpdateListener: function () {
  53079. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53080. },
  53081. removeControllersUpdateListener: function () {
  53082. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53083. },
  53084. onControllersUpdate: function () {
  53085. this.checkIfControllerPresent();
  53086. },
  53087. /**
  53088. * Rotate the trigger button based on how hard the trigger is pressed.
  53089. */
  53090. onButtonChanged: function (evt) {
  53091. var button = this.mapping.buttons[evt.detail.id];
  53092. var buttonMeshes = this.buttonMeshes;
  53093. var analogValue;
  53094. if (!button) { return; }
  53095. if (button === 'trigger') {
  53096. analogValue = evt.detail.state.value;
  53097. // Update trigger rotation depending on button value.
  53098. if (buttonMeshes && buttonMeshes.trigger) {
  53099. buttonMeshes.trigger.rotation.x = this.triggerOriginalRotationX - analogValue * (Math.PI / 40);
  53100. }
  53101. }
  53102. // Pass along changed event with button state, using button mapping for convenience.
  53103. this.el.emit(button + 'changed', evt.detail.state);
  53104. },
  53105. onModelLoaded: function (evt) {
  53106. var buttonMeshes;
  53107. var controllerObject3D = evt.detail.model;
  53108. var self = this;
  53109. if (!this.data.model) { return; }
  53110. // Store button meshes object to be able to change their colors.
  53111. buttonMeshes = this.buttonMeshes = {};
  53112. buttonMeshes.grip = {
  53113. left: controllerObject3D.getObjectByName('leftgrip'),
  53114. right: controllerObject3D.getObjectByName('rightgrip')
  53115. };
  53116. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  53117. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  53118. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  53119. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  53120. this.triggerOriginalRotationX = buttonMeshes.trigger.rotation.x;
  53121. // Set default colors.
  53122. Object.keys(buttonMeshes).forEach(function (buttonName) {
  53123. self.setButtonColor(buttonName, self.data.buttonColor);
  53124. });
  53125. // Offset pivot point.
  53126. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  53127. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  53128. this.el.emit('controllermodelready', {
  53129. name: 'valve-index-controlls',
  53130. model: this.data.model,
  53131. rayOrigin: new THREE.Vector3(0, 0, 0)
  53132. });
  53133. },
  53134. onAxisMoved: function (evt) {
  53135. emitIfAxesChanged(this, this.mapping.axes, evt);
  53136. },
  53137. updateModel: function (buttonName, evtName) {
  53138. var color;
  53139. var isTouch;
  53140. if (!this.data.model) { return; }
  53141. isTouch = evtName.indexOf('touch') !== -1;
  53142. // Don't change color for trackpad touch.
  53143. if (isTouch) { return; }
  53144. // Update colors.
  53145. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  53146. this.setButtonColor(buttonName, color);
  53147. },
  53148. setButtonColor: function (buttonName, color) {
  53149. // TODO: The meshes aren't set up correctly now, skipping for the moment
  53150. return;
  53151. }
  53152. });
  53153. },{"../core/component":132,"../lib/three":180,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],119:[function(_dereq_,module,exports){
  53154. var registerComponent = _dereq_('../core/component').registerComponent;
  53155. /**
  53156. * Visibility component.
  53157. */
  53158. module.exports.Component = registerComponent('visible', {
  53159. schema: {default: true},
  53160. update: function () {
  53161. this.el.object3D.visible = this.data;
  53162. }
  53163. });
  53164. },{"../core/component":132}],120:[function(_dereq_,module,exports){
  53165. var registerComponent = _dereq_('../core/component').registerComponent;
  53166. var bind = _dereq_('../utils/bind');
  53167. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53168. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53169. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53170. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53171. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  53172. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  53173. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53174. var GAMEPAD_ID_WEBXR = 'htc-vive';
  53175. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  53176. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  53177. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53178. /**
  53179. * Button IDs:
  53180. * 0 - trackpad
  53181. * 1 - trigger (intensity value from 0.5 to 1)
  53182. * 2 - grip
  53183. * 3 - menu (dispatch but better for menu options)
  53184. * 4 - system (never dispatched on this layer)
  53185. */
  53186. var INPUT_MAPPING_WEBVR = {
  53187. axes: {trackpad: [0, 1]},
  53188. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  53189. };
  53190. /**
  53191. * Button IDs:
  53192. * 0 - trigger
  53193. * 1 - squeeze
  53194. * 2 - touchpad
  53195. * 3 - none (dispatch but better for menu options)
  53196. * 4 - menu (never dispatched on this layer)
  53197. *
  53198. * Axis:
  53199. * 0 - touchpad x axis
  53200. * 1 - touchpad y axis
  53201. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  53202. */
  53203. var INPUT_MAPPING_WEBXR = {
  53204. axes: {thumbstick: [0, 1]},
  53205. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  53206. };
  53207. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53208. /**
  53209. * Vive controls.
  53210. * Interface with Vive controllers and map Gamepad events to controller buttons:
  53211. * trackpad, trigger, grip, menu, system
  53212. * Load a controller model and highlight the pressed buttons.
  53213. */
  53214. module.exports.Component = registerComponent('vive-controls', {
  53215. schema: {
  53216. hand: {default: 'left'},
  53217. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  53218. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  53219. model: {default: true},
  53220. orientationOffset: {type: 'vec3'}
  53221. },
  53222. mapping: INPUT_MAPPING,
  53223. init: function () {
  53224. var self = this;
  53225. this.controllerPresent = false;
  53226. this.lastControllerCheck = 0;
  53227. this.onButtonChanged = bind(this.onButtonChanged, this);
  53228. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53229. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53230. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53231. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53232. this.previousButtonValues = {};
  53233. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53234. this.bindMethods();
  53235. },
  53236. update: function () {
  53237. var data = this.data;
  53238. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  53239. },
  53240. play: function () {
  53241. this.checkIfControllerPresent();
  53242. this.addControllersUpdateListener();
  53243. },
  53244. pause: function () {
  53245. this.removeEventListeners();
  53246. this.removeControllersUpdateListener();
  53247. },
  53248. bindMethods: function () {
  53249. this.onModelLoaded = bind(this.onModelLoaded, this);
  53250. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53251. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53252. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53253. this.onAxisMoved = bind(this.onAxisMoved, this);
  53254. },
  53255. addEventListeners: function () {
  53256. var el = this.el;
  53257. el.addEventListener('buttonchanged', this.onButtonChanged);
  53258. el.addEventListener('buttondown', this.onButtonDown);
  53259. el.addEventListener('buttonup', this.onButtonUp);
  53260. el.addEventListener('touchend', this.onButtonTouchEnd);
  53261. el.addEventListener('touchstart', this.onButtonTouchStart);
  53262. el.addEventListener('model-loaded', this.onModelLoaded);
  53263. el.addEventListener('axismove', this.onAxisMoved);
  53264. this.controllerEventsActive = true;
  53265. },
  53266. removeEventListeners: function () {
  53267. var el = this.el;
  53268. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53269. el.removeEventListener('buttondown', this.onButtonDown);
  53270. el.removeEventListener('buttonup', this.onButtonUp);
  53271. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53272. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53273. el.removeEventListener('model-loaded', this.onModelLoaded);
  53274. el.removeEventListener('axismove', this.onAxisMoved);
  53275. this.controllerEventsActive = false;
  53276. },
  53277. /**
  53278. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  53279. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  53280. { hand: data.hand });
  53281. * Until then, use hardcoded index.
  53282. */
  53283. checkIfControllerPresent: function () {
  53284. var data = this.data;
  53285. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  53286. },
  53287. injectTrackedControls: function () {
  53288. var el = this.el;
  53289. var data = this.data;
  53290. // If we have an OpenVR Gamepad, use the fixed mapping.
  53291. el.setAttribute('tracked-controls', {
  53292. idPrefix: GAMEPAD_ID_PREFIX,
  53293. hand: data.hand,
  53294. controller: this.controllerIndex,
  53295. orientationOffset: data.orientationOffset
  53296. });
  53297. // Load model.
  53298. if (!this.data.model) { return; }
  53299. this.el.setAttribute('obj-model', {
  53300. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  53301. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  53302. });
  53303. },
  53304. addControllersUpdateListener: function () {
  53305. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53306. },
  53307. removeControllersUpdateListener: function () {
  53308. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53309. },
  53310. onControllersUpdate: function () {
  53311. this.checkIfControllerPresent();
  53312. },
  53313. /**
  53314. * Rotate the trigger button based on how hard the trigger is pressed.
  53315. */
  53316. onButtonChanged: function (evt) {
  53317. var button = this.mapping.buttons[evt.detail.id];
  53318. var buttonMeshes = this.buttonMeshes;
  53319. var analogValue;
  53320. if (!button) { return; }
  53321. if (button === 'trigger') {
  53322. analogValue = evt.detail.state.value;
  53323. // Update trigger rotation depending on button value.
  53324. if (buttonMeshes && buttonMeshes.trigger) {
  53325. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  53326. }
  53327. }
  53328. // Pass along changed event with button state, using button mapping for convenience.
  53329. this.el.emit(button + 'changed', evt.detail.state);
  53330. },
  53331. onModelLoaded: function (evt) {
  53332. var buttonMeshes;
  53333. var controllerObject3D = evt.detail.model;
  53334. var self = this;
  53335. if (!this.data.model) { return; }
  53336. // Store button meshes object to be able to change their colors.
  53337. buttonMeshes = this.buttonMeshes = {};
  53338. buttonMeshes.grip = {
  53339. left: controllerObject3D.getObjectByName('leftgrip'),
  53340. right: controllerObject3D.getObjectByName('rightgrip')
  53341. };
  53342. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  53343. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  53344. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  53345. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  53346. // Set default colors.
  53347. Object.keys(buttonMeshes).forEach(function (buttonName) {
  53348. self.setButtonColor(buttonName, self.data.buttonColor);
  53349. });
  53350. // Offset pivot point.
  53351. controllerObject3D.position.set(0, -0.015, 0.04);
  53352. },
  53353. onAxisMoved: function (evt) {
  53354. emitIfAxesChanged(this, this.mapping.axes, evt);
  53355. },
  53356. updateModel: function (buttonName, evtName) {
  53357. var color;
  53358. var isTouch;
  53359. if (!this.data.model) { return; }
  53360. isTouch = evtName.indexOf('touch') !== -1;
  53361. // Don't change color for trackpad touch.
  53362. if (isTouch) { return; }
  53363. // Update colors.
  53364. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  53365. this.setButtonColor(buttonName, color);
  53366. },
  53367. setButtonColor: function (buttonName, color) {
  53368. var buttonMeshes = this.buttonMeshes;
  53369. var rendererSystem = this.rendererSystem;
  53370. if (!buttonMeshes) { return; }
  53371. // Need to do both left and right sides for grip.
  53372. if (buttonName === 'grip') {
  53373. buttonMeshes.grip.left.material.color.set(color);
  53374. buttonMeshes.grip.right.material.color.set(color);
  53375. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  53376. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  53377. return;
  53378. }
  53379. buttonMeshes[buttonName].material.color.set(color);
  53380. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  53381. }
  53382. });
  53383. },{"../core/component":132,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],121:[function(_dereq_,module,exports){
  53384. var registerComponent = _dereq_('../core/component').registerComponent;
  53385. var bind = _dereq_('../utils/bind');
  53386. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53387. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53388. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53389. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53390. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  53391. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  53392. /**
  53393. * Vive Focus controls.
  53394. * Interface with Vive Focus controller and map Gamepad events to
  53395. * controller buttons: trackpad, trigger
  53396. * Load a controller model and highlight the pressed buttons.
  53397. */
  53398. module.exports.Component = registerComponent('vive-focus-controls', {
  53399. schema: {
  53400. hand: {default: ''}, // This informs the degenerate arm model.
  53401. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  53402. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  53403. model: {default: true},
  53404. orientationOffset: {type: 'vec3'},
  53405. armModel: {default: true}
  53406. },
  53407. /**
  53408. * Button IDs:
  53409. * 0 - trackpad
  53410. * 1 - trigger
  53411. */
  53412. mapping: {
  53413. axes: {trackpad: [0, 1]},
  53414. buttons: ['trackpad', 'trigger']
  53415. },
  53416. bindMethods: function () {
  53417. this.onModelLoaded = bind(this.onModelLoaded, this);
  53418. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53419. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53420. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53421. this.onAxisMoved = bind(this.onAxisMoved, this);
  53422. },
  53423. init: function () {
  53424. var self = this;
  53425. this.onButtonChanged = bind(this.onButtonChanged, this);
  53426. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53427. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53428. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53429. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53430. this.controllerPresent = false;
  53431. this.lastControllerCheck = 0;
  53432. this.bindMethods();
  53433. },
  53434. addEventListeners: function () {
  53435. var el = this.el;
  53436. el.addEventListener('buttonchanged', this.onButtonChanged);
  53437. el.addEventListener('buttondown', this.onButtonDown);
  53438. el.addEventListener('buttonup', this.onButtonUp);
  53439. el.addEventListener('touchstart', this.onButtonTouchStart);
  53440. el.addEventListener('touchend', this.onButtonTouchEnd);
  53441. el.addEventListener('model-loaded', this.onModelLoaded);
  53442. el.addEventListener('axismove', this.onAxisMoved);
  53443. this.controllerEventsActive = true;
  53444. this.addControllersUpdateListener();
  53445. },
  53446. removeEventListeners: function () {
  53447. var el = this.el;
  53448. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53449. el.removeEventListener('buttondown', this.onButtonDown);
  53450. el.removeEventListener('buttonup', this.onButtonUp);
  53451. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53452. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53453. el.removeEventListener('model-loaded', this.onModelLoaded);
  53454. el.removeEventListener('axismove', this.onAxisMoved);
  53455. this.controllerEventsActive = false;
  53456. this.removeControllersUpdateListener();
  53457. },
  53458. checkIfControllerPresent: function () {
  53459. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  53460. this.data.hand ? {hand: this.data.hand} : {});
  53461. },
  53462. play: function () {
  53463. this.checkIfControllerPresent();
  53464. this.addControllersUpdateListener();
  53465. },
  53466. pause: function () {
  53467. this.removeEventListeners();
  53468. this.removeControllersUpdateListener();
  53469. },
  53470. injectTrackedControls: function () {
  53471. var el = this.el;
  53472. var data = this.data;
  53473. el.setAttribute('tracked-controls', {
  53474. armModel: data.armModel,
  53475. idPrefix: GAMEPAD_ID_PREFIX,
  53476. orientationOffset: data.orientationOffset
  53477. });
  53478. if (!this.data.model) { return; }
  53479. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  53480. },
  53481. addControllersUpdateListener: function () {
  53482. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53483. },
  53484. removeControllersUpdateListener: function () {
  53485. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53486. },
  53487. onControllersUpdate: function () {
  53488. this.checkIfControllerPresent();
  53489. },
  53490. onModelLoaded: function (evt) {
  53491. var controllerObject3D = evt.detail.model;
  53492. var buttonMeshes;
  53493. if (!this.data.model) { return; }
  53494. buttonMeshes = this.buttonMeshes = {};
  53495. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  53496. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  53497. if (buttonMeshes.triggerPressed) {
  53498. buttonMeshes.triggerPressed.visible = false;
  53499. }
  53500. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  53501. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  53502. if (buttonMeshes.trackpadPressed) {
  53503. buttonMeshes.trackpadPressed.visible = false;
  53504. }
  53505. },
  53506. // No analog buttons, only emits 0/1 values
  53507. onButtonChanged: function (evt) {
  53508. var button = this.mapping.buttons[evt.detail.id];
  53509. if (!button) return;
  53510. // Pass along changed event with button state, using button mapping for convenience.
  53511. this.el.emit(button + 'changed', evt.detail.state);
  53512. },
  53513. onAxisMoved: function (evt) {
  53514. emitIfAxesChanged(this, this.mapping.axes, evt);
  53515. },
  53516. updateModel: function (buttonName, evtName) {
  53517. if (!this.data.model) { return; }
  53518. this.updateButtonModel(buttonName, evtName);
  53519. },
  53520. updateButtonModel: function (buttonName, state) {
  53521. var buttonMeshes = this.buttonMeshes;
  53522. var pressedName = buttonName + 'Pressed';
  53523. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  53524. return;
  53525. }
  53526. var color;
  53527. switch (state) {
  53528. case 'down':
  53529. color = this.data.buttonHighlightColor;
  53530. break;
  53531. case 'touchstart':
  53532. color = this.data.buttonTouchedColor;
  53533. break;
  53534. }
  53535. if (color) {
  53536. buttonMeshes[pressedName].material.color.set(color);
  53537. }
  53538. buttonMeshes[pressedName].visible = !!color;
  53539. buttonMeshes[buttonName].visible = !color;
  53540. }
  53541. });
  53542. },{"../core/component":132,"../utils/bind":200,"../utils/tracked-controls":215}],122:[function(_dereq_,module,exports){
  53543. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  53544. var registerComponent = _dereq_('../core/component').registerComponent;
  53545. var THREE = _dereq_('../lib/three');
  53546. var utils = _dereq_('../utils/');
  53547. var bind = utils.bind;
  53548. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  53549. var CLAMP_VELOCITY = 0.00001;
  53550. var MAX_DELTA = 0.2;
  53551. var KEYS = [
  53552. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  53553. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  53554. ];
  53555. /**
  53556. * WASD component to control entities using WASD keys.
  53557. */
  53558. module.exports.Component = registerComponent('wasd-controls', {
  53559. schema: {
  53560. acceleration: {default: 65},
  53561. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  53562. adEnabled: {default: true},
  53563. adInverted: {default: false},
  53564. enabled: {default: true},
  53565. fly: {default: false},
  53566. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  53567. wsEnabled: {default: true},
  53568. wsInverted: {default: false}
  53569. },
  53570. init: function () {
  53571. // To keep track of the pressed keys.
  53572. this.keys = {};
  53573. this.easing = 1.1;
  53574. this.velocity = new THREE.Vector3();
  53575. // Bind methods and add event listeners.
  53576. this.onBlur = bind(this.onBlur, this);
  53577. this.onContextMenu = bind(this.onContextMenu, this);
  53578. this.onFocus = bind(this.onFocus, this);
  53579. this.onKeyDown = bind(this.onKeyDown, this);
  53580. this.onKeyUp = bind(this.onKeyUp, this);
  53581. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  53582. this.attachVisibilityEventListeners();
  53583. },
  53584. tick: function (time, delta) {
  53585. var data = this.data;
  53586. var el = this.el;
  53587. var velocity = this.velocity;
  53588. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  53589. isEmptyObject(this.keys)) { return; }
  53590. // Update velocity.
  53591. delta = delta / 1000;
  53592. this.updateVelocity(delta);
  53593. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  53594. // Get movement vector and translate position.
  53595. el.object3D.position.add(this.getMovementVector(delta));
  53596. },
  53597. remove: function () {
  53598. this.removeKeyEventListeners();
  53599. this.removeVisibilityEventListeners();
  53600. },
  53601. play: function () {
  53602. this.attachKeyEventListeners();
  53603. },
  53604. pause: function () {
  53605. this.keys = {};
  53606. this.removeKeyEventListeners();
  53607. },
  53608. updateVelocity: function (delta) {
  53609. var acceleration;
  53610. var adAxis;
  53611. var adSign;
  53612. var data = this.data;
  53613. var keys = this.keys;
  53614. var velocity = this.velocity;
  53615. var wsAxis;
  53616. var wsSign;
  53617. adAxis = data.adAxis;
  53618. wsAxis = data.wsAxis;
  53619. // If FPS too low, reset velocity.
  53620. if (delta > MAX_DELTA) {
  53621. velocity[adAxis] = 0;
  53622. velocity[wsAxis] = 0;
  53623. return;
  53624. }
  53625. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  53626. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  53627. // Velocity Easing.
  53628. if (velocity[adAxis] !== 0) {
  53629. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  53630. }
  53631. if (velocity[wsAxis] !== 0) {
  53632. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  53633. }
  53634. // Clamp velocity easing.
  53635. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  53636. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  53637. if (!data.enabled) { return; }
  53638. // Update velocity using keys pressed.
  53639. acceleration = data.acceleration;
  53640. if (data.adEnabled) {
  53641. adSign = data.adInverted ? -1 : 1;
  53642. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  53643. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  53644. }
  53645. if (data.wsEnabled) {
  53646. wsSign = data.wsInverted ? -1 : 1;
  53647. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  53648. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  53649. }
  53650. },
  53651. getMovementVector: (function () {
  53652. var directionVector = new THREE.Vector3(0, 0, 0);
  53653. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  53654. return function (delta) {
  53655. var rotation = this.el.getAttribute('rotation');
  53656. var velocity = this.velocity;
  53657. var xRotation;
  53658. directionVector.copy(velocity);
  53659. directionVector.multiplyScalar(delta);
  53660. // Absolute.
  53661. if (!rotation) { return directionVector; }
  53662. xRotation = this.data.fly ? rotation.x : 0;
  53663. // Transform direction relative to heading.
  53664. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  53665. directionVector.applyEuler(rotationEuler);
  53666. return directionVector;
  53667. };
  53668. })(),
  53669. attachVisibilityEventListeners: function () {
  53670. window.oncontextmenu = this.onContextMenu;
  53671. window.addEventListener('blur', this.onBlur);
  53672. window.addEventListener('focus', this.onFocus);
  53673. document.addEventListener('visibilitychange', this.onVisibilityChange);
  53674. },
  53675. removeVisibilityEventListeners: function () {
  53676. window.removeEventListener('blur', this.onBlur);
  53677. window.removeEventListener('focus', this.onFocus);
  53678. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  53679. },
  53680. attachKeyEventListeners: function () {
  53681. window.addEventListener('keydown', this.onKeyDown);
  53682. window.addEventListener('keyup', this.onKeyUp);
  53683. },
  53684. removeKeyEventListeners: function () {
  53685. window.removeEventListener('keydown', this.onKeyDown);
  53686. window.removeEventListener('keyup', this.onKeyUp);
  53687. },
  53688. onContextMenu: function () {
  53689. var keys = Object.keys(this.keys);
  53690. for (var i = 0; i < keys.length; i++) {
  53691. delete this.keys[keys[i]];
  53692. }
  53693. },
  53694. onBlur: function () {
  53695. this.pause();
  53696. },
  53697. onFocus: function () {
  53698. this.play();
  53699. },
  53700. onVisibilityChange: function () {
  53701. if (document.hidden) {
  53702. this.onBlur();
  53703. } else {
  53704. this.onFocus();
  53705. }
  53706. },
  53707. onKeyDown: function (event) {
  53708. var code;
  53709. if (!shouldCaptureKeyEvent(event)) { return; }
  53710. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53711. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  53712. },
  53713. onKeyUp: function (event) {
  53714. var code;
  53715. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53716. delete this.keys[code];
  53717. }
  53718. });
  53719. function isEmptyObject (keys) {
  53720. var key;
  53721. for (key in keys) { return false; }
  53722. return true;
  53723. }
  53724. },{"../constants":124,"../core/component":132,"../lib/three":180,"../utils/":206}],123:[function(_dereq_,module,exports){
  53725. /* global THREE */
  53726. var registerComponent = _dereq_('../core/component').registerComponent;
  53727. var bind = _dereq_('../utils/bind');
  53728. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53729. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53730. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53731. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53732. var utils = _dereq_('../utils/');
  53733. var debug = utils.debug('components:windows-motion-controls:debug');
  53734. var warn = utils.debug('components:windows-motion-controls:warn');
  53735. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  53736. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  53737. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  53738. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53739. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  53740. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  53741. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  53742. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53743. var INPUT_MAPPING_WEBVR = {
  53744. // A-Frame specific semantic axis names
  53745. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  53746. // A-Frame specific semantic button names
  53747. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  53748. // A mapping of the semantic name to node name in the glTF model file,
  53749. // that should be transformed by axis value.
  53750. // This array mirrors the browser Gamepad.axes array, such that
  53751. // the mesh corresponding to axis 0 is in this array index 0.
  53752. axisMeshNames: [
  53753. 'THUMBSTICK_X',
  53754. 'THUMBSTICK_Y',
  53755. 'TOUCHPAD_TOUCH_X',
  53756. 'TOUCHPAD_TOUCH_Y'
  53757. ],
  53758. // A mapping of the semantic name to button node name in the glTF model file,
  53759. // that should be transformed by button value.
  53760. buttonMeshNames: {
  53761. 'trigger': 'SELECT',
  53762. 'menu': 'MENU',
  53763. 'grip': 'GRASP',
  53764. 'thumbstick': 'THUMBSTICK_PRESS',
  53765. 'trackpad': 'TOUCHPAD_PRESS'
  53766. },
  53767. pointingPoseMeshName: 'POINTING_POSE'
  53768. };
  53769. var INPUT_MAPPING_WEBXR = {
  53770. // A-Frame specific semantic axis names
  53771. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  53772. // A-Frame specific semantic button names
  53773. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  53774. // A mapping of the semantic name to node name in the glTF model file,
  53775. // that should be transformed by axis value.
  53776. // This array mirrors the browser Gamepad.axes array, such that
  53777. // the mesh corresponding to axis 0 is in this array index 0.
  53778. axisMeshNames: [
  53779. 'TOUCHPAD_TOUCH_X',
  53780. 'TOUCHPAD_TOUCH_X',
  53781. 'THUMBSTICK_X',
  53782. 'THUMBSTICK_Y'
  53783. ],
  53784. // A mapping of the semantic name to button node name in the glTF model file,
  53785. // that should be transformed by button value.
  53786. buttonMeshNames: {
  53787. 'trigger': 'SELECT',
  53788. 'menu': 'MENU',
  53789. 'squeeze': 'GRASP',
  53790. 'thumbstick': 'THUMBSTICK_PRESS',
  53791. 'touchpad': 'TOUCHPAD_PRESS'
  53792. },
  53793. pointingPoseMeshName: 'POINTING_POSE'
  53794. };
  53795. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53796. /**
  53797. * Windows Motion Controller controls.
  53798. * Interface with Windows Motion Controller controllers and map Gamepad events to
  53799. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  53800. * Load a controller model and transform the pressed buttons.
  53801. */
  53802. module.exports.Component = registerComponent('windows-motion-controls', {
  53803. schema: {
  53804. hand: {default: DEFAULT_HANDEDNESS},
  53805. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  53806. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  53807. pair: {default: 0},
  53808. // If true, loads the controller glTF asset.
  53809. model: {default: true},
  53810. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  53811. hideDisconnected: {default: true}
  53812. },
  53813. mapping: INPUT_MAPPING,
  53814. bindMethods: function () {
  53815. this.onModelError = bind(this.onModelError, this);
  53816. this.onModelLoaded = bind(this.onModelLoaded, this);
  53817. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53818. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53819. this.onAxisMoved = bind(this.onAxisMoved, this);
  53820. },
  53821. init: function () {
  53822. var self = this;
  53823. var el = this.el;
  53824. this.onButtonChanged = bind(this.onButtonChanged, this);
  53825. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53826. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53827. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53828. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53829. this.onControllerConnected = function () { self.setModelVisibility(true); };
  53830. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  53831. this.controllerPresent = false;
  53832. this.lastControllerCheck = 0;
  53833. this.previousButtonValues = {};
  53834. this.bindMethods();
  53835. // Cache for submeshes that we have looked up by name.
  53836. this.loadedMeshInfo = {
  53837. buttonMeshes: null,
  53838. axisMeshes: null
  53839. };
  53840. // Pointing poses
  53841. this.rayOrigin = {
  53842. origin: new THREE.Vector3(),
  53843. direction: new THREE.Vector3(0, 0, -1),
  53844. createdFromMesh: false
  53845. };
  53846. el.addEventListener('controllerconnected', this.onControllerConnected);
  53847. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  53848. },
  53849. addEventListeners: function () {
  53850. var el = this.el;
  53851. el.addEventListener('buttonchanged', this.onButtonChanged);
  53852. el.addEventListener('buttondown', this.onButtonDown);
  53853. el.addEventListener('buttonup', this.onButtonUp);
  53854. el.addEventListener('touchstart', this.onButtonTouchStart);
  53855. el.addEventListener('touchend', this.onButtonTouchEnd);
  53856. el.addEventListener('axismove', this.onAxisMoved);
  53857. el.addEventListener('model-error', this.onModelError);
  53858. el.addEventListener('model-loaded', this.onModelLoaded);
  53859. this.controllerEventsActive = true;
  53860. },
  53861. removeEventListeners: function () {
  53862. var el = this.el;
  53863. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53864. el.removeEventListener('buttondown', this.onButtonDown);
  53865. el.removeEventListener('buttonup', this.onButtonUp);
  53866. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53867. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53868. el.removeEventListener('axismove', this.onAxisMoved);
  53869. el.removeEventListener('model-error', this.onModelError);
  53870. el.removeEventListener('model-loaded', this.onModelLoaded);
  53871. this.controllerEventsActive = false;
  53872. },
  53873. checkIfControllerPresent: function () {
  53874. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  53875. hand: this.data.hand,
  53876. index: this.data.pair,
  53877. iterateControllerProfiles: true
  53878. });
  53879. },
  53880. play: function () {
  53881. this.checkIfControllerPresent();
  53882. this.addControllersUpdateListener();
  53883. },
  53884. pause: function () {
  53885. this.removeEventListeners();
  53886. this.removeControllersUpdateListener();
  53887. },
  53888. updateControllerModel: function () {
  53889. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  53890. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  53891. this.modelReady();
  53892. return;
  53893. }
  53894. var sourceUrl = this.createControllerModelUrl();
  53895. this.loadModel(sourceUrl);
  53896. },
  53897. /**
  53898. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  53899. * art assets.
  53900. */
  53901. createControllerModelUrl: function (forceDefault) {
  53902. // Determine the device specific folder based on the ID suffix
  53903. var trackedControlsComponent = this.el.components['tracked-controls'];
  53904. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  53905. var device = 'default';
  53906. var hand = this.data.hand;
  53907. var filename;
  53908. if (controller && !window.hasNativeWebXRImplementation) {
  53909. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  53910. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  53911. // In this case, we want to load the universal model, so need to get the '' from the controller.
  53912. hand = controller.hand;
  53913. if (!forceDefault) {
  53914. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  53915. device = ((match && match[0]) || device);
  53916. }
  53917. }
  53918. // Hand
  53919. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  53920. // Final url
  53921. return MODEL_BASE_URL + device + '/' + filename;
  53922. },
  53923. injectTrackedControls: function () {
  53924. var data = this.data;
  53925. this.el.setAttribute('tracked-controls', {
  53926. idPrefix: GAMEPAD_ID_PREFIX,
  53927. controller: data.pair,
  53928. hand: data.hand,
  53929. armModel: false
  53930. });
  53931. this.updateControllerModel();
  53932. },
  53933. addControllersUpdateListener: function () {
  53934. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53935. },
  53936. removeControllersUpdateListener: function () {
  53937. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53938. },
  53939. onControllersUpdate: function () {
  53940. this.checkIfControllerPresent();
  53941. },
  53942. onModelError: function (evt) {
  53943. var defaultUrl = this.createControllerModelUrl(true);
  53944. if (evt.detail.src !== defaultUrl) {
  53945. warn('Failed to load controller model for device, attempting to load default.');
  53946. this.loadModel(defaultUrl);
  53947. } else {
  53948. warn('Failed to load default controller model.');
  53949. }
  53950. },
  53951. loadModel: function (url) {
  53952. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  53953. // removed and re-loaded if the given url changes.
  53954. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  53955. },
  53956. onModelLoaded: function (evt) {
  53957. var rootNode = this.controllerModel = evt.detail.model;
  53958. var loadedMeshInfo = this.loadedMeshInfo;
  53959. var i;
  53960. var meshName;
  53961. var mesh;
  53962. var meshInfo;
  53963. debug('Processing model');
  53964. // Reset the caches
  53965. loadedMeshInfo.buttonMeshes = {};
  53966. loadedMeshInfo.axisMeshes = {};
  53967. // Cache our meshes so we aren't traversing the hierarchy per frame
  53968. if (rootNode) {
  53969. // Button Meshes
  53970. for (i = 0; i < this.mapping.buttons.length; i++) {
  53971. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  53972. if (!meshName) {
  53973. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  53974. continue;
  53975. }
  53976. mesh = rootNode.getObjectByName(meshName);
  53977. if (!mesh) {
  53978. warn('Missing button mesh with name: ' + meshName);
  53979. continue;
  53980. }
  53981. meshInfo = {
  53982. index: i,
  53983. value: getImmediateChildByName(mesh, 'VALUE'),
  53984. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  53985. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  53986. };
  53987. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  53988. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  53989. } else {
  53990. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  53991. warn('Missing button submesh under mesh with name: ' + meshName +
  53992. '(VALUE: ' + !!meshInfo.value +
  53993. ', PRESSED: ' + !!meshInfo.pressed +
  53994. ', UNPRESSED:' + !!meshInfo.unpressed +
  53995. ')');
  53996. }
  53997. }
  53998. // Axis Meshes
  53999. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  54000. meshName = this.mapping.axisMeshNames[i];
  54001. if (!meshName) {
  54002. debug('Skipping unknown axis at index: ' + i);
  54003. continue;
  54004. }
  54005. mesh = rootNode.getObjectByName(meshName);
  54006. if (!mesh) {
  54007. warn('Missing axis mesh with name: ' + meshName);
  54008. continue;
  54009. }
  54010. meshInfo = {
  54011. index: i,
  54012. value: getImmediateChildByName(mesh, 'VALUE'),
  54013. min: getImmediateChildByName(mesh, 'MIN'),
  54014. max: getImmediateChildByName(mesh, 'MAX')
  54015. };
  54016. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  54017. loadedMeshInfo.axisMeshes[i] = meshInfo;
  54018. } else {
  54019. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  54020. warn('Missing axis submesh under mesh with name: ' + meshName +
  54021. '(VALUE: ' + !!meshInfo.value +
  54022. ', MIN: ' + !!meshInfo.min +
  54023. ', MAX:' + !!meshInfo.max +
  54024. ')');
  54025. }
  54026. }
  54027. this.calculateRayOriginFromMesh(rootNode);
  54028. // Determine if the model has to be visible or not.
  54029. this.setModelVisibility();
  54030. }
  54031. debug('Model load complete.');
  54032. // Look through only immediate children. This will return null if no mesh exists with the given name.
  54033. function getImmediateChildByName (object3d, value) {
  54034. for (var i = 0, l = object3d.children.length; i < l; i++) {
  54035. var obj = object3d.children[i];
  54036. if (obj && obj['name'] === value) {
  54037. return obj;
  54038. }
  54039. }
  54040. return undefined;
  54041. }
  54042. },
  54043. calculateRayOriginFromMesh: (function () {
  54044. var quaternion = new THREE.Quaternion();
  54045. return function (rootNode) {
  54046. var mesh;
  54047. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  54048. // in the glTF (assumes that root node is at world origin)
  54049. this.rayOrigin.origin.set(0, 0, 0);
  54050. this.rayOrigin.direction.set(0, 0, -1);
  54051. this.rayOrigin.createdFromMesh = true;
  54052. // Try to read Pointing pose from the source model
  54053. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  54054. if (mesh) {
  54055. var parent = rootNode.parent;
  54056. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  54057. if (parent) {
  54058. rootNode.parent = null;
  54059. rootNode.updateMatrixWorld(true);
  54060. rootNode.parent = parent;
  54061. }
  54062. mesh.getWorldPosition(this.rayOrigin.origin);
  54063. mesh.getWorldQuaternion(quaternion);
  54064. this.rayOrigin.direction.applyQuaternion(quaternion);
  54065. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  54066. if (parent) {
  54067. rootNode.updateMatrixWorld(true);
  54068. }
  54069. } else {
  54070. debug('Mesh does not contain pointing origin data, defaulting to none.');
  54071. }
  54072. // Emit event stating that our pointing ray is now accurate.
  54073. this.modelReady();
  54074. };
  54075. })(),
  54076. lerpAxisTransform: (function () {
  54077. var quaternion = new THREE.Quaternion();
  54078. return function (axis, axisValue) {
  54079. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  54080. if (!axisMeshInfo) return;
  54081. var min = axisMeshInfo.min;
  54082. var max = axisMeshInfo.max;
  54083. var target = axisMeshInfo.value;
  54084. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  54085. var lerpValue = axisValue * 0.5 + 0.5;
  54086. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  54087. target.position.lerpVectors(min.position, max.position, lerpValue);
  54088. };
  54089. })(),
  54090. lerpButtonTransform: (function () {
  54091. var quaternion = new THREE.Quaternion();
  54092. return function (buttonName, buttonValue) {
  54093. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  54094. if (!buttonMeshInfo) return;
  54095. var min = buttonMeshInfo.unpressed;
  54096. var max = buttonMeshInfo.pressed;
  54097. var target = buttonMeshInfo.value;
  54098. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  54099. target.position.lerpVectors(min.position, max.position, buttonValue);
  54100. };
  54101. })(),
  54102. modelReady: function () {
  54103. this.el.emit('controllermodelready', {
  54104. name: 'windows-motion-controls',
  54105. model: this.data.model,
  54106. rayOrigin: this.rayOrigin
  54107. });
  54108. },
  54109. onButtonChanged: function (evt) {
  54110. var buttonName = this.mapping.buttons[evt.detail.id];
  54111. if (buttonName) {
  54112. // Update the button mesh transform
  54113. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  54114. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  54115. }
  54116. // Only emit events for buttons that we know how to map from index to name
  54117. this.el.emit(buttonName + 'changed', evt.detail.state);
  54118. }
  54119. },
  54120. onAxisMoved: function (evt) {
  54121. var numAxes = this.mapping.axisMeshNames.length;
  54122. // Only attempt to update meshes if we have valid data.
  54123. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  54124. for (var axis = 0; axis < numAxes; axis++) {
  54125. // Update the button mesh transform
  54126. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  54127. }
  54128. }
  54129. emitIfAxesChanged(this, this.mapping.axes, evt);
  54130. },
  54131. setModelVisibility: function (visible) {
  54132. var model = this.el.getObject3D('mesh');
  54133. visible = visible !== undefined ? visible : this.modelVisible;
  54134. this.modelVisible = visible;
  54135. if (!model) { return; }
  54136. model.visible = visible;
  54137. }
  54138. });
  54139. },{"../constants":124,"../core/component":132,"../utils/":206,"../utils/bind":200,"../utils/tracked-controls":215}],124:[function(_dereq_,module,exports){
  54140. module.exports = {
  54141. AFRAME_INJECTED: 'aframe-injected',
  54142. DEFAULT_CAMERA_HEIGHT: 1.6,
  54143. DEFAULT_HANDEDNESS: 'right',
  54144. keyboardevent: _dereq_('./keyboardevent')
  54145. };
  54146. },{"./keyboardevent":125}],125:[function(_dereq_,module,exports){
  54147. module.exports = {
  54148. // Tiny KeyboardEvent.code polyfill.
  54149. KEYCODE_TO_CODE: {
  54150. '38': 'ArrowUp',
  54151. '37': 'ArrowLeft',
  54152. '40': 'ArrowDown',
  54153. '39': 'ArrowRight',
  54154. '87': 'KeyW',
  54155. '65': 'KeyA',
  54156. '83': 'KeyS',
  54157. '68': 'KeyD'
  54158. }
  54159. };
  54160. },{}],126:[function(_dereq_,module,exports){
  54161. var ANode = _dereq_('./a-node');
  54162. var bind = _dereq_('../utils/bind');
  54163. var debug = _dereq_('../utils/debug');
  54164. var registerElement = _dereq_('./a-register-element').registerElement;
  54165. var THREE = _dereq_('../lib/three');
  54166. var fileLoader = new THREE.FileLoader();
  54167. var warn = debug('core:a-assets:warn');
  54168. /**
  54169. * Asset management system. Handles blocking on asset loading.
  54170. */
  54171. module.exports = registerElement('a-assets', {
  54172. prototype: Object.create(ANode.prototype, {
  54173. createdCallback: {
  54174. value: function () {
  54175. this.isAssets = true;
  54176. this.fileLoader = fileLoader;
  54177. this.timeout = null;
  54178. }
  54179. },
  54180. attachedCallback: {
  54181. value: function () {
  54182. var self = this;
  54183. var i;
  54184. var loaded = [];
  54185. var mediaEl;
  54186. var mediaEls;
  54187. var imgEl;
  54188. var imgEls;
  54189. var timeout;
  54190. if (!this.parentNode.isScene) {
  54191. throw new Error('<a-assets> must be a child of a <a-scene>.');
  54192. }
  54193. // Wait for <img>s.
  54194. imgEls = this.querySelectorAll('img');
  54195. for (i = 0; i < imgEls.length; i++) {
  54196. imgEl = fixUpMediaElement(imgEls[i]);
  54197. loaded.push(new Promise(function (resolve, reject) {
  54198. // Set in cache because we won't be needing to call three.js loader if we have.
  54199. // a loaded media element.
  54200. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  54201. imgEl.onload = resolve;
  54202. imgEl.onerror = reject;
  54203. }));
  54204. }
  54205. // Wait for <audio>s and <video>s.
  54206. mediaEls = this.querySelectorAll('audio, video');
  54207. for (i = 0; i < mediaEls.length; i++) {
  54208. mediaEl = fixUpMediaElement(mediaEls[i]);
  54209. if (!mediaEl.src && !mediaEl.srcObject) {
  54210. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  54211. }
  54212. loaded.push(mediaElementLoaded(mediaEl));
  54213. }
  54214. // Trigger loaded for scene to start rendering.
  54215. Promise.all(loaded).then(bind(this.load, this));
  54216. // Timeout to start loading anyways.
  54217. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  54218. this.timeout = setTimeout(function () {
  54219. if (self.hasLoaded) { return; }
  54220. warn('Asset loading timed out in ', timeout, 'ms');
  54221. self.emit('timeout');
  54222. self.load();
  54223. }, timeout);
  54224. }
  54225. },
  54226. detachedCallback: {
  54227. value: function () {
  54228. if (this.timeout) { clearTimeout(this.timeout); }
  54229. }
  54230. },
  54231. load: {
  54232. value: function () {
  54233. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  54234. return el.isAssetItem && el.hasAttribute('src');
  54235. });
  54236. }
  54237. }
  54238. })
  54239. });
  54240. /**
  54241. * Preload using XHRLoader for any type of asset.
  54242. */
  54243. registerElement('a-asset-item', {
  54244. prototype: Object.create(ANode.prototype, {
  54245. createdCallback: {
  54246. value: function () {
  54247. this.data = null;
  54248. this.isAssetItem = true;
  54249. }
  54250. },
  54251. attachedCallback: {
  54252. value: function () {
  54253. var self = this;
  54254. var src = this.getAttribute('src');
  54255. fileLoader.setResponseType(
  54256. this.getAttribute('response-type') || inferResponseType(src));
  54257. fileLoader.load(src, function handleOnLoad (response) {
  54258. self.data = response;
  54259. /*
  54260. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  54261. previous one closes, the second request never finishes.
  54262. setTimeout finishes the first request and lets the logic triggered by load open
  54263. subsequent requests.
  54264. setTimeout can be removed once the fix for the bug below ships:
  54265. 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
  54266. */
  54267. setTimeout(function load () { ANode.prototype.load.call(self); });
  54268. }, function handleOnProgress (xhr) {
  54269. self.emit('progress', {
  54270. loadedBytes: xhr.loaded,
  54271. totalBytes: xhr.total,
  54272. xhr: xhr
  54273. });
  54274. }, function handleOnError (xhr) {
  54275. self.emit('error', {xhr: xhr});
  54276. });
  54277. }
  54278. }
  54279. })
  54280. });
  54281. /**
  54282. * Create a Promise that resolves once the media element has finished buffering.
  54283. *
  54284. * @param {Element} el - HTMLMediaElement.
  54285. * @returns {Promise}
  54286. */
  54287. function mediaElementLoaded (el) {
  54288. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  54289. return;
  54290. }
  54291. // If media specifies autoplay or preload, wait until media is completely buffered.
  54292. return new Promise(function (resolve, reject) {
  54293. if (el.readyState === 4) { return resolve(); } // Already loaded.
  54294. if (el.error) { return reject(); } // Error.
  54295. el.addEventListener('loadeddata', checkProgress, false);
  54296. el.addEventListener('progress', checkProgress, false);
  54297. el.addEventListener('error', reject, false);
  54298. function checkProgress () {
  54299. // Add up the seconds buffered.
  54300. var secondsBuffered = 0;
  54301. for (var i = 0; i < el.buffered.length; i++) {
  54302. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  54303. }
  54304. // Compare seconds buffered to media duration.
  54305. if (secondsBuffered >= el.duration) {
  54306. // Set in cache because we won't be needing to call three.js loader if we have.
  54307. // a loaded media element.
  54308. // Store video elements only. three.js loader is used for audio elements.
  54309. // See assetParse too.
  54310. if (el.tagName === 'VIDEO') {
  54311. THREE.Cache.files[el.getAttribute('src')] = el;
  54312. }
  54313. resolve();
  54314. }
  54315. }
  54316. });
  54317. }
  54318. /**
  54319. * Automatically add attributes to media elements where convenient.
  54320. * crossorigin, playsinline.
  54321. */
  54322. function fixUpMediaElement (mediaEl) {
  54323. // Cross-origin.
  54324. var newMediaEl = setCrossOrigin(mediaEl);
  54325. // Plays inline for mobile.
  54326. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  54327. newMediaEl.setAttribute('playsinline', '');
  54328. newMediaEl.setAttribute('webkit-playsinline', '');
  54329. }
  54330. if (newMediaEl !== mediaEl) {
  54331. mediaEl.parentNode.appendChild(newMediaEl);
  54332. mediaEl.parentNode.removeChild(mediaEl);
  54333. }
  54334. return newMediaEl;
  54335. }
  54336. /**
  54337. * Automatically set `crossorigin` if not defined on the media element.
  54338. * If it is not defined, we must create and re-append a new media element <img> and
  54339. * have the browser re-request it with `crossorigin` set.
  54340. *
  54341. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  54342. * @returns {Element} Media element to be used to listen to for loaded events.
  54343. */
  54344. function setCrossOrigin (mediaEl) {
  54345. var newMediaEl;
  54346. var src;
  54347. // Already has crossorigin set.
  54348. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  54349. src = mediaEl.getAttribute('src');
  54350. if (src !== null) {
  54351. // Does not have protocol.
  54352. if (src.indexOf('://') === -1) { return mediaEl; }
  54353. // Determine if cross origin is actually needed.
  54354. if (extractDomain(src) === window.location.host) { return mediaEl; }
  54355. }
  54356. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  54357. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  54358. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  54359. mediaEl.crossOrigin = 'anonymous';
  54360. newMediaEl = mediaEl.cloneNode(true);
  54361. return newMediaEl;
  54362. }
  54363. /**
  54364. * Extract domain out of URL.
  54365. *
  54366. * @param {string} url
  54367. * @returns {string}
  54368. */
  54369. function extractDomain (url) {
  54370. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  54371. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  54372. // Find and remove port number.
  54373. return domain.substring(0, domain.indexOf(':'));
  54374. }
  54375. /**
  54376. * Infer response-type attribute from src.
  54377. * Default is text (default XMLHttpRequest.responseType)
  54378. * and arraybuffer for .glb files.
  54379. *
  54380. * @param {string} src
  54381. * @returns {string}
  54382. */
  54383. function inferResponseType (src) {
  54384. var fileName = getFileNameFromURL(src);
  54385. var dotLastIndex = fileName.lastIndexOf('.');
  54386. if (dotLastIndex >= 0) {
  54387. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  54388. if (extension === '.glb') {
  54389. return 'arraybuffer';
  54390. }
  54391. }
  54392. return 'text';
  54393. }
  54394. module.exports.inferResponseType = inferResponseType;
  54395. /**
  54396. * Extract filename from URL
  54397. *
  54398. * @param {string} url
  54399. * @returns {string}
  54400. */
  54401. function getFileNameFromURL (url) {
  54402. var parser = document.createElement('a');
  54403. parser.href = url;
  54404. var query = parser.search.replace(/^\?/, '');
  54405. var filePath = url.replace(query, '').replace('?', '');
  54406. return filePath.substring(filePath.lastIndexOf('/') + 1);
  54407. }
  54408. module.exports.getFileNameFromURL = getFileNameFromURL;
  54409. },{"../lib/three":180,"../utils/bind":200,"../utils/debug":202,"./a-node":130,"./a-register-element":131}],127:[function(_dereq_,module,exports){
  54410. var debug = _dereq_('../utils/debug');
  54411. var registerElement = _dereq_('./a-register-element').registerElement;
  54412. var warn = debug('core:cubemap:warn');
  54413. /**
  54414. * Cubemap element that handles validation and exposes list of URLs.
  54415. * Does not listen to updates.
  54416. */
  54417. module.exports = registerElement('a-cubemap', {
  54418. prototype: Object.create(window.HTMLElement.prototype, {
  54419. /**
  54420. * Calculates this.srcs.
  54421. */
  54422. attachedCallback: {
  54423. value: function () {
  54424. this.srcs = this.validate();
  54425. },
  54426. writable: window.debug
  54427. },
  54428. /**
  54429. * Checks for exactly six elements with [src].
  54430. * Does not check explicitly for <img>s in case user does not want
  54431. * prefetching.
  54432. *
  54433. * @returns {Array|null} - six URLs if valid, else null.
  54434. */
  54435. validate: {
  54436. value: function () {
  54437. var elements = this.querySelectorAll('[src]');
  54438. var i;
  54439. var srcs = [];
  54440. if (elements.length === 6) {
  54441. for (i = 0; i < elements.length; i++) {
  54442. srcs.push(elements[i].getAttribute('src'));
  54443. }
  54444. return srcs;
  54445. }
  54446. // Else if there are not six elements, throw a warning.
  54447. warn(
  54448. '<a-cubemap> did not contain exactly six elements each with a ' +
  54449. '`src` attribute.');
  54450. },
  54451. writable: window.debug
  54452. }
  54453. })
  54454. });
  54455. },{"../utils/debug":202,"./a-register-element":131}],128:[function(_dereq_,module,exports){
  54456. var ANode = _dereq_('./a-node');
  54457. var COMPONENTS = _dereq_('./component').components;
  54458. var registerElement = _dereq_('./a-register-element').registerElement;
  54459. var THREE = _dereq_('../lib/three');
  54460. var utils = _dereq_('../utils/');
  54461. var AEntity;
  54462. var debug = utils.debug('core:a-entity:debug');
  54463. var warn = utils.debug('core:a-entity:warn');
  54464. var MULTIPLE_COMPONENT_DELIMITER = '__';
  54465. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  54466. var ONCE = {once: true};
  54467. /**
  54468. * Entity is a container object that components are plugged into to comprise everything in
  54469. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  54470. *
  54471. * To be able to take components, the scene element inherits from the entity definition.
  54472. *
  54473. * @member {object} components - entity's currently initialized components.
  54474. * @member {object} object3D - three.js object.
  54475. * @member {array} states
  54476. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  54477. */
  54478. var proto = Object.create(ANode.prototype, {
  54479. createdCallback: {
  54480. value: function () {
  54481. this.components = {};
  54482. // To avoid double initializations and infinite loops.
  54483. this.initializingComponents = {};
  54484. this.componentsToUpdate = {};
  54485. this.isEntity = true;
  54486. this.isPlaying = false;
  54487. this.object3D = new THREE.Group();
  54488. this.object3D.el = this;
  54489. this.object3DMap = {};
  54490. this.parentEl = null;
  54491. this.rotationObj = {};
  54492. this.states = [];
  54493. }
  54494. },
  54495. /**
  54496. * Handle changes coming from the browser DOM inspector.
  54497. */
  54498. attributeChangedCallback: {
  54499. value: function (attr, oldVal, newVal) {
  54500. var component = this.components[attr];
  54501. // If the empty string is passed by the component initialization
  54502. // logic we ignore the component update.
  54503. if (component && component.justInitialized && newVal === '') {
  54504. delete component.justInitialized;
  54505. return;
  54506. }
  54507. // When a component is removed after calling el.removeAttribute('material')
  54508. if (!component && newVal === null) { return; }
  54509. this.setEntityAttribute(attr, oldVal, newVal);
  54510. }
  54511. },
  54512. /**
  54513. * Add to parent, load, play.
  54514. */
  54515. attachedCallback: {
  54516. value: function () {
  54517. var assetsEl; // Asset management system element.
  54518. var sceneEl = this.sceneEl;
  54519. var self = this; // Component.
  54520. this.addToParent();
  54521. // Don't .load() scene on attachedCallback.
  54522. if (this.isScene) { return; }
  54523. // Gracefully not error when outside of <a-scene> (e.g., tests).
  54524. if (!sceneEl) {
  54525. this.load();
  54526. return;
  54527. }
  54528. // Wait for asset management system to finish before loading.
  54529. assetsEl = sceneEl.querySelector('a-assets');
  54530. if (assetsEl && !assetsEl.hasLoaded) {
  54531. assetsEl.addEventListener('loaded', function () { self.load(); });
  54532. return;
  54533. }
  54534. this.load();
  54535. }
  54536. },
  54537. /**
  54538. * Tell parent to remove this element's object3D from its object3D.
  54539. * Do not call on scene element because that will cause a call to document.body.remove().
  54540. */
  54541. detachedCallback: {
  54542. value: function () {
  54543. var componentName;
  54544. if (!this.parentEl) { return; }
  54545. // Remove components.
  54546. for (componentName in this.components) {
  54547. this.removeComponent(componentName, false);
  54548. }
  54549. if (this.isScene) { return; }
  54550. this.removeFromParent();
  54551. ANode.prototype.detachedCallback.call(this);
  54552. // Remove cyclic reference.
  54553. this.object3D.el = null;
  54554. }
  54555. },
  54556. getObject3D: {
  54557. value: function (type) {
  54558. return this.object3DMap[type];
  54559. }
  54560. },
  54561. /**
  54562. * Set a THREE.Object3D into the map.
  54563. *
  54564. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  54565. * @param {object} obj - A THREE.Object3D.
  54566. */
  54567. setObject3D: {
  54568. value: function (type, obj) {
  54569. var oldObj;
  54570. var self = this;
  54571. if (!(obj instanceof THREE.Object3D)) {
  54572. throw new Error(
  54573. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  54574. 'THREE.Object3D.'
  54575. );
  54576. }
  54577. // Remove existing object of the type.
  54578. oldObj = this.getObject3D(type);
  54579. if (oldObj) { this.object3D.remove(oldObj); }
  54580. // Set references to A-Frame entity.
  54581. obj.el = this;
  54582. if (obj.children.length) {
  54583. obj.traverse(function bindEl (child) {
  54584. child.el = self;
  54585. });
  54586. }
  54587. // Add.
  54588. this.object3D.add(obj);
  54589. this.object3DMap[type] = obj;
  54590. this.emit('object3dset', {object: obj, type: type});
  54591. }
  54592. },
  54593. /**
  54594. * Remove object from scene and entity object3D map.
  54595. */
  54596. removeObject3D: {
  54597. value: function (type) {
  54598. var obj = this.getObject3D(type);
  54599. if (!obj) {
  54600. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  54601. return;
  54602. }
  54603. this.object3D.remove(obj);
  54604. delete this.object3DMap[type];
  54605. this.emit('object3dremove', {type: type});
  54606. }
  54607. },
  54608. /**
  54609. * Gets or creates an object3D of a given type.
  54610. *
  54611. * @param {string} type - Type of the object3D.
  54612. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  54613. * @returns {object}
  54614. */
  54615. getOrCreateObject3D: {
  54616. value: function (type, Constructor) {
  54617. var object3D = this.getObject3D(type);
  54618. if (!object3D && Constructor) {
  54619. object3D = new Constructor();
  54620. this.setObject3D(type, object3D);
  54621. }
  54622. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  54623. 'and `object3dset` event instead.');
  54624. return object3D;
  54625. }
  54626. },
  54627. /**
  54628. * Add child entity.
  54629. *
  54630. * @param {Element} el - Child entity.
  54631. */
  54632. add: {
  54633. value: function (el) {
  54634. if (!el.object3D) {
  54635. throw new Error("Trying to add an element that doesn't have an `object3D`");
  54636. }
  54637. this.object3D.add(el.object3D);
  54638. this.emit('child-attached', {el: el});
  54639. }
  54640. },
  54641. /**
  54642. * Tell parentNode to add this entity to itself.
  54643. */
  54644. addToParent: {
  54645. value: function () {
  54646. var parentNode = this.parentEl = this.parentNode;
  54647. // `!parentNode` check primarily for unit tests.
  54648. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  54649. parentNode.add(this);
  54650. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  54651. }
  54652. },
  54653. /**
  54654. * Tell parentNode to remove this entity from itself.
  54655. */
  54656. removeFromParent: {
  54657. value: function () {
  54658. var parentEl = this.parentEl;
  54659. this.parentEl.remove(this);
  54660. this.attachedToParent = false;
  54661. this.parentEl = null;
  54662. parentEl.emit('child-detached', {el: this});
  54663. }
  54664. },
  54665. load: {
  54666. value: function () {
  54667. var self = this;
  54668. if (this.hasLoaded || !this.parentEl) { return; }
  54669. ANode.prototype.load.call(this, function entityLoadCallback () {
  54670. // Check if entity was detached while it was waiting to load.
  54671. if (!self.parentEl) { return; }
  54672. self.updateComponents();
  54673. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  54674. });
  54675. },
  54676. writable: window.debug
  54677. },
  54678. /**
  54679. * Remove child entity.
  54680. *
  54681. * @param {Element} el - Child entity.
  54682. */
  54683. remove: {
  54684. value: function (el) {
  54685. if (el) {
  54686. this.object3D.remove(el.object3D);
  54687. } else {
  54688. this.parentNode.removeChild(this);
  54689. }
  54690. }
  54691. },
  54692. /**
  54693. * @returns {array} Direct children that are entities.
  54694. */
  54695. getChildEntities: {
  54696. value: function () {
  54697. var children = this.children;
  54698. var childEntities = [];
  54699. for (var i = 0; i < children.length; i++) {
  54700. var child = children[i];
  54701. if (child instanceof AEntity) {
  54702. childEntities.push(child);
  54703. }
  54704. }
  54705. return childEntities;
  54706. }
  54707. },
  54708. /**
  54709. * Initialize component.
  54710. *
  54711. * @param {string} attrName - Attribute name asociated to the component.
  54712. * @param {object} data - Component data
  54713. * @param {boolean} isDependency - True if the component is a dependency.
  54714. */
  54715. initComponent: {
  54716. value: function (attrName, data, isDependency) {
  54717. var component;
  54718. var componentId;
  54719. var componentInfo;
  54720. var componentName;
  54721. var isComponentDefined;
  54722. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  54723. componentName = componentInfo[0];
  54724. componentId = componentInfo.length > 2
  54725. ? componentInfo.slice(1).join('__')
  54726. : componentInfo[1];
  54727. // Not a registered component.
  54728. if (!COMPONENTS[componentName]) { return; }
  54729. // Component is not a dependency and is undefined.
  54730. // If a component is a dependency, then it is okay to have no data.
  54731. isComponentDefined = checkComponentDefined(this, attrName) ||
  54732. data !== undefined;
  54733. if (!isComponentDefined && !isDependency) { return; }
  54734. // Component already initialized.
  54735. if (attrName in this.components) { return; }
  54736. // Initialize dependencies first
  54737. this.initComponentDependencies(componentName);
  54738. // If component name has an id we check component type multiplic
  54739. if (componentId && !COMPONENTS[componentName].multiple) {
  54740. throw new Error('Trying to initialize multiple ' +
  54741. 'components of type `' + componentName +
  54742. '`. There can only be one component of this type per entity.');
  54743. }
  54744. component = new COMPONENTS[componentName].Component(this, data, componentId);
  54745. if (this.isPlaying) { component.play(); }
  54746. // Components are reflected in the DOM as attributes but the state is not shown
  54747. // hence we set the attribute to empty string.
  54748. // The flag justInitialized is for attributeChangedCallback to not overwrite
  54749. // the component with the empty string.
  54750. if (!this.hasAttribute(attrName)) {
  54751. component.justInitialized = true;
  54752. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  54753. }
  54754. debug('Component initialized: %s', attrName);
  54755. },
  54756. writable: window.debug
  54757. },
  54758. /**
  54759. * Initialize dependencies of a component.
  54760. *
  54761. * @param {string} name - Root component name.
  54762. */
  54763. initComponentDependencies: {
  54764. value: function (name) {
  54765. var self = this;
  54766. var component = COMPONENTS[name];
  54767. var dependencies;
  54768. var i;
  54769. // Not a component.
  54770. if (!component) { return; }
  54771. // No dependencies.
  54772. dependencies = COMPONENTS[name].dependencies;
  54773. if (!dependencies) { return; }
  54774. // Initialize dependencies.
  54775. for (i = 0; i < dependencies.length; i++) {
  54776. // Call getAttribute to initialize the data from the DOM.
  54777. self.initComponent(
  54778. dependencies[i],
  54779. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  54780. true
  54781. );
  54782. }
  54783. }
  54784. },
  54785. removeComponent: {
  54786. value: function (name, destroy) {
  54787. var component;
  54788. component = this.components[name];
  54789. if (!component) { return; }
  54790. // Wait for component to initialize.
  54791. if (!component.initialized) {
  54792. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  54793. if (evt.detail.name !== name) { return; }
  54794. this.removeComponent(name, destroy);
  54795. this.removeEventListener('componentinitialized', tryRemoveLater);
  54796. });
  54797. return;
  54798. }
  54799. component.pause();
  54800. component.remove();
  54801. // Keep component attached to entity in case of just full entity detach.
  54802. if (destroy) {
  54803. component.destroy();
  54804. delete this.components[name];
  54805. }
  54806. this.emit('componentremoved', component.evtDetail, false);
  54807. },
  54808. writable: window.debug
  54809. },
  54810. /**
  54811. * Initialize or update all components.
  54812. * Build data using initial components, defined attributes, mixins, and defaults.
  54813. * Update default components before the rest.
  54814. *
  54815. * @member {function} getExtraComponents - Can be implemented to include component data
  54816. * from other sources (e.g., implemented by primitives).
  54817. */
  54818. updateComponents: {
  54819. value: function () {
  54820. var data;
  54821. var extraComponents;
  54822. var i;
  54823. var name;
  54824. var componentsToUpdate = this.componentsToUpdate;
  54825. if (!this.hasLoaded) { return; }
  54826. // Gather mixin-defined components.
  54827. for (i = 0; i < this.mixinEls.length; i++) {
  54828. for (name in this.mixinEls[i].componentCache) {
  54829. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54830. }
  54831. }
  54832. // Gather from extra initial component data if defined (e.g., primitives).
  54833. if (this.getExtraComponents) {
  54834. extraComponents = this.getExtraComponents();
  54835. for (name in extraComponents) {
  54836. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54837. }
  54838. }
  54839. // Gather entity-defined components.
  54840. for (i = 0; i < this.attributes.length; ++i) {
  54841. name = this.attributes[i].name;
  54842. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  54843. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54844. }
  54845. // object3D components first (position, rotation, scale, visible).
  54846. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  54847. name = OBJECT3D_COMPONENTS[i];
  54848. if (!this.hasAttribute(name)) { continue; }
  54849. this.updateComponent(name, this.getDOMAttribute(name));
  54850. }
  54851. // Initialize or update rest of components.
  54852. for (name in componentsToUpdate) {
  54853. data = mergeComponentData(this.getDOMAttribute(name),
  54854. extraComponents && extraComponents[name]);
  54855. this.updateComponent(name, data);
  54856. delete componentsToUpdate[name];
  54857. }
  54858. },
  54859. writable: window.debug
  54860. },
  54861. /**
  54862. * Initialize, update, or remove a single component.
  54863. *
  54864. * When initializing, we set the component on `this.components`.
  54865. *
  54866. * @param {string} attr - Component name.
  54867. * @param {object} attrValue - Value of the DOM attribute.
  54868. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  54869. */
  54870. updateComponent: {
  54871. value: function (attr, attrValue, clobber) {
  54872. var component = this.components[attr];
  54873. if (component) {
  54874. // Remove component.
  54875. if (attrValue === null && !checkComponentDefined(this, attr)) {
  54876. this.removeComponent(attr, true);
  54877. return;
  54878. }
  54879. // Component already initialized. Update component.
  54880. component.updateProperties(attrValue, clobber);
  54881. return;
  54882. }
  54883. // Component not yet initialized. Initialize component.
  54884. this.initComponent(attr, attrValue, false);
  54885. }
  54886. },
  54887. /**
  54888. * If `attr` is a component name, detach the component from the entity.
  54889. *
  54890. * If `propertyName` is given, reset the component property value to its default.
  54891. *
  54892. * @param {string} attr - Attribute name, which could also be a component name.
  54893. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  54894. */
  54895. removeAttribute: {
  54896. value: function (attr, propertyName) {
  54897. var component = this.components[attr];
  54898. // Remove component.
  54899. if (component && propertyName === undefined) {
  54900. this.removeComponent(attr, true);
  54901. }
  54902. // Reset component property value.
  54903. if (component && propertyName !== undefined) {
  54904. component.resetProperty(propertyName);
  54905. return;
  54906. }
  54907. // Remove mixins.
  54908. if (attr === 'mixin') {
  54909. this.mixinUpdate('');
  54910. }
  54911. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  54912. }
  54913. },
  54914. /**
  54915. * Start dynamic behavior associated with entity such as dynamic components and animations.
  54916. * Tell all children entities to also play.
  54917. */
  54918. play: {
  54919. value: function () {
  54920. var entities;
  54921. var i;
  54922. var key;
  54923. // Already playing.
  54924. if (this.isPlaying || !this.hasLoaded) { return; }
  54925. this.isPlaying = true;
  54926. // Wake up all components.
  54927. for (key in this.components) { this.components[key].play(); }
  54928. // Tell all child entities to play.
  54929. entities = this.getChildEntities();
  54930. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  54931. this.emit('play');
  54932. },
  54933. writable: true
  54934. },
  54935. /**
  54936. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  54937. * Tell all children entities to also pause.
  54938. */
  54939. pause: {
  54940. value: function () {
  54941. var entities;
  54942. var i;
  54943. var key;
  54944. if (!this.isPlaying) { return; }
  54945. this.isPlaying = false;
  54946. // Sleep all components.
  54947. for (key in this.components) { this.components[key].pause(); }
  54948. // Tell all child entities to pause.
  54949. entities = this.getChildEntities();
  54950. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  54951. this.emit('pause');
  54952. },
  54953. writable: true
  54954. },
  54955. /**
  54956. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  54957. *
  54958. * @param {string} attr
  54959. * @param {string} oldVal
  54960. * @param {string|object} newVal
  54961. */
  54962. setEntityAttribute: {
  54963. value: function (attr, oldVal, newVal) {
  54964. if (COMPONENTS[attr] || this.components[attr]) {
  54965. this.updateComponent(attr, newVal);
  54966. return;
  54967. }
  54968. if (attr === 'mixin') {
  54969. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  54970. if (newVal === this.computedMixinStr) { return; }
  54971. this.mixinUpdate(newVal, oldVal);
  54972. }
  54973. }
  54974. },
  54975. /**
  54976. * When mixins updated, trigger init or optimized-update of relevant components.
  54977. */
  54978. mixinUpdate: {
  54979. value: (function () {
  54980. var componentsUpdated = [];
  54981. return function (newMixins, oldMixins) {
  54982. var component;
  54983. var mixinEl;
  54984. var mixinIds;
  54985. var i;
  54986. var self = this;
  54987. if (!this.hasLoaded) {
  54988. this.addEventListener('loaded', function () {
  54989. self.mixinUpdate(newMixins, oldMixins);
  54990. }, ONCE);
  54991. return;
  54992. }
  54993. oldMixins = oldMixins || this.getAttribute('mixin');
  54994. mixinIds = this.updateMixins(newMixins, oldMixins);
  54995. // Loop over current mixins.
  54996. componentsUpdated.length = 0;
  54997. for (i = 0; i < this.mixinEls.length; i++) {
  54998. for (component in this.mixinEls[i].componentCache) {
  54999. if (componentsUpdated.indexOf(component) === -1) {
  55000. if (this.components[component]) {
  55001. // Update. Just rebuild data.
  55002. this.components[component].handleMixinUpdate();
  55003. } else {
  55004. // Init. buildData will gather mixin values.
  55005. this.initComponent(component, null);
  55006. }
  55007. componentsUpdated.push(component);
  55008. }
  55009. }
  55010. }
  55011. // Loop over old mixins to call for data rebuild.
  55012. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  55013. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  55014. if (!mixinEl) { continue; }
  55015. for (component in mixinEl.componentCache) {
  55016. if (componentsUpdated.indexOf(component) === -1) {
  55017. if (this.components[component]) {
  55018. if (this.getDOMAttribute(component)) {
  55019. // Update component if explicitly defined.
  55020. this.components[component].handleMixinUpdate();
  55021. } else {
  55022. // Remove component if not explicitly defined.
  55023. this.removeComponent(component, true);
  55024. }
  55025. }
  55026. }
  55027. }
  55028. }
  55029. };
  55030. })()
  55031. },
  55032. /**
  55033. * setAttribute can:
  55034. *
  55035. * 1. Set a single property of a multi-property component.
  55036. * 2. Set multiple properties of a multi-property component.
  55037. * 3. Replace properties of a multi-property component.
  55038. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  55039. *
  55040. * @param {string} attrName - Component or attribute name.
  55041. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  55042. * object of properties.
  55043. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  55044. * it is a boolean indicating whether to clobber previous values (defaults to false).
  55045. */
  55046. setAttribute: {
  55047. value: (function () {
  55048. var singlePropUpdate = {};
  55049. return function (attrName, arg1, arg2) {
  55050. var newAttrValue;
  55051. var clobber;
  55052. var componentName;
  55053. var delimiterIndex;
  55054. var isDebugMode;
  55055. var key;
  55056. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  55057. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  55058. // Not a component. Normal set attribute.
  55059. if (!COMPONENTS[componentName]) {
  55060. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  55061. ANode.prototype.setAttribute.call(this, attrName, arg1);
  55062. return;
  55063. }
  55064. // Initialize component first if not yet initialized.
  55065. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  55066. this.updateComponent(
  55067. attrName,
  55068. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  55069. }
  55070. // Determine new attributes from the arguments
  55071. if (typeof arg2 !== 'undefined' &&
  55072. typeof arg1 === 'string' &&
  55073. arg1.length > 0 &&
  55074. typeof utils.styleParser.parse(arg1) === 'string') {
  55075. // Update a single property of a multi-property component
  55076. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  55077. newAttrValue = singlePropUpdate;
  55078. newAttrValue[arg1] = arg2;
  55079. clobber = false;
  55080. } else {
  55081. // Update with a value, object, or CSS-style property string, with the possiblity
  55082. // of clobbering previous values.
  55083. newAttrValue = arg1;
  55084. clobber = (arg2 === true);
  55085. }
  55086. // Update component
  55087. this.updateComponent(attrName, newAttrValue, clobber);
  55088. // In debug mode, write component data up to the DOM.
  55089. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  55090. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  55091. };
  55092. })(),
  55093. writable: window.debug
  55094. },
  55095. /**
  55096. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  55097. *
  55098. * @param {bool} recursive - Also flushToDOM on the children.
  55099. **/
  55100. flushToDOM: {
  55101. value: function (recursive) {
  55102. var components = this.components;
  55103. var child;
  55104. var children = this.children;
  55105. var i;
  55106. var key;
  55107. // Flush entity's components to DOM.
  55108. for (key in components) {
  55109. components[key].flushToDOM();
  55110. }
  55111. // Recurse.
  55112. if (!recursive) { return; }
  55113. for (i = 0; i < children.length; ++i) {
  55114. child = children[i];
  55115. if (!child.flushToDOM) { continue; }
  55116. child.flushToDOM(recursive);
  55117. }
  55118. }
  55119. },
  55120. /**
  55121. * If `attr` is a component, returns ALL component data including applied mixins and
  55122. * defaults.
  55123. *
  55124. * If `attr` is not a component, fall back to HTML getAttribute.
  55125. *
  55126. * @param {string} attr
  55127. * @returns {object|string} Object if component, else string.
  55128. */
  55129. getAttribute: {
  55130. value: function (attr) {
  55131. // If component, return component data.
  55132. var component;
  55133. if (attr === 'position') { return this.object3D.position; }
  55134. if (attr === 'rotation') { return getRotation(this); }
  55135. if (attr === 'scale') { return this.object3D.scale; }
  55136. if (attr === 'visible') { return this.object3D.visible; }
  55137. component = this.components[attr];
  55138. if (component) { return component.data; }
  55139. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  55140. },
  55141. writable: window.debug
  55142. },
  55143. /**
  55144. * If `attr` is a component, returns JUST the component data defined on the entity.
  55145. * Like a partial version of `getComputedAttribute` as returned component data
  55146. * does not include applied mixins or defaults.
  55147. *
  55148. * If `attr` is not a component, fall back to HTML getAttribute.
  55149. *
  55150. * @param {string} attr
  55151. * @returns {object|string} Object if component, else string.
  55152. */
  55153. getDOMAttribute: {
  55154. value: function (attr) {
  55155. // If cached value exists, return partial component data.
  55156. var component = this.components[attr];
  55157. if (component) { return component.attrValue; }
  55158. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  55159. },
  55160. writable: window.debug
  55161. },
  55162. addState: {
  55163. value: function (state) {
  55164. if (this.is(state)) { return; }
  55165. this.states.push(state);
  55166. this.emit('stateadded', state);
  55167. }
  55168. },
  55169. removeState: {
  55170. value: function (state) {
  55171. var stateIndex = this.states.indexOf(state);
  55172. if (stateIndex === -1) { return; }
  55173. this.states.splice(stateIndex, 1);
  55174. this.emit('stateremoved', state);
  55175. }
  55176. },
  55177. /**
  55178. * Checks if the element is in a given state. e.g. el.is('alive');
  55179. * @type {string} state - Name of the state we want to check
  55180. */
  55181. is: {
  55182. value: function (state) {
  55183. return this.states.indexOf(state) !== -1;
  55184. }
  55185. },
  55186. /**
  55187. * Open Inspector to this entity.
  55188. */
  55189. inspect: {
  55190. value: function () {
  55191. this.sceneEl.components.inspector.openInspector(this);
  55192. }
  55193. },
  55194. /**
  55195. * Clean up memory and return memory to object pools.
  55196. */
  55197. destroy: {
  55198. value: function () {
  55199. var key;
  55200. if (this.parentNode) {
  55201. warn('Entity can only be destroyed if detached from scenegraph.');
  55202. return;
  55203. }
  55204. for (key in this.components) {
  55205. this.components[key].destroy();
  55206. }
  55207. }
  55208. }
  55209. });
  55210. /**
  55211. * Check if a component is *defined* for an entity, including defaults and mixins.
  55212. * Does not check whether the component has been *initialized* for an entity.
  55213. *
  55214. * @param {string} el - Entity.
  55215. * @param {string} name - Component name.
  55216. * @returns {boolean}
  55217. */
  55218. function checkComponentDefined (el, name) {
  55219. // Check if element contains the component.
  55220. if (el.components[name] && el.components[name].attrValue) { return true; }
  55221. return isComponentMixedIn(name, el.mixinEls);
  55222. }
  55223. /**
  55224. * Check if any mixins contains a component.
  55225. *
  55226. * @param {string} name - Component name.
  55227. * @param {array} mixinEls - Array of <a-mixin>s.
  55228. */
  55229. function isComponentMixedIn (name, mixinEls) {
  55230. var i;
  55231. var inMixin = false;
  55232. for (i = 0; i < mixinEls.length; ++i) {
  55233. inMixin = mixinEls[i].hasAttribute(name);
  55234. if (inMixin) { break; }
  55235. }
  55236. return inMixin;
  55237. }
  55238. /**
  55239. * Given entity defined value, merge in extra data if necessary.
  55240. * Handle both single and multi-property components.
  55241. *
  55242. * @param {string} attrValue - Entity data.
  55243. * @param extraData - Entity data from another source to merge in.
  55244. */
  55245. function mergeComponentData (attrValue, extraData) {
  55246. // Extra data not defined, just return attrValue.
  55247. if (!extraData) { return attrValue; }
  55248. // Merge multi-property data.
  55249. if (extraData.constructor === Object) {
  55250. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  55251. }
  55252. // Return data, precendence to the defined value.
  55253. return attrValue || extraData;
  55254. }
  55255. function isComponent (componentName) {
  55256. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  55257. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  55258. }
  55259. if (!COMPONENTS[componentName]) { return false; }
  55260. return true;
  55261. }
  55262. function getRotation (entityEl) {
  55263. var radToDeg = THREE.Math.radToDeg;
  55264. var rotation = entityEl.object3D.rotation;
  55265. var rotationObj = entityEl.rotationObj;
  55266. rotationObj.x = radToDeg(rotation.x);
  55267. rotationObj.y = radToDeg(rotation.y);
  55268. rotationObj.z = radToDeg(rotation.z);
  55269. return rotationObj;
  55270. }
  55271. AEntity = registerElement('a-entity', {prototype: proto});
  55272. module.exports = AEntity;
  55273. },{"../lib/three":180,"../utils/":206,"./a-node":130,"./a-register-element":131,"./component":132}],129:[function(_dereq_,module,exports){
  55274. var ANode = _dereq_('./a-node');
  55275. var registerElement = _dereq_('./a-register-element').registerElement;
  55276. var components = _dereq_('./component').components;
  55277. var utils = _dereq_('../utils');
  55278. var MULTIPLE_COMPONENT_DELIMITER = '__';
  55279. /**
  55280. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  55281. * are component names and the values are already parsed by the component.
  55282. */
  55283. module.exports = registerElement('a-mixin', {
  55284. prototype: Object.create(ANode.prototype, {
  55285. createdCallback: {
  55286. value: function () {
  55287. this.componentCache = {};
  55288. this.id = this.getAttribute('id');
  55289. this.isMixin = true;
  55290. }
  55291. },
  55292. attributeChangedCallback: {
  55293. value: function (attr, oldVal, newVal) {
  55294. this.cacheAttribute(attr, newVal);
  55295. this.updateEntities();
  55296. }
  55297. },
  55298. attachedCallback: {
  55299. value: function () {
  55300. this.sceneEl = this.closestScene();
  55301. this.cacheAttributes();
  55302. this.updateEntities();
  55303. this.load();
  55304. }
  55305. },
  55306. /**
  55307. * setAttribute that parses and caches component values.
  55308. */
  55309. setAttribute: {
  55310. value: function (attr, value) {
  55311. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  55312. this.cacheAttribute(attr, value);
  55313. }
  55314. },
  55315. /**
  55316. * If `attr` is a component, then parse the value using the schema and store it.
  55317. */
  55318. cacheAttribute: {
  55319. value: function (attr, value) {
  55320. var component;
  55321. var componentName;
  55322. // Get component data.
  55323. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  55324. component = components[componentName];
  55325. if (!component) { return; }
  55326. if (value === undefined) {
  55327. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  55328. }
  55329. this.componentCache[attr] = component.parseAttrValueForCache(value);
  55330. }
  55331. },
  55332. /**
  55333. * If `attr` is a component, then grab pre-parsed value from the cache.
  55334. * Else do a normal getAttribute.
  55335. */
  55336. getAttribute: {
  55337. value: function (attr) {
  55338. return this.componentCache[attr] ||
  55339. window.HTMLElement.prototype.getAttribute.call(this, attr);
  55340. }
  55341. },
  55342. /**
  55343. * Parse and cache every component defined on the mixin.
  55344. */
  55345. cacheAttributes: {
  55346. value: function () {
  55347. var attributes = this.attributes;
  55348. var attrName;
  55349. var i;
  55350. for (i = 0; i < attributes.length; i++) {
  55351. attrName = attributes[i].name;
  55352. this.cacheAttribute(attrName);
  55353. }
  55354. }
  55355. },
  55356. /**
  55357. * For entities that already have been loaded by the time the mixin was attached, tell
  55358. * those entities to register the mixin and refresh their component data.
  55359. */
  55360. updateEntities: {
  55361. value: function () {
  55362. var entity;
  55363. var entities;
  55364. var i;
  55365. if (!this.sceneEl) { return; }
  55366. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  55367. for (i = 0; i < entities.length; i++) {
  55368. entity = entities[i];
  55369. if (!entity.hasLoaded || entity.isMixin) { continue; }
  55370. entity.mixinUpdate(this.id);
  55371. }
  55372. }
  55373. }
  55374. })
  55375. });
  55376. },{"../utils":206,"./a-node":130,"./a-register-element":131,"./component":132}],130:[function(_dereq_,module,exports){
  55377. /* global CustomEvent */
  55378. var registerElement = _dereq_('./a-register-element').registerElement;
  55379. var isNode = _dereq_('./a-register-element').isNode;
  55380. var utils = _dereq_('../utils/');
  55381. var warn = utils.debug('core:a-node:warn');
  55382. var error = utils.debug('core:a-node:error');
  55383. /**
  55384. * Base class for A-Frame that manages loading of objects.
  55385. *
  55386. * Nodes can be modified using mixins.
  55387. * Nodes emit a `loaded` event when they and their children have initialized.
  55388. */
  55389. module.exports = registerElement('a-node', {
  55390. prototype: Object.create(window.HTMLElement.prototype, {
  55391. createdCallback: {
  55392. value: function () {
  55393. this.computedMixinStr = '';
  55394. this.hasLoaded = false;
  55395. this.isNode = true;
  55396. this.mixinEls = [];
  55397. },
  55398. writable: window.debug
  55399. },
  55400. attachedCallback: {
  55401. value: function () {
  55402. var mixins;
  55403. this.sceneEl = this.closestScene();
  55404. if (!this.sceneEl) {
  55405. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  55406. 'scene. Append this element to `<a-scene>` instead.');
  55407. }
  55408. this.hasLoaded = false;
  55409. this.emit('nodeready', undefined, false);
  55410. if (!this.isMixin) {
  55411. mixins = this.getAttribute('mixin');
  55412. if (mixins) { this.updateMixins(mixins); }
  55413. }
  55414. },
  55415. writable: window.debug
  55416. },
  55417. /**
  55418. * Handle mixin.
  55419. */
  55420. attributeChangedCallback: {
  55421. value: function (attr, oldVal, newVal) {
  55422. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  55423. if (newVal === this.computedMixinStr) { return; }
  55424. if (attr === 'mixin' && !this.isMixin) {
  55425. this.updateMixins(newVal, oldVal);
  55426. }
  55427. }
  55428. },
  55429. /**
  55430. * Returns the first scene by traversing up the tree starting from and
  55431. * including receiver element.
  55432. */
  55433. closestScene: {
  55434. value: function closest () {
  55435. var element = this;
  55436. while (element) {
  55437. if (element.isScene) { break; }
  55438. element = element.parentElement;
  55439. }
  55440. return element;
  55441. }
  55442. },
  55443. /**
  55444. * Returns first element matching a selector by traversing up the tree starting
  55445. * from and including receiver element.
  55446. *
  55447. * @param {string} selector - Selector of element to find.
  55448. */
  55449. closest: {
  55450. value: function closest (selector) {
  55451. var matches = this.matches || this.mozMatchesSelector ||
  55452. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  55453. var element = this;
  55454. while (element) {
  55455. if (matches.call(element, selector)) { break; }
  55456. element = element.parentElement;
  55457. }
  55458. return element;
  55459. }
  55460. },
  55461. detachedCallback: {
  55462. value: function () {
  55463. this.hasLoaded = false;
  55464. }
  55465. },
  55466. /**
  55467. * Wait for children to load, if any.
  55468. * Then emit `loaded` event and set `hasLoaded`.
  55469. */
  55470. load: {
  55471. value: function (cb, childFilter) {
  55472. var children;
  55473. var childrenLoaded;
  55474. var self = this;
  55475. if (this.hasLoaded) { return; }
  55476. // Default to waiting for all nodes.
  55477. childFilter = childFilter || isNode;
  55478. // Wait for children to load (if any), then load.
  55479. children = this.getChildren();
  55480. childrenLoaded = children.filter(childFilter).map(function (child) {
  55481. return new Promise(function waitForLoaded (resolve) {
  55482. if (child.hasLoaded) { return resolve(); }
  55483. child.addEventListener('loaded', resolve);
  55484. });
  55485. });
  55486. Promise.all(childrenLoaded).then(function emitLoaded () {
  55487. self.hasLoaded = true;
  55488. if (cb) { cb(); }
  55489. self.emit('loaded', undefined, false);
  55490. }).catch(function (err) {
  55491. error('Failure loading node: ', err);
  55492. });
  55493. },
  55494. writable: true
  55495. },
  55496. getChildren: {
  55497. value: function () {
  55498. return Array.prototype.slice.call(this.children, 0);
  55499. }
  55500. },
  55501. /**
  55502. * Unregister old mixins and listeners.
  55503. * Register new mixins and listeners.
  55504. * Registering means to update `this.mixinEls` with listeners.
  55505. */
  55506. updateMixins: {
  55507. value: (function () {
  55508. var newMixinIdArray = [];
  55509. var oldMixinIdArray = [];
  55510. var mixinIds = {};
  55511. return function (newMixins, oldMixins) {
  55512. var i;
  55513. var newMixinIds;
  55514. var oldMixinIds;
  55515. newMixinIdArray.length = 0;
  55516. oldMixinIdArray.length = 0;
  55517. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  55518. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  55519. mixinIds.newMixinIds = newMixinIds;
  55520. mixinIds.oldMixinIds = oldMixinIds;
  55521. // Unregister old mixins.
  55522. for (i = 0; i < oldMixinIds.length; i++) {
  55523. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  55524. this.unregisterMixin(oldMixinIds[i]);
  55525. }
  55526. }
  55527. // Register new mixins.
  55528. this.computedMixinStr = '';
  55529. this.mixinEls.length = 0;
  55530. for (i = 0; i < newMixinIds.length; i++) {
  55531. this.registerMixin(document.getElementById(newMixinIds[i]));
  55532. }
  55533. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  55534. // update.
  55535. if (this.computedMixinStr) {
  55536. this.computedMixinStr = this.computedMixinStr.trim();
  55537. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  55538. this.computedMixinStr);
  55539. }
  55540. return mixinIds;
  55541. };
  55542. })()
  55543. },
  55544. /**
  55545. * From mixin ID, add mixin element to `mixinEls`.
  55546. *
  55547. * @param {Element} mixinEl
  55548. */
  55549. registerMixin: {
  55550. value: function (mixinEl) {
  55551. var compositedMixinIds;
  55552. var i;
  55553. var mixin;
  55554. if (!mixinEl) { return; }
  55555. // Register composited mixins (if mixin has mixins).
  55556. mixin = mixinEl.getAttribute('mixin');
  55557. if (mixin) {
  55558. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  55559. for (i = 0; i < compositedMixinIds.length; i++) {
  55560. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  55561. }
  55562. }
  55563. // Register mixin.
  55564. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  55565. this.mixinEls.push(mixinEl);
  55566. }
  55567. },
  55568. setAttribute: {
  55569. value: function (attr, newValue) {
  55570. if (attr === 'mixin') { this.updateMixins(newValue); }
  55571. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  55572. }
  55573. },
  55574. unregisterMixin: {
  55575. value: function (mixinId) {
  55576. var i;
  55577. var mixinEls = this.mixinEls;
  55578. var mixinEl;
  55579. for (i = 0; i < mixinEls.length; ++i) {
  55580. mixinEl = mixinEls[i];
  55581. if (mixinId === mixinEl.id) {
  55582. mixinEls.splice(i, 1);
  55583. break;
  55584. }
  55585. }
  55586. }
  55587. },
  55588. /**
  55589. * Emit a DOM event.
  55590. *
  55591. * @param {string} name - Name of event.
  55592. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  55593. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  55594. * @param {object} [extraData] - Extra data to pass to the event, if any.
  55595. */
  55596. emit: {
  55597. value: (function () {
  55598. var data = {};
  55599. return function (name, detail, bubbles, extraData) {
  55600. if (bubbles === undefined) { bubbles = true; }
  55601. data.bubbles = !!bubbles;
  55602. data.detail = detail;
  55603. // If extra data is present, we need to create a new object.
  55604. if (extraData) { data = utils.extend({}, extraData, data); }
  55605. this.dispatchEvent(new CustomEvent(name, data));
  55606. };
  55607. })(),
  55608. writable: window.debug
  55609. }
  55610. })
  55611. });
  55612. },{"../utils/":206,"./a-register-element":131}],131:[function(_dereq_,module,exports){
  55613. /*
  55614. ------------------------------------------------------------
  55615. ------------- WARNING WARNING WARNING WARNING --------------
  55616. ------------------------------------------------------------
  55617. This module wraps registerElement to deal with components that inherit from
  55618. `ANode` and `AEntity`. It's a pass through in any other case.
  55619. It wraps some of the prototype methods of the created element to make sure
  55620. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  55621. are also invoked. The method in the base prototype is always called before the one
  55622. in the derived prototype.
  55623. */
  55624. // Polyfill `document.registerElement`.
  55625. _dereq_('document-register-element');
  55626. var ANode; // Must declare before AEntity. Initialized at the bottom.
  55627. var AEntity;
  55628. var knownTags = module.exports.knownTags = {};
  55629. function addTagName (tagName) {
  55630. knownTags[tagName.toLowerCase()] = true;
  55631. }
  55632. /**
  55633. * Return whether the element type is one of our known registered ones.
  55634. *
  55635. * @param {string} node - The name of the tag to register.
  55636. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  55637. */
  55638. module.exports.isNode = function (node) {
  55639. return node.tagName.toLowerCase() in knownTags || node.isNode;
  55640. };
  55641. /**
  55642. * @param {string} tagName - The name of the tag to register.
  55643. * @param {object} obj - The prototype of the new element.
  55644. * @returns {object} The prototype of the new element.
  55645. */
  55646. module.exports.registerElement = function (tagName, obj) {
  55647. var proto = Object.getPrototypeOf(obj.prototype);
  55648. var newObj = obj;
  55649. var isANode = ANode && proto === ANode.prototype;
  55650. var isAEntity = AEntity && proto === AEntity.prototype;
  55651. if (isANode || isAEntity) { addTagName(tagName); }
  55652. // Wrap if element inherits from `ANode`.
  55653. if (isANode) {
  55654. newObj = wrapANodeMethods(obj.prototype);
  55655. newObj = {prototype: Object.create(proto, newObj)};
  55656. }
  55657. // Wrap if element inherits from `AEntity`.
  55658. if (isAEntity) {
  55659. newObj = wrapAEntityMethods(obj.prototype);
  55660. newObj = {prototype: Object.create(proto, newObj)};
  55661. }
  55662. // Give all functions their proper name.
  55663. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  55664. var propVal = newObj.prototype[propName];
  55665. if (typeof propVal === 'function') {
  55666. propVal.displayName = propName;
  55667. }
  55668. });
  55669. return document.registerElement(tagName, newObj);
  55670. };
  55671. /**
  55672. * Wrap some obj methods to call those on `ANode` base prototype.
  55673. *
  55674. * @param {object} obj - Object that contains the methods that will be wrapped.
  55675. * @return {object} An object with the same properties as the input parameter but
  55676. * with some of methods wrapped.
  55677. */
  55678. function wrapANodeMethods (obj) {
  55679. var newObj = {};
  55680. var ANodeMethods = [
  55681. 'attachedCallback',
  55682. 'attributeChangedCallback',
  55683. 'createdCallback',
  55684. 'detachedCallback'
  55685. ];
  55686. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55687. copyProperties(obj, newObj);
  55688. return newObj;
  55689. }
  55690. /**
  55691. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  55692. *
  55693. * @param {object} obj - The objects that contains the methods that will be wrapped.
  55694. * @return {object} - An object with the same properties as the input parameter but
  55695. * with some of methods wrapped.
  55696. */
  55697. function wrapAEntityMethods (obj) {
  55698. var newObj = {};
  55699. var ANodeMethods = [
  55700. 'attachedCallback',
  55701. 'attributeChangedCallback',
  55702. 'createdCallback',
  55703. 'detachedCallback'
  55704. ];
  55705. var AEntityMethods = [
  55706. 'attachedCallback',
  55707. 'attributeChangedCallback',
  55708. 'createdCallback',
  55709. 'detachedCallback'
  55710. ];
  55711. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55712. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  55713. // Copies the remaining properties into the new object.
  55714. copyProperties(obj, newObj);
  55715. return newObj;
  55716. }
  55717. /**
  55718. * Wrap a list a methods to ensure that those in the base prototype are called
  55719. * before the derived one.
  55720. *
  55721. * @param {object} targetObj - Object that will contain the wrapped methods.
  55722. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  55723. * @param {object} derivedObject - Object that inherits from the baseObj.
  55724. * @param {object} baseObj - Object that derivedObj inherits from.
  55725. */
  55726. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  55727. methodList.forEach(function (methodName) {
  55728. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  55729. });
  55730. }
  55731. module.exports.wrapMethods = wrapMethods;
  55732. /**
  55733. * Wrap one method to ensure that the one in the base prototype is called before
  55734. * the one in the derived one.
  55735. *
  55736. * @param {object} obj - Object that will contain the wrapped method.
  55737. * @param {string} methodName - The name of the method that will be wrapped.
  55738. * @param {object} derivedObject - Object that inherits from the baseObj.
  55739. * @param {object} baseObj - Object that derivedObj inherits from.
  55740. */
  55741. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  55742. var derivedMethod = derivedObj[methodName];
  55743. var baseMethod = baseObj[methodName];
  55744. // Derived prototype does not define method, no need to wrap.
  55745. if (!derivedMethod || !baseMethod) { return; }
  55746. // Derived prototype doesn't override the one in the base one, no need to wrap.
  55747. if (derivedMethod === baseMethod) { return; }
  55748. // Wrap to ensure the base method is called before the one in the derived prototype.
  55749. obj[methodName] = {
  55750. value: function wrappedMethod () {
  55751. baseMethod.apply(this, arguments);
  55752. return derivedMethod.apply(this, arguments);
  55753. },
  55754. writable: window.debug
  55755. };
  55756. }
  55757. /**
  55758. * It copies the properties from source to destination object if they don't
  55759. * exist already.
  55760. *
  55761. * @param {object} source - The object where properties are copied from.
  55762. * @param {type} destination - The object where properties are copied to.
  55763. */
  55764. function copyProperties (source, destination) {
  55765. var props = Object.getOwnPropertyNames(source);
  55766. props.forEach(function (prop) {
  55767. var desc;
  55768. if (!destination[prop]) {
  55769. desc = Object.getOwnPropertyDescriptor(source, prop);
  55770. destination[prop] = {value: source[prop], writable: desc.writable};
  55771. }
  55772. });
  55773. }
  55774. ANode = _dereq_('./a-node');
  55775. AEntity = _dereq_('./a-entity');
  55776. },{"./a-entity":128,"./a-node":130,"document-register-element":12}],132:[function(_dereq_,module,exports){
  55777. /* global Node */
  55778. var schema = _dereq_('./schema');
  55779. var scenes = _dereq_('./scene/scenes');
  55780. var systems = _dereq_('./system');
  55781. var utils = _dereq_('../utils/');
  55782. var components = module.exports.components = {}; // Keep track of registered components.
  55783. var parseProperties = schema.parseProperties;
  55784. var parseProperty = schema.parseProperty;
  55785. var processSchema = schema.process;
  55786. var isSingleProp = schema.isSingleProperty;
  55787. var stringifyProperties = schema.stringifyProperties;
  55788. var stringifyProperty = schema.stringifyProperty;
  55789. var styleParser = utils.styleParser;
  55790. var warn = utils.debug('core:component:warn');
  55791. var aframeScript = document.currentScript;
  55792. var upperCaseRegExp = new RegExp('[A-Z]+');
  55793. // Object pools by component, created upon registration.
  55794. var objectPools = {};
  55795. /**
  55796. * Component class definition.
  55797. *
  55798. * Components configure appearance, modify behavior, or add functionality to
  55799. * entities. The behavior and appearance of an entity can be changed at runtime
  55800. * by adding, removing, or updating components. Entities do not share instances
  55801. * of components.
  55802. *
  55803. * @member {object} el - Reference to the entity element.
  55804. * @member {string} attrValue - Value of the corresponding HTML attribute.
  55805. * @member {object} data - Component data populated by parsing the
  55806. * mapped attribute of the component plus applying defaults and mixins.
  55807. */
  55808. var Component = module.exports.Component = function (el, attrValue, id) {
  55809. var self = this;
  55810. this.el = el;
  55811. this.id = id;
  55812. this.attrName = this.name + (id ? '__' + id : '');
  55813. this.evtDetail = {id: this.id, name: this.name};
  55814. this.initialized = false;
  55815. this.isSingleProperty = isSingleProp(this.schema);
  55816. this.isSinglePropertyObject = this.isSingleProperty &&
  55817. isObject(parseProperty(undefined, this.schema)) &&
  55818. !(this.schema.default instanceof window.HTMLElement);
  55819. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  55820. this.el.components[this.attrName] = this;
  55821. this.objectPool = objectPools[this.name];
  55822. const events = this.events;
  55823. this.events = {};
  55824. eventsBind(this, events);
  55825. // Store component data from previous update call.
  55826. this.attrValue = undefined;
  55827. if (this.isObjectBased) {
  55828. this.nextData = this.objectPool.use();
  55829. // Drop any properties added by dynamic schemas in previous use
  55830. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  55831. this.oldData = this.objectPool.use();
  55832. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  55833. this.previousOldData = this.objectPool.use();
  55834. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  55835. this.parsingAttrValue = this.objectPool.use();
  55836. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  55837. } else {
  55838. this.nextData = undefined;
  55839. this.oldData = undefined;
  55840. this.previousOldData = undefined;
  55841. this.parsingAttrValue = undefined;
  55842. }
  55843. // Last value passed to updateProperties.
  55844. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  55845. el.emit('componentchanged', self.evtDetail, false);
  55846. }, 200);
  55847. this.updateProperties(attrValue);
  55848. };
  55849. Component.prototype = {
  55850. /**
  55851. * Contains the type schema and defaults for the data values.
  55852. * Data is coerced into the types of the values of the defaults.
  55853. */
  55854. schema: {},
  55855. /**
  55856. * Init handler. Similar to attachedCallback.
  55857. * Called during component initialization and is only run once.
  55858. * Components can use this to set initial state.
  55859. */
  55860. init: function () { /* no-op */ },
  55861. /**
  55862. * Map of event names to binded event handlers that will be lifecycle-handled.
  55863. * Will be detached on pause / remove.
  55864. * Will be attached on play.
  55865. */
  55866. events: {},
  55867. /**
  55868. * Update handler. Similar to attributeChangedCallback.
  55869. * Called whenever component's data changes.
  55870. * Also called on component initialization when the component receives initial data.
  55871. *
  55872. * @param {object} prevData - Previous attributes of the component.
  55873. */
  55874. update: function (prevData) { /* no-op */ },
  55875. updateSchema: undefined,
  55876. /**
  55877. * Tick handler.
  55878. * Called on each tick of the scene render loop.
  55879. * Affected by play and pause.
  55880. *
  55881. * @param {number} time - Scene tick time.
  55882. * @param {number} timeDelta - Difference in current render time and previous render time.
  55883. */
  55884. tick: undefined,
  55885. /**
  55886. * Tock handler.
  55887. * Called on each tock of the scene render loop.
  55888. * Affected by play and pause.
  55889. *
  55890. * @param {number} time - Scene tick time.
  55891. * @param {number} timeDelta - Difference in current render time and previous render time.
  55892. * @param {object} camera - Camera used to render the last frame.
  55893. */
  55894. tock: undefined,
  55895. /**
  55896. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  55897. */
  55898. play: function () { /* no-op */ },
  55899. /**
  55900. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  55901. */
  55902. pause: function () { /* no-op */ },
  55903. /**
  55904. * Remove handler. Similar to detachedCallback.
  55905. * Called whenever component is removed from the entity (i.e., removeAttribute).
  55906. * Components can use this to reset behavior on the entity.
  55907. */
  55908. remove: function () { /* no-op */ },
  55909. /**
  55910. * Parses each property based on property type.
  55911. * If component is single-property, then parses the single property value.
  55912. *
  55913. * @param {string} value - HTML attribute value.
  55914. * @param {boolean} silent - Suppress warning messages.
  55915. * @returns {object} Component data.
  55916. */
  55917. parse: function (value, silent) {
  55918. var schema = this.schema;
  55919. if (this.isSingleProperty) { return parseProperty(value, schema); }
  55920. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  55921. },
  55922. /**
  55923. * Stringify properties if necessary.
  55924. *
  55925. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  55926. * value (e.g., selector, vec3 property types).
  55927. *
  55928. * @param {object} data - Complete component data.
  55929. * @returns {string}
  55930. */
  55931. stringify: function (data) {
  55932. var schema = this.schema;
  55933. if (typeof data === 'string') { return data; }
  55934. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  55935. data = stringifyProperties(data, schema);
  55936. return styleParser.stringify(data);
  55937. },
  55938. /**
  55939. * Update the cache of the pre-parsed attribute value.
  55940. *
  55941. * @param {string} value - New data.
  55942. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  55943. */
  55944. updateCachedAttrValue: function (value, clobber) {
  55945. var newAttrValue;
  55946. var tempObject;
  55947. var property;
  55948. if (value === undefined) { return; }
  55949. // If null value is the new attribute value, make the attribute value falsy.
  55950. if (value === null) {
  55951. if (this.isObjectBased && this.attrValue) {
  55952. this.objectPool.recycle(this.attrValue);
  55953. }
  55954. this.attrValue = undefined;
  55955. return;
  55956. }
  55957. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  55958. // If value is an object, copy it to our pooled newAttrValue object to use to update
  55959. // the attrValue.
  55960. tempObject = this.objectPool.use();
  55961. newAttrValue = utils.extend(tempObject, value);
  55962. } else {
  55963. newAttrValue = this.parseAttrValueForCache(value);
  55964. }
  55965. // Merge new data with previous `attrValue` if updating and not clobbering.
  55966. if (this.isObjectBased && !clobber && this.attrValue) {
  55967. for (property in this.attrValue) {
  55968. if (newAttrValue[property] === undefined) {
  55969. newAttrValue[property] = this.attrValue[property];
  55970. }
  55971. }
  55972. }
  55973. // Update attrValue.
  55974. if (this.isObjectBased && !this.attrValue) {
  55975. this.attrValue = this.objectPool.use();
  55976. }
  55977. utils.objectPool.clearObject(this.attrValue);
  55978. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  55979. utils.objectPool.clearObject(tempObject);
  55980. },
  55981. /**
  55982. * Given an HTML attribute value parses the string based on the component schema.
  55983. * To avoid double parsings of strings into strings we store the original instead
  55984. * of the parsed one
  55985. *
  55986. * @param {string} value - HTML attribute value
  55987. */
  55988. parseAttrValueForCache: function (value) {
  55989. var parsedValue;
  55990. if (typeof value !== 'string') { return value; }
  55991. if (this.isSingleProperty) {
  55992. parsedValue = this.schema.parse(value);
  55993. /**
  55994. * To avoid bogus double parsings. Cached values will be parsed when building
  55995. * component data. For instance when parsing a src id to its url, we want to cache
  55996. * original string and not the parsed one (#monster -> models/monster.dae)
  55997. * so when building data we parse the expected value.
  55998. */
  55999. if (typeof parsedValue === 'string') { parsedValue = value; }
  56000. } else {
  56001. // Parse using the style parser to avoid double parsing of individual properties.
  56002. utils.objectPool.clearObject(this.parsingAttrValue);
  56003. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  56004. }
  56005. return parsedValue;
  56006. },
  56007. /**
  56008. * Write cached attribute data to the entity DOM element.
  56009. *
  56010. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  56011. * default components.
  56012. */
  56013. flushToDOM: function (isDefault) {
  56014. var attrValue = isDefault ? this.data : this.attrValue;
  56015. if (attrValue === null || attrValue === undefined) { return; }
  56016. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  56017. this.stringify(attrValue));
  56018. },
  56019. /**
  56020. * Apply new component data if data has changed (from setAttribute).
  56021. *
  56022. * @param {string} attrValue - HTML attribute value.
  56023. * If undefined, use the cached attribute value and continue updating properties.
  56024. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  56025. */
  56026. updateProperties: function (attrValue, clobber) {
  56027. var el = this.el;
  56028. // Just cache the attribute if the entity has not loaded
  56029. // Components are not initialized until the entity has loaded
  56030. if (!el.hasLoaded) {
  56031. this.updateCachedAttrValue(attrValue);
  56032. return;
  56033. }
  56034. // Parse the attribute value.
  56035. // Cache current attrValue for future updates. Updates `this.attrValue`.
  56036. // `null` means no value on purpose, do not set a default value, let mixins take over.
  56037. if (attrValue !== null) {
  56038. attrValue = this.parseAttrValueForCache(attrValue);
  56039. }
  56040. // Cache current attrValue for future updates.
  56041. this.updateCachedAttrValue(attrValue, clobber);
  56042. if (this.initialized) {
  56043. this.updateComponent(attrValue, clobber);
  56044. this.callUpdateHandler();
  56045. } else {
  56046. this.initComponent();
  56047. }
  56048. },
  56049. initComponent: function () {
  56050. var el = this.el;
  56051. var initialOldData;
  56052. // Build data.
  56053. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  56054. this.data = this.buildData(this.attrValue);
  56055. // Component is being already initialized.
  56056. if (el.initializingComponents[this.name]) { return; }
  56057. // Prevent infinite loop in case of init method setting same component on the entity.
  56058. el.initializingComponents[this.name] = true;
  56059. // Initialize component.
  56060. this.init();
  56061. this.initialized = true;
  56062. delete el.initializingComponents[this.name];
  56063. // Store current data as previous data for future updates.
  56064. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  56065. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  56066. // Pass undefined to rest of types.
  56067. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  56068. this.update(initialOldData);
  56069. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  56070. // Play the component if the entity is playing.
  56071. if (el.isPlaying) { this.play(); }
  56072. el.emit('componentinitialized', this.evtDetail, false);
  56073. },
  56074. /**
  56075. * @param attrValue - Passed argument from setAttribute.
  56076. */
  56077. updateComponent: function (attrValue, clobber) {
  56078. var key;
  56079. var mayNeedSchemaUpdate;
  56080. if (clobber) {
  56081. // Clobber. Rebuild.
  56082. if (this.updateSchema) {
  56083. this.updateSchema(this.buildData(this.attrValue, true, true));
  56084. }
  56085. this.data = this.buildData(this.attrValue, true, false);
  56086. return;
  56087. }
  56088. // Apply new value to this.data in place since direct update.
  56089. if (this.isSingleProperty) {
  56090. if (this.isObjectBased) {
  56091. parseProperty(attrValue, this.schema);
  56092. }
  56093. // Single-property (already parsed).
  56094. this.data = attrValue;
  56095. return;
  56096. }
  56097. parseProperties(attrValue, this.schema, true, this.name);
  56098. // Check if we need to update schema.
  56099. if (this.schemaChangeKeys.length) {
  56100. for (key in attrValue) {
  56101. if (this.schema[key].schemaChange) {
  56102. mayNeedSchemaUpdate = true;
  56103. break;
  56104. }
  56105. }
  56106. }
  56107. if (mayNeedSchemaUpdate) {
  56108. // Rebuild data if need schema update.
  56109. if (this.updateSchema) {
  56110. this.updateSchema(this.buildData(this.attrValue, true, true));
  56111. }
  56112. this.data = this.buildData(this.attrValue, true, false);
  56113. return;
  56114. }
  56115. // Normal update.
  56116. for (key in attrValue) {
  56117. if (attrValue[key] === undefined) { continue; }
  56118. this.data[key] = attrValue[key];
  56119. }
  56120. },
  56121. /**
  56122. * Check if component should fire update and fire update lifecycle handler.
  56123. */
  56124. callUpdateHandler: function () {
  56125. var hasComponentChanged;
  56126. // Store the previous old data before we calculate the new oldData.
  56127. if (this.previousOldData instanceof Object) {
  56128. utils.objectPool.clearObject(this.previousOldData);
  56129. }
  56130. if (this.isObjectBased) {
  56131. copyData(this.previousOldData, this.oldData);
  56132. } else {
  56133. this.previousOldData = this.oldData;
  56134. }
  56135. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  56136. // Don't update if properties haven't changed.
  56137. // Always update rotation, position, scale.
  56138. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  56139. // Store current data as previous data for future updates.
  56140. // Reuse `this.oldData` object to try not to allocate another one.
  56141. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  56142. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  56143. // Update component with the previous old data.
  56144. this.update(this.previousOldData);
  56145. this.throttledEmitComponentChanged();
  56146. },
  56147. handleMixinUpdate: function () {
  56148. this.data = this.buildData(this.attrValue);
  56149. this.callUpdateHandler();
  56150. },
  56151. /**
  56152. * Reset value of a property to the property's default value.
  56153. * If single-prop component, reset value to component's default value.
  56154. *
  56155. * @param {string} propertyName - Name of property to reset.
  56156. */
  56157. resetProperty: function (propertyName) {
  56158. if (this.isObjectBased) {
  56159. if (!(propertyName in this.attrValue)) { return; }
  56160. delete this.attrValue[propertyName];
  56161. this.data[propertyName] = this.schema[propertyName].default;
  56162. } else {
  56163. this.attrValue = this.schema.default;
  56164. this.data = this.schema.default;
  56165. }
  56166. this.updateProperties(this.attrValue);
  56167. },
  56168. /**
  56169. * Extend schema of component given a partial schema.
  56170. *
  56171. * Some components might want to mutate their schema based on certain properties.
  56172. * e.g., Material component changes its schema based on `shader` to account for different
  56173. * uniforms
  56174. *
  56175. * @param {object} schemaAddon - Schema chunk that extend base schema.
  56176. */
  56177. extendSchema: function (schemaAddon) {
  56178. var extendedSchema;
  56179. // Clone base schema.
  56180. extendedSchema = utils.extend({}, components[this.name].schema);
  56181. // Extend base schema with new schema chunk.
  56182. utils.extend(extendedSchema, schemaAddon);
  56183. this.schema = processSchema(extendedSchema);
  56184. this.el.emit('schemachanged', this.evtDetail);
  56185. },
  56186. /**
  56187. * Build component data from the current state of the entity.data.
  56188. *
  56189. * Precedence:
  56190. * 1. Defaults data
  56191. * 2. Mixin data.
  56192. * 3. Attribute data.
  56193. *
  56194. * Finally coerce the data to the types of the defaults.
  56195. *
  56196. * @param {object} newData - Element new data.
  56197. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  56198. * @param {boolean} silent - Suppress warning messages.
  56199. * @return {object} The component data
  56200. */
  56201. buildData: function (newData, clobber, silent) {
  56202. var componentDefined;
  56203. var data;
  56204. var defaultValue;
  56205. var key;
  56206. var mixinData;
  56207. var nextData = this.nextData;
  56208. var schema = this.schema;
  56209. var i;
  56210. var mixinEls = this.el.mixinEls;
  56211. var previousData;
  56212. // Whether component has a defined value. For arrays, treat empty as not defined.
  56213. componentDefined = newData && newData.constructor === Array
  56214. ? newData.length
  56215. : newData !== undefined && newData !== null;
  56216. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  56217. // 1. Gather default values (lowest precendence).
  56218. if (this.isSingleProperty) {
  56219. if (this.isObjectBased) {
  56220. // If object-based single-prop, then copy over the data to our pooled object.
  56221. data = copyData(nextData, schema.default);
  56222. } else {
  56223. // If is plain single-prop, copy by value the default.
  56224. data = isObjectOrArray(schema.default)
  56225. ? utils.clone(schema.default)
  56226. : schema.default;
  56227. }
  56228. } else {
  56229. // Preserve previously set properties if clobber not enabled.
  56230. previousData = !clobber && this.attrValue;
  56231. // Clone default value if object so components don't share object
  56232. data = previousData instanceof Object
  56233. ? copyData(nextData, previousData)
  56234. : nextData;
  56235. // Apply defaults.
  56236. for (key in schema) {
  56237. defaultValue = schema[key].default;
  56238. if (data[key] !== undefined) { continue; }
  56239. // Clone default value if object so components don't share object
  56240. data[key] = isObjectOrArray(defaultValue)
  56241. ? utils.clone(defaultValue)
  56242. : defaultValue;
  56243. }
  56244. }
  56245. // 2. Gather mixin values.
  56246. for (i = 0; i < mixinEls.length; i++) {
  56247. mixinData = mixinEls[i].getAttribute(this.attrName);
  56248. if (!mixinData) { continue; }
  56249. data = extendProperties(data, mixinData, this.isObjectBased);
  56250. }
  56251. // 3. Gather attribute values (highest precendence).
  56252. if (componentDefined) {
  56253. if (this.isSingleProperty) {
  56254. // If object-based, copy the value to not modify the original.
  56255. if (isObject(newData)) {
  56256. copyData(this.parsingAttrValue, newData);
  56257. return parseProperty(this.parsingAttrValue, schema);
  56258. }
  56259. return parseProperty(newData, schema);
  56260. }
  56261. data = extendProperties(data, newData, this.isObjectBased);
  56262. } else {
  56263. // Parse and coerce using the schema.
  56264. if (this.isSingleProperty) { return parseProperty(data, schema); }
  56265. }
  56266. return parseProperties(data, schema, undefined, this.name, silent);
  56267. },
  56268. /**
  56269. * Attach events from component-defined events map.
  56270. */
  56271. eventsAttach: function () {
  56272. var eventName;
  56273. // Safety detach to prevent double-registration.
  56274. this.eventsDetach();
  56275. for (eventName in this.events) {
  56276. this.el.addEventListener(eventName, this.events[eventName]);
  56277. }
  56278. },
  56279. /**
  56280. * Detach events from component-defined events map.
  56281. */
  56282. eventsDetach: function () {
  56283. var eventName;
  56284. for (eventName in this.events) {
  56285. this.el.removeEventListener(eventName, this.events[eventName]);
  56286. }
  56287. },
  56288. /**
  56289. * Release and free memory.
  56290. */
  56291. destroy: function () {
  56292. this.objectPool.recycle(this.attrValue);
  56293. this.objectPool.recycle(this.oldData);
  56294. this.objectPool.recycle(this.parsingAttrValue);
  56295. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  56296. }
  56297. };
  56298. function eventsBind (component, events) {
  56299. var eventName;
  56300. for (eventName in events) {
  56301. component.events[eventName] = events[eventName].bind(component);
  56302. }
  56303. }
  56304. // For testing.
  56305. if (window.debug) {
  56306. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  56307. }
  56308. /**
  56309. * Register a component to A-Frame.
  56310. *
  56311. * @param {string} name - Component name.
  56312. * @param {object} definition - Component schema and lifecycle method handlers.
  56313. * @returns {object} Component.
  56314. */
  56315. module.exports.registerComponent = function (name, definition) {
  56316. var NewComponent;
  56317. var propertyName;
  56318. var proto = {};
  56319. var schema;
  56320. var schemaIsSingleProp;
  56321. // Warning if component is statically registered after the scene.
  56322. if (document.currentScript && document.currentScript !== aframeScript) {
  56323. scenes.forEach(function checkPosition (sceneEl) {
  56324. // Okay to register component after the scene at runtime.
  56325. if (sceneEl.hasLoaded) { return; }
  56326. // Check that component is declared before the scene.
  56327. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  56328. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  56329. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  56330. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  56331. 'such that the component is available to entities during scene initialization.');
  56332. // For testing.
  56333. if (window.debug) { registrationOrderWarnings[name] = true; }
  56334. });
  56335. }
  56336. if (upperCaseRegExp.test(name) === true) {
  56337. warn('The component name `' + name + '` contains uppercase characters, but ' +
  56338. 'HTML will ignore the capitalization of attribute names. ' +
  56339. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  56340. }
  56341. if (name.indexOf('__') !== -1) {
  56342. throw new Error('The component name `' + name + '` is not allowed. ' +
  56343. 'The sequence __ (double underscore) is reserved to specify an id' +
  56344. ' for multiple components of the same type');
  56345. }
  56346. // Format definition object to prototype object.
  56347. Object.keys(definition).forEach(function (key) {
  56348. proto[key] = {
  56349. value: definition[key],
  56350. writable: true
  56351. };
  56352. });
  56353. if (components[name]) {
  56354. throw new Error('The component `' + name + '` has been already registered. ' +
  56355. 'Check that you are not loading two versions of the same component ' +
  56356. 'or two different components of the same name.');
  56357. }
  56358. NewComponent = function (el, attr, id) {
  56359. Component.call(this, el, attr, id);
  56360. };
  56361. NewComponent.prototype = Object.create(Component.prototype, proto);
  56362. NewComponent.prototype.name = name;
  56363. NewComponent.prototype.isPositionRotationScale =
  56364. name === 'position' || name === 'rotation' || name === 'scale';
  56365. NewComponent.prototype.constructor = NewComponent;
  56366. NewComponent.prototype.system = systems && systems.systems[name];
  56367. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  56368. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  56369. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  56370. NewComponent.prototype.name));
  56371. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  56372. // Keep track of keys that may potentially change the schema.
  56373. if (!schemaIsSingleProp) {
  56374. NewComponent.prototype.schemaChangeKeys = [];
  56375. for (propertyName in schema) {
  56376. if (schema[propertyName].schemaChange) {
  56377. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  56378. }
  56379. }
  56380. }
  56381. // Create object pool for class of components.
  56382. objectPools[name] = utils.objectPool.createPool();
  56383. components[name] = {
  56384. Component: NewComponent,
  56385. dependencies: NewComponent.prototype.dependencies,
  56386. isSingleProp: schemaIsSingleProp,
  56387. multiple: NewComponent.prototype.multiple,
  56388. name: name,
  56389. parse: NewComponent.prototype.parse,
  56390. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  56391. schema: schema,
  56392. stringify: NewComponent.prototype.stringify,
  56393. type: NewComponent.prototype.type
  56394. };
  56395. return NewComponent;
  56396. };
  56397. /**
  56398. * Clone component data.
  56399. * Clone only the properties that are plain objects while keeping a reference for the rest.
  56400. *
  56401. * @param data - Component data to clone.
  56402. * @returns Cloned data.
  56403. */
  56404. function copyData (dest, sourceData) {
  56405. var parsedProperty;
  56406. var key;
  56407. for (key in sourceData) {
  56408. if (sourceData[key] === undefined) { continue; }
  56409. parsedProperty = sourceData[key];
  56410. dest[key] = isObjectOrArray(parsedProperty)
  56411. ? utils.clone(parsedProperty)
  56412. : parsedProperty;
  56413. }
  56414. return dest;
  56415. }
  56416. /**
  56417. * Object extending with checking for single-property schema.
  56418. *
  56419. * @param dest - Destination object or value.
  56420. * @param source - Source object or value
  56421. * @param {boolean} isObjectBased - Whether values are objects.
  56422. * @returns Overridden object or value.
  56423. */
  56424. function extendProperties (dest, source, isObjectBased) {
  56425. var key;
  56426. if (isObjectBased && source.constructor === Object) {
  56427. for (key in source) {
  56428. if (source[key] === undefined) { continue; }
  56429. if (source[key] && source[key].constructor === Object) {
  56430. dest[key] = utils.clone(source[key]);
  56431. } else {
  56432. dest[key] = source[key];
  56433. }
  56434. }
  56435. return dest;
  56436. }
  56437. return source;
  56438. }
  56439. /**
  56440. * Checks if a component has defined a method that needs to run every frame.
  56441. */
  56442. function hasBehavior (component) {
  56443. return component.tick || component.tock;
  56444. }
  56445. /**
  56446. * Wrapper for defined pause method.
  56447. * Pause component by removing tick behavior and calling user's pause method.
  56448. *
  56449. * @param pauseMethod {function}
  56450. */
  56451. function wrapPause (pauseMethod) {
  56452. return function pause () {
  56453. var sceneEl = this.el.sceneEl;
  56454. if (!this.isPlaying) { return; }
  56455. pauseMethod.call(this);
  56456. this.isPlaying = false;
  56457. this.eventsDetach();
  56458. // Remove tick behavior.
  56459. if (!hasBehavior(this)) { return; }
  56460. sceneEl.removeBehavior(this);
  56461. };
  56462. }
  56463. /**
  56464. * Wrapper for defined play method.
  56465. * Play component by adding tick behavior and calling user's play method.
  56466. *
  56467. * @param playMethod {function}
  56468. */
  56469. function wrapPlay (playMethod) {
  56470. return function play () {
  56471. var sceneEl = this.el.sceneEl;
  56472. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  56473. if (!this.initialized || !shouldPlay) { return; }
  56474. playMethod.call(this);
  56475. this.isPlaying = true;
  56476. this.eventsAttach();
  56477. // Add tick behavior.
  56478. if (!hasBehavior(this)) { return; }
  56479. sceneEl.addBehavior(this);
  56480. };
  56481. }
  56482. function isObject (value) {
  56483. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  56484. }
  56485. function isObjectOrArray (value) {
  56486. return value && (value.constructor === Object || value.constructor === Array) &&
  56487. !(value instanceof window.HTMLElement);
  56488. }
  56489. },{"../utils/":206,"./scene/scenes":139,"./schema":141,"./system":143}],133:[function(_dereq_,module,exports){
  56490. var schema = _dereq_('./schema');
  56491. var processSchema = schema.process;
  56492. var geometries = module.exports.geometries = {}; // Registered geometries.
  56493. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  56494. var THREE = _dereq_('../lib/three');
  56495. /**
  56496. * Geometry class definition.
  56497. *
  56498. * Geometries extend the geometry component API to create and register geometry types.
  56499. */
  56500. var Geometry = module.exports.Geometry = function () {};
  56501. Geometry.prototype = {
  56502. /**
  56503. * Contains the type schema and defaults for the data values.
  56504. * Data is coerced into the types of the values of the defaults.
  56505. */
  56506. schema: {},
  56507. /**
  56508. * Init handler. Similar to attachedCallback.
  56509. * Called during shader initialization and is only run once.
  56510. */
  56511. init: function (data) {
  56512. this.geometry = new THREE.BufferGeometry();
  56513. return this.geometry;
  56514. },
  56515. /**
  56516. * Update handler. Similar to attributeChangedCallback.
  56517. * Called whenever the associated geometry data changes.
  56518. *
  56519. * @param {object} data - New geometry data.
  56520. */
  56521. update: function (data) { /* no-op */ }
  56522. };
  56523. /**
  56524. * Registers a geometry to A-Frame.
  56525. *
  56526. * @param {string} name - Geometry name.
  56527. * @param {object} definition - Geometry property and methods.
  56528. * @returns {object} Geometry.
  56529. */
  56530. module.exports.registerGeometry = function (name, definition) {
  56531. var NewGeometry;
  56532. var proto = {};
  56533. // Format definition object to prototype object.
  56534. Object.keys(definition).forEach(function expandDefinition (key) {
  56535. proto[key] = {
  56536. value: definition[key],
  56537. writable: true
  56538. };
  56539. });
  56540. if (geometries[name]) {
  56541. throw new Error('The geometry `' + name + '` has been already registered');
  56542. }
  56543. NewGeometry = function () { Geometry.call(this); };
  56544. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  56545. NewGeometry.prototype.name = name;
  56546. NewGeometry.prototype.constructor = NewGeometry;
  56547. geometries[name] = {
  56548. Geometry: NewGeometry,
  56549. schema: processSchema(NewGeometry.prototype.schema)
  56550. };
  56551. geometryNames.push(name);
  56552. return NewGeometry;
  56553. };
  56554. },{"../lib/three":180,"./schema":141}],134:[function(_dereq_,module,exports){
  56555. var coordinates = _dereq_('../utils/coordinates');
  56556. var debug = _dereq_('debug');
  56557. var error = debug('core:propertyTypes:warn');
  56558. var warn = debug('core:propertyTypes:warn');
  56559. var propertyTypes = module.exports.propertyTypes = {};
  56560. var nonCharRegex = /[,> .[\]:]/;
  56561. var urlRegex = /\url\((.+)\)/;
  56562. // Built-in property types.
  56563. registerPropertyType('audio', '', assetParse);
  56564. registerPropertyType('array', [], arrayParse, arrayStringify);
  56565. registerPropertyType('asset', '', assetParse);
  56566. registerPropertyType('boolean', false, boolParse);
  56567. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  56568. registerPropertyType('int', 0, intParse);
  56569. registerPropertyType('number', 0, numberParse);
  56570. registerPropertyType('map', '', assetParse);
  56571. registerPropertyType('model', '', assetParse);
  56572. registerPropertyType('selector', null, selectorParse, selectorStringify);
  56573. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  56574. registerPropertyType('src', '', srcParse);
  56575. registerPropertyType('string', '', defaultParse, defaultStringify);
  56576. registerPropertyType('time', 0, intParse);
  56577. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  56578. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  56579. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  56580. /**
  56581. * Register a parser for re-use such that when someone uses `type` in the schema,
  56582. * `schema.process` will set the property `parse` and `stringify`.
  56583. *
  56584. * @param {string} type - Type name.
  56585. * @param [defaultValue=null] -
  56586. * Default value to use if component does not define default value.
  56587. * @param {function} [parse=defaultParse] - Parse string function.
  56588. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  56589. */
  56590. function registerPropertyType (type, defaultValue, parse, stringify) {
  56591. if ('type' in propertyTypes) {
  56592. error('Property type ' + type + ' is already registered.');
  56593. return;
  56594. }
  56595. propertyTypes[type] = {
  56596. default: defaultValue,
  56597. parse: parse || defaultParse,
  56598. stringify: stringify || defaultStringify
  56599. };
  56600. }
  56601. module.exports.registerPropertyType = registerPropertyType;
  56602. function arrayParse (value) {
  56603. if (Array.isArray(value)) { return value; }
  56604. if (!value || typeof value !== 'string') { return []; }
  56605. return value.split(',').map(trim);
  56606. function trim (str) { return str.trim(); }
  56607. }
  56608. function arrayStringify (value) {
  56609. return value.join(', ');
  56610. }
  56611. /**
  56612. * For general assets.
  56613. *
  56614. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  56615. * just string.
  56616. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  56617. * just string.
  56618. */
  56619. function assetParse (value) {
  56620. var el;
  56621. var parsedUrl;
  56622. // If an element was provided (e.g. canvas or video), just return it.
  56623. if (typeof value !== 'string') { return value; }
  56624. // Wrapped `url()` in case of data URI.
  56625. parsedUrl = value.match(urlRegex);
  56626. if (parsedUrl) { return parsedUrl[1]; }
  56627. // ID.
  56628. if (value.charAt(0) === '#') {
  56629. el = document.getElementById(value.substring(1));
  56630. if (el) {
  56631. // Pass through media elements. If we have the elements, we don't have to call
  56632. // three.js loaders which would re-request the assets.
  56633. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  56634. return el;
  56635. }
  56636. return el.getAttribute('src');
  56637. }
  56638. warn('"' + value + '" asset not found.');
  56639. return;
  56640. }
  56641. // Non-wrapped url().
  56642. return value;
  56643. }
  56644. function defaultParse (value) {
  56645. return value;
  56646. }
  56647. function defaultStringify (value) {
  56648. if (value === null) { return 'null'; }
  56649. return value.toString();
  56650. }
  56651. function boolParse (value) {
  56652. return value !== 'false' && value !== false;
  56653. }
  56654. function intParse (value) {
  56655. return parseInt(value, 10);
  56656. }
  56657. function numberParse (value) {
  56658. return parseFloat(value, 10);
  56659. }
  56660. function selectorParse (value) {
  56661. if (!value) { return null; }
  56662. if (typeof value !== 'string') { return value; }
  56663. if (value[0] === '#' && !nonCharRegex.test(value)) {
  56664. // When selecting element by ID only, use getElementById for better performance.
  56665. // Don't match like #myId .child.
  56666. return document.getElementById(value.substring(1));
  56667. }
  56668. return document.querySelector(value);
  56669. }
  56670. function selectorAllParse (value) {
  56671. if (!value) { return null; }
  56672. if (typeof value !== 'string') { return value; }
  56673. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  56674. }
  56675. function selectorStringify (value) {
  56676. if (value.getAttribute) {
  56677. return '#' + value.getAttribute('id');
  56678. }
  56679. return defaultStringify(value);
  56680. }
  56681. function selectorAllStringify (value) {
  56682. if (value instanceof Array) {
  56683. return value.map(function (element) {
  56684. return '#' + element.getAttribute('id');
  56685. }).join(', ');
  56686. }
  56687. return defaultStringify(value);
  56688. }
  56689. function srcParse (value) {
  56690. warn('`src` property type is deprecated. Use `asset` instead.');
  56691. return assetParse(value);
  56692. }
  56693. function vecParse (value) {
  56694. return coordinates.parse(value, this.default);
  56695. }
  56696. /**
  56697. * Validate the default values in a schema to match their type.
  56698. *
  56699. * @param {string} type - Property type name.
  56700. * @param defaultVal - Property type default value.
  56701. * @returns {boolean} Whether default value is accurate given the type.
  56702. */
  56703. function isValidDefaultValue (type, defaultVal) {
  56704. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  56705. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  56706. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  56707. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  56708. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  56709. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  56710. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  56711. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  56712. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  56713. if (type === 'selector' && typeof defaultVal !== 'string' &&
  56714. defaultVal !== null) { return false; }
  56715. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  56716. defaultVal !== null) { return false; }
  56717. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  56718. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  56719. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  56720. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  56721. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  56722. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  56723. return true;
  56724. }
  56725. module.exports.isValidDefaultValue = isValidDefaultValue;
  56726. /**
  56727. * Checks if default coordinates are valid.
  56728. *
  56729. * @param possibleCoordinates
  56730. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  56731. * @returns {boolean} Whether coordinates are parsed correctly.
  56732. */
  56733. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  56734. if (possibleCoordinates === null) { return true; }
  56735. if (typeof possibleCoordinates !== 'object') { return false; }
  56736. if (Object.keys(possibleCoordinates).length !== dimensions) {
  56737. return false;
  56738. } else {
  56739. var x = possibleCoordinates.x;
  56740. var y = possibleCoordinates.y;
  56741. var z = possibleCoordinates.z;
  56742. var w = possibleCoordinates.w;
  56743. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  56744. if (dimensions > 2 && typeof z !== 'number') { return false; }
  56745. if (dimensions > 3 && typeof w !== 'number') { return false; }
  56746. }
  56747. return true;
  56748. }
  56749. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  56750. },{"../utils/coordinates":201,"debug":8}],135:[function(_dereq_,module,exports){
  56751. /* global Promise, screen, CustomEvent */
  56752. var initMetaTags = _dereq_('./metaTags').inject;
  56753. var initWakelock = _dereq_('./wakelock');
  56754. var loadingScreen = _dereq_('./loadingScreen');
  56755. var re = _dereq_('../a-register-element');
  56756. var scenes = _dereq_('./scenes');
  56757. var systems = _dereq_('../system').systems;
  56758. var THREE = _dereq_('../../lib/three');
  56759. var utils = _dereq_('../../utils/');
  56760. // Require after.
  56761. var AEntity = _dereq_('../a-entity');
  56762. var ANode = _dereq_('../a-node');
  56763. var initPostMessageAPI = _dereq_('./postMessage');
  56764. var bind = utils.bind;
  56765. var isIOS = utils.device.isIOS();
  56766. var isMobile = utils.device.isMobile();
  56767. var isWebXRAvailable = utils.device.isWebXRAvailable;
  56768. var registerElement = re.registerElement;
  56769. var warn = utils.debug('core:a-scene:warn');
  56770. if (isIOS) { _dereq_('../../utils/ios-orientationchange-blank-bug'); }
  56771. /**
  56772. * Scene element, holds all entities.
  56773. *
  56774. * @member {array} behaviors - Component instances that have registered themselves to be
  56775. updated on every tick.
  56776. * @member {object} camera - three.js Camera object.
  56777. * @member {object} canvas
  56778. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  56779. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  56780. * @member {object} object3D - Root three.js Scene object.
  56781. * @member {object} renderer
  56782. * @member {bool} renderStarted
  56783. * @member {object} systems - Registered instantiated systems.
  56784. * @member {number} time
  56785. */
  56786. module.exports.AScene = registerElement('a-scene', {
  56787. prototype: Object.create(AEntity.prototype, {
  56788. createdCallback: {
  56789. value: function () {
  56790. this.clock = new THREE.Clock();
  56791. this.isIOS = isIOS;
  56792. this.isMobile = isMobile;
  56793. this.hasWebXR = isWebXRAvailable;
  56794. this.isAR = false;
  56795. this.isScene = true;
  56796. this.object3D = new THREE.Scene();
  56797. var self = this;
  56798. this.object3D.onAfterRender = function (renderer, scene, camera) {
  56799. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  56800. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  56801. };
  56802. this.resize = bind(this.resize, this);
  56803. this.render = bind(this.render, this);
  56804. this.systems = {};
  56805. this.systemNames = [];
  56806. this.time = this.delta = 0;
  56807. this.behaviors = {tick: [], tock: []};
  56808. this.hasLoaded = false;
  56809. this.isPlaying = false;
  56810. this.originalHTML = this.innerHTML;
  56811. // Default components.
  56812. this.setAttribute('inspector', '');
  56813. this.setAttribute('keyboard-shortcuts', '');
  56814. this.setAttribute('screenshot', '');
  56815. this.setAttribute('vr-mode-ui', '');
  56816. this.setAttribute('device-orientation-permission-ui', '');
  56817. }
  56818. },
  56819. addFullScreenStyles: {
  56820. value: function () {
  56821. document.documentElement.classList.add('a-fullscreen');
  56822. }
  56823. },
  56824. removeFullScreenStyles: {
  56825. value: function () {
  56826. document.documentElement.classList.remove('a-fullscreen');
  56827. }
  56828. },
  56829. attachedCallback: {
  56830. value: function () {
  56831. var self = this;
  56832. var embedded = this.hasAttribute('embedded');
  56833. // Renderer initialization
  56834. setupCanvas(this);
  56835. this.setupRenderer();
  56836. loadingScreen.setup(this, getCanvasSize);
  56837. this.resize();
  56838. if (!embedded) { this.addFullScreenStyles(); }
  56839. initPostMessageAPI(this);
  56840. initMetaTags(this);
  56841. initWakelock(this);
  56842. // Handler to exit VR (e.g., Oculus Browser back button).
  56843. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  56844. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56845. // Bind functions.
  56846. this.enterVRBound = function () { self.enterVR(); };
  56847. this.exitVRBound = function () { self.exitVR(); };
  56848. this.exitVRTrueBound = function () { self.exitVR(true); };
  56849. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  56850. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  56851. if (!isWebXRAvailable) {
  56852. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  56853. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  56854. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  56855. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56856. // Register for mouse restricted events while in VR
  56857. // (e.g. mouse no longer available on desktop 2D view)
  56858. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56859. // Register for mouse unrestricted events while in VR
  56860. // (e.g. mouse once again available on desktop 2D view)
  56861. window.addEventListener('vrdisplaypointerunrestricted',
  56862. this.pointerUnrestrictedBound);
  56863. }
  56864. window.addEventListener('sessionend', this.resize);
  56865. // Camera set up by camera system.
  56866. this.addEventListener('cameraready', function () {
  56867. self.attachedCallbackPostCamera();
  56868. });
  56869. this.initSystems();
  56870. // WebXR Immersive navigation handler.
  56871. if (this.hasWebXR && navigator.xr && navigator.xr.addEventListener) {
  56872. navigator.xr.addEventListener('sessiongranted', function () { self.enterVR(); });
  56873. }
  56874. }
  56875. },
  56876. attachedCallbackPostCamera: {
  56877. value: function () {
  56878. var resize;
  56879. var self = this;
  56880. window.addEventListener('load', resize);
  56881. window.addEventListener('resize', function () {
  56882. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  56883. // where the window does not contain the correct viewport size
  56884. // after an orientation change. The window size is correct if the operation
  56885. // is postponed a few milliseconds.
  56886. // self.resize can be called directly once the bug above is fixed.
  56887. if (self.isIOS) {
  56888. setTimeout(self.resize, 100);
  56889. } else {
  56890. self.resize();
  56891. }
  56892. });
  56893. this.play();
  56894. // Add to scene index.
  56895. scenes.push(this);
  56896. },
  56897. writable: window.debug
  56898. },
  56899. /**
  56900. * Initialize all systems.
  56901. */
  56902. initSystems: {
  56903. value: function () {
  56904. var name;
  56905. // Initialize camera system first.
  56906. this.initSystem('camera');
  56907. for (name in systems) {
  56908. if (name === 'camera') { continue; }
  56909. this.initSystem(name);
  56910. }
  56911. }
  56912. },
  56913. /**
  56914. * Initialize a system.
  56915. */
  56916. initSystem: {
  56917. value: function (name) {
  56918. if (this.systems[name]) { return; }
  56919. this.systems[name] = new systems[name](this);
  56920. this.systemNames.push(name);
  56921. }
  56922. },
  56923. /**
  56924. * Shut down scene on detach.
  56925. */
  56926. detachedCallback: {
  56927. value: function () {
  56928. // Remove from scene index.
  56929. var sceneIndex = scenes.indexOf(this);
  56930. scenes.splice(sceneIndex, 1);
  56931. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56932. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  56933. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  56934. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  56935. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56936. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56937. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  56938. window.removeEventListener('sessionend', this.resize);
  56939. this.renderer.xr.dispose();
  56940. }
  56941. },
  56942. /**
  56943. * Add ticks and tocks.
  56944. *
  56945. * @param {object} behavior - A component.
  56946. */
  56947. addBehavior: {
  56948. value: function (behavior) {
  56949. var behaviorArr;
  56950. var behaviors = this.behaviors;
  56951. var behaviorType;
  56952. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  56953. for (behaviorType in behaviors) {
  56954. if (!behavior[behaviorType]) { continue; }
  56955. behaviorArr = this.behaviors[behaviorType];
  56956. if (behaviorArr.indexOf(behavior) === -1) {
  56957. behaviorArr.push(behavior);
  56958. }
  56959. }
  56960. }
  56961. },
  56962. /**
  56963. * For tests.
  56964. */
  56965. getPointerLockElement: {
  56966. value: function () {
  56967. return document.pointerLockElement;
  56968. },
  56969. writable: window.debug
  56970. },
  56971. /**
  56972. * For tests.
  56973. */
  56974. checkHeadsetConnected: {
  56975. value: utils.device.checkHeadsetConnected,
  56976. writable: window.debug
  56977. },
  56978. enterAR: {
  56979. value: function () {
  56980. var errorMessage;
  56981. if (!this.hasWebXR) {
  56982. errorMessage = 'Failed to enter AR mode, WebXR not supported.';
  56983. throw new Error(errorMessage);
  56984. }
  56985. if (!utils.device.checkARSupport()) {
  56986. errorMessage = 'Failed to enter AR, WebXR immersive-ar mode not supported in your browser or device.';
  56987. throw new Error(errorMessage);
  56988. }
  56989. return this.enterVR(true);
  56990. }
  56991. },
  56992. /**
  56993. * Call `requestPresent` if WebVR or WebVR polyfill.
  56994. * Call `requestFullscreen` on desktop.
  56995. * Handle events, states, fullscreen styles.
  56996. *
  56997. * @param {bool?} useAR - if true, try immersive-ar mode
  56998. * @returns {Promise}
  56999. */
  57000. enterVR: {
  57001. value: function (useAR) {
  57002. var self = this;
  57003. var vrDisplay;
  57004. var vrManager = self.renderer.xr;
  57005. var xrInit;
  57006. // Don't enter VR if already in VR.
  57007. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  57008. // Has VR.
  57009. if (this.checkHeadsetConnected() || this.isMobile) {
  57010. vrManager.enabled = true;
  57011. if (this.hasWebXR) {
  57012. // XR API.
  57013. if (this.xrSession) {
  57014. this.xrSession.removeEventListener('end', this.exitVRBound);
  57015. }
  57016. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  57017. vrManager.setReferenceSpaceType(refspace);
  57018. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  57019. xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  57020. return new Promise(function (resolve, reject) {
  57021. navigator.xr.requestSession(xrMode, xrInit).then(
  57022. function requestSuccess (xrSession) {
  57023. self.xrSession = xrSession;
  57024. vrManager.layersEnabled = xrInit.requiredFeatures.indexOf('layers') !== -1;
  57025. vrManager.setSession(xrSession);
  57026. xrSession.addEventListener('end', self.exitVRBound);
  57027. enterVRSuccess(resolve);
  57028. },
  57029. function requestFail (error) {
  57030. var useAR = xrMode === 'immersive-ar';
  57031. var mode = useAR ? 'AR' : 'VR';
  57032. throw new Error('Failed to enter ' + mode + ' mode (`requestSession`) ' + error);
  57033. }
  57034. );
  57035. });
  57036. } else {
  57037. vrDisplay = utils.device.getVRDisplay();
  57038. vrManager.setDevice(vrDisplay);
  57039. if (vrDisplay.isPresenting &&
  57040. !window.hasNativeWebVRImplementation) {
  57041. enterVRSuccess();
  57042. return Promise.resolve();
  57043. }
  57044. var rendererSystem = this.getAttribute('renderer');
  57045. var presentationAttributes = {
  57046. highRefreshRate: rendererSystem.highRefreshRate,
  57047. foveationLevel: rendererSystem.foveationLevel
  57048. };
  57049. return vrDisplay.requestPresent([{
  57050. source: this.canvas,
  57051. attributes: presentationAttributes
  57052. }]).then(enterVRSuccess, enterVRFailure);
  57053. }
  57054. }
  57055. // No VR.
  57056. enterVRSuccess();
  57057. return Promise.resolve();
  57058. // Callback that happens on enter VR success or enter fullscreen (any API).
  57059. function enterVRSuccess (resolve) {
  57060. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  57061. // the first requestPresent could be called from ondisplayactivate and there is no way
  57062. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  57063. // for the actual requestPresent. Need to make sure there are no issues with firing the
  57064. // vrdisplaypresentchange multiple times.
  57065. var event;
  57066. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  57067. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  57068. window.dispatchEvent(event);
  57069. }
  57070. if (useAR) {
  57071. self.addState('ar-mode');
  57072. } else {
  57073. self.addState('vr-mode');
  57074. }
  57075. self.emit('enter-vr', {target: self});
  57076. // Lock to landscape orientation on mobile.
  57077. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  57078. screen.orientation.lock('landscape');
  57079. }
  57080. self.addFullScreenStyles();
  57081. // On mobile, the polyfill handles fullscreen.
  57082. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  57083. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  57084. // connected.
  57085. if (!self.isMobile && !self.checkHeadsetConnected()) {
  57086. requestFullscreen(self.canvas);
  57087. }
  57088. self.renderer.setAnimationLoop(self.render);
  57089. self.resize();
  57090. if (resolve) { resolve(); }
  57091. }
  57092. function enterVRFailure (err) {
  57093. self.removeState('vr-mode');
  57094. if (err && err.message) {
  57095. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  57096. } else {
  57097. throw new Error('Failed to enter VR mode (`requestPresent`).');
  57098. }
  57099. }
  57100. },
  57101. writable: true
  57102. },
  57103. /**
  57104. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  57105. * Handle events, states, fullscreen styles.
  57106. *
  57107. * @returns {Promise}
  57108. */
  57109. exitVR: {
  57110. value: function () {
  57111. var self = this;
  57112. var vrDisplay;
  57113. var vrManager = this.renderer.xr;
  57114. // Don't exit VR if not in VR.
  57115. if (!this.is('vr-mode') && !this.is('ar-mode')) { return Promise.resolve('Not in immersive mode.'); }
  57116. // Handle exiting VR if not yet already and in a headset or polyfill.
  57117. if (this.checkHeadsetConnected() || this.isMobile) {
  57118. vrManager.enabled = false;
  57119. vrDisplay = utils.device.getVRDisplay();
  57120. if (this.hasWebXR) {
  57121. this.xrSession.removeEventListener('end', this.exitVRBound);
  57122. // Capture promise to avoid errors.
  57123. this.xrSession.end().then(function () {}, function () {});
  57124. this.xrSession = undefined;
  57125. vrManager.setSession(null);
  57126. } else {
  57127. if (vrDisplay.isPresenting) {
  57128. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  57129. }
  57130. }
  57131. } else {
  57132. exitFullscreen();
  57133. }
  57134. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  57135. exitVRSuccess();
  57136. return Promise.resolve();
  57137. function exitVRSuccess () {
  57138. self.removeState('vr-mode');
  57139. self.removeState('ar-mode');
  57140. // Lock to landscape orientation on mobile.
  57141. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  57142. screen.orientation.unlock();
  57143. }
  57144. // Exiting VR in embedded mode, no longer need fullscreen styles.
  57145. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  57146. self.resize();
  57147. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  57148. self.renderer.setPixelRatio(window.devicePixelRatio);
  57149. self.emit('exit-vr', {target: self});
  57150. }
  57151. function exitVRFailure (err) {
  57152. if (err && err.message) {
  57153. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  57154. } else {
  57155. throw new Error('Failed to exit VR mode (`exitPresent`).');
  57156. }
  57157. }
  57158. },
  57159. writable: true
  57160. },
  57161. pointerRestricted: {
  57162. value: function () {
  57163. if (this.canvas) {
  57164. var pointerLockElement = this.getPointerLockElement();
  57165. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  57166. // Recreate pointer lock on the canvas, if taken on another element.
  57167. document.exitPointerLock();
  57168. }
  57169. if (this.canvas.requestPointerLock) {
  57170. this.canvas.requestPointerLock();
  57171. }
  57172. }
  57173. }
  57174. },
  57175. pointerUnrestricted: {
  57176. value: function () {
  57177. var pointerLockElement = this.getPointerLockElement();
  57178. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  57179. document.exitPointerLock();
  57180. }
  57181. }
  57182. },
  57183. /**
  57184. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  57185. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  57186. */
  57187. onVRPresentChange: {
  57188. value: function (evt) {
  57189. // Polyfill places display inside the detail property
  57190. var display = evt.display || evt.detail.display;
  57191. // Entering VR.
  57192. if (display && display.isPresenting) {
  57193. this.enterVR();
  57194. return;
  57195. }
  57196. // Exiting VR.
  57197. this.exitVR();
  57198. }
  57199. },
  57200. /**
  57201. * Wraps Entity.getAttribute to take into account for systems.
  57202. * If system exists, then return system data rather than possible component data.
  57203. */
  57204. getAttribute: {
  57205. value: function (attr) {
  57206. var system = this.systems[attr];
  57207. if (system) { return system.data; }
  57208. return AEntity.prototype.getAttribute.call(this, attr);
  57209. }
  57210. },
  57211. /**
  57212. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  57213. * what `getAttribute` is now. Now legacy code.
  57214. */
  57215. getComputedAttribute: {
  57216. value: function (attr) {
  57217. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  57218. this.getAttribute(attr);
  57219. }
  57220. },
  57221. /**
  57222. * Wraps Entity.getDOMAttribute to take into account for systems.
  57223. * If system exists, then return system data rather than possible component data.
  57224. */
  57225. getDOMAttribute: {
  57226. value: function (attr) {
  57227. var system = this.systems[attr];
  57228. if (system) { return system.data; }
  57229. return AEntity.prototype.getDOMAttribute.call(this, attr);
  57230. }
  57231. },
  57232. /**
  57233. * Wrap Entity.setAttribute to take into account for systems.
  57234. * If system exists, then skip component initialization checks and do a normal
  57235. * setAttribute.
  57236. */
  57237. setAttribute: {
  57238. value: function (attr, value, componentPropValue) {
  57239. var system = this.systems[attr];
  57240. if (system) {
  57241. ANode.prototype.setAttribute.call(this, attr, value);
  57242. system.updateProperties(value);
  57243. return;
  57244. }
  57245. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  57246. }
  57247. },
  57248. /**
  57249. * @param {object} behavior - A component.
  57250. */
  57251. removeBehavior: {
  57252. value: function (behavior) {
  57253. var behaviorArr;
  57254. var behaviorType;
  57255. var behaviors = this.behaviors;
  57256. var index;
  57257. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  57258. // array.
  57259. for (behaviorType in behaviors) {
  57260. if (!behavior[behaviorType]) { continue; }
  57261. behaviorArr = this.behaviors[behaviorType];
  57262. index = behaviorArr.indexOf(behavior);
  57263. if (index !== -1) { behaviorArr.splice(index, 1); }
  57264. }
  57265. }
  57266. },
  57267. resize: {
  57268. value: function () {
  57269. var camera = this.camera;
  57270. var canvas = this.canvas;
  57271. var embedded;
  57272. var isVRPresenting;
  57273. var size;
  57274. var isPresenting = this.renderer.xr.isPresenting;
  57275. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  57276. // Do not update renderer, if a camera or a canvas have not been injected.
  57277. // In VR mode, three handles canvas resize based on the dimensions returned by
  57278. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  57279. // the window size, therefore should not be overwritten with the window's width and
  57280. // height, // except when in fullscreen mode.
  57281. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  57282. return;
  57283. }
  57284. // Update camera.
  57285. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  57286. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  57287. camera.aspect = size.width / size.height;
  57288. camera.updateProjectionMatrix();
  57289. // Notify renderer of size change.
  57290. this.renderer.setSize(size.width, size.height, false);
  57291. this.emit('rendererresize', null, false);
  57292. },
  57293. writable: true
  57294. },
  57295. setupRenderer: {
  57296. value: function () {
  57297. var self = this;
  57298. var renderer;
  57299. var rendererAttr;
  57300. var rendererAttrString;
  57301. var rendererConfig;
  57302. rendererConfig = {
  57303. alpha: true,
  57304. antialias: !isMobile,
  57305. canvas: this.canvas,
  57306. logarithmicDepthBuffer: false,
  57307. powerPreference: 'high-performance'
  57308. };
  57309. this.maxCanvasSize = {height: 1920, width: 1920};
  57310. if (this.hasAttribute('renderer')) {
  57311. rendererAttrString = this.getAttribute('renderer');
  57312. rendererAttr = utils.styleParser.parse(rendererAttrString);
  57313. if (rendererAttr.precision) {
  57314. rendererConfig.precision = rendererAttr.precision + 'p';
  57315. }
  57316. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  57317. rendererConfig.antialias = rendererAttr.antialias === 'true';
  57318. }
  57319. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  57320. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  57321. }
  57322. if (rendererAttr.alpha) {
  57323. rendererConfig.alpha = rendererAttr.alpha === 'true';
  57324. }
  57325. this.maxCanvasSize = {
  57326. width: rendererAttr.maxCanvasWidth
  57327. ? parseInt(rendererAttr.maxCanvasWidth)
  57328. : this.maxCanvasSize.width,
  57329. height: rendererAttr.maxCanvasHeight
  57330. ? parseInt(rendererAttr.maxCanvasHeight)
  57331. : this.maxCanvasSize.height
  57332. };
  57333. }
  57334. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  57335. renderer.setPixelRatio(window.devicePixelRatio);
  57336. renderer.sortObjects = false;
  57337. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  57338. this.addEventListener('camera-set-active', function () {
  57339. renderer.xr.setPoseTarget(self.camera.el.object3D);
  57340. });
  57341. },
  57342. writable: window.debug
  57343. },
  57344. /**
  57345. * Handler attached to elements to help scene know when to kick off.
  57346. * Scene waits for all entities to load.
  57347. */
  57348. play: {
  57349. value: function () {
  57350. var self = this;
  57351. var sceneEl = this;
  57352. if (this.renderStarted) {
  57353. AEntity.prototype.play.call(this);
  57354. return;
  57355. }
  57356. this.addEventListener('loaded', function () {
  57357. var renderer = this.renderer;
  57358. var vrDisplay;
  57359. var vrManager = this.renderer.xr;
  57360. AEntity.prototype.play.call(this); // .play() *before* render.
  57361. if (sceneEl.renderStarted) { return; }
  57362. sceneEl.resize();
  57363. // Kick off render loop.
  57364. if (sceneEl.renderer) {
  57365. if (window.performance) { window.performance.mark('render-started'); }
  57366. loadingScreen.remove();
  57367. vrDisplay = utils.device.getVRDisplay();
  57368. if (vrDisplay && vrDisplay.isPresenting) {
  57369. vrManager.setDevice(vrDisplay);
  57370. vrManager.enabled = true;
  57371. sceneEl.enterVR();
  57372. }
  57373. renderer.setAnimationLoop(this.render);
  57374. sceneEl.renderStarted = true;
  57375. sceneEl.emit('renderstart');
  57376. }
  57377. });
  57378. // setTimeout to wait for all nodes to attach and run their callbacks.
  57379. setTimeout(function () {
  57380. AEntity.prototype.load.call(self);
  57381. });
  57382. }
  57383. },
  57384. /**
  57385. * Wrap `updateComponent` to not initialize the component if the component has a system
  57386. * (aframevr/aframe#2365).
  57387. */
  57388. updateComponent: {
  57389. value: function (componentName) {
  57390. if (componentName in systems) { return; }
  57391. AEntity.prototype.updateComponent.apply(this, arguments);
  57392. }
  57393. },
  57394. /**
  57395. * Behavior-updater meant to be called from scene render.
  57396. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  57397. * needing to render.
  57398. */
  57399. tick: {
  57400. value: function (time, timeDelta) {
  57401. var i;
  57402. var systems = this.systems;
  57403. // Components.
  57404. for (i = 0; i < this.behaviors.tick.length; i++) {
  57405. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  57406. this.behaviors.tick[i].tick(time, timeDelta);
  57407. }
  57408. // Systems.
  57409. for (i = 0; i < this.systemNames.length; i++) {
  57410. if (!systems[this.systemNames[i]].tick) { continue; }
  57411. systems[this.systemNames[i]].tick(time, timeDelta);
  57412. }
  57413. }
  57414. },
  57415. /**
  57416. * Behavior-updater meant to be called after scene render for post processing purposes.
  57417. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  57418. * needing to render.
  57419. */
  57420. tock: {
  57421. value: function (time, timeDelta, camera) {
  57422. var i;
  57423. var systems = this.systems;
  57424. // Components.
  57425. for (i = 0; i < this.behaviors.tock.length; i++) {
  57426. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  57427. this.behaviors.tock[i].tock(time, timeDelta, camera);
  57428. }
  57429. // Systems.
  57430. for (i = 0; i < this.systemNames.length; i++) {
  57431. if (!systems[this.systemNames[i]].tock) { continue; }
  57432. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  57433. }
  57434. }
  57435. },
  57436. /**
  57437. * The render loop.
  57438. *
  57439. * Updates animations.
  57440. * Updates behaviors.
  57441. * Renders with request animation frame.
  57442. */
  57443. render: {
  57444. value: function (time, frame) {
  57445. var renderer = this.renderer;
  57446. this.frame = frame;
  57447. this.delta = this.clock.getDelta() * 1000;
  57448. this.time = this.clock.elapsedTime * 1000;
  57449. if (this.isPlaying) { this.tick(this.time, this.delta); }
  57450. var savedBackground = null;
  57451. if (this.is('ar-mode')) {
  57452. // In AR mode, don't render the default background. Hide it, then
  57453. // restore it again after rendering.
  57454. savedBackground = this.object3D.background;
  57455. this.object3D.background = null;
  57456. }
  57457. renderer.render(this.object3D, this.camera);
  57458. if (savedBackground) {
  57459. this.object3D.background = savedBackground;
  57460. }
  57461. },
  57462. writable: true
  57463. }
  57464. })
  57465. });
  57466. /**
  57467. * Return the canvas size where the scene will be rendered.
  57468. * Will be always the window size except when the scene is embedded.
  57469. * The parent size (less than max size) will be returned in that case.
  57470. *
  57471. * @param {object} canvasEl - the canvas element
  57472. * @param {boolean} embedded - Is the scene embedded?
  57473. * @param {object} max - Max size parameters
  57474. * @param {boolean} isVR - If in VR
  57475. */
  57476. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  57477. if (!canvasEl.parentElement) { return {height: 0, width: 0}; }
  57478. if (embedded) {
  57479. return {
  57480. height: canvasEl.parentElement.offsetHeight,
  57481. width: canvasEl.parentElement.offsetWidth
  57482. };
  57483. }
  57484. return getMaxSize(maxSize, isVR);
  57485. }
  57486. /**
  57487. * Return the canvas size. Will be the window size unless that size is greater than the
  57488. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  57489. * maintaining aspect ratio
  57490. *
  57491. * @param {object} maxSize - Max size parameters (width and height).
  57492. * @param {boolean} isVR - If in VR.
  57493. * @returns {object} Width and height.
  57494. */
  57495. function getMaxSize (maxSize, isVR) {
  57496. var aspectRatio;
  57497. var size;
  57498. var pixelRatio = window.devicePixelRatio;
  57499. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  57500. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  57501. return size;
  57502. }
  57503. if (size.width * pixelRatio < maxSize.width &&
  57504. size.height * pixelRatio < maxSize.height) {
  57505. return size;
  57506. }
  57507. aspectRatio = size.width / size.height;
  57508. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  57509. size.width = Math.round(maxSize.width / pixelRatio);
  57510. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  57511. }
  57512. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  57513. size.height = Math.round(maxSize.height / pixelRatio);
  57514. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  57515. }
  57516. return size;
  57517. }
  57518. function requestFullscreen (canvas) {
  57519. var requestFullscreen =
  57520. canvas.requestFullscreen ||
  57521. canvas.webkitRequestFullscreen ||
  57522. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  57523. canvas.msRequestFullscreen;
  57524. // Hide navigation buttons on Android.
  57525. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  57526. }
  57527. function exitFullscreen () {
  57528. var fullscreenEl =
  57529. document.fullscreenElement ||
  57530. document.webkitFullscreenElement ||
  57531. document.mozFullScreenElement;
  57532. if (!fullscreenEl) { return; }
  57533. if (document.exitFullscreen) {
  57534. document.exitFullscreen();
  57535. } else if (document.mozCancelFullScreen) {
  57536. document.mozCancelFullScreen();
  57537. } else if (document.webkitExitFullscreen) {
  57538. document.webkitExitFullscreen();
  57539. }
  57540. }
  57541. function setupCanvas (sceneEl) {
  57542. var canvasEl;
  57543. canvasEl = document.createElement('canvas');
  57544. canvasEl.classList.add('a-canvas');
  57545. // Mark canvas as provided/injected by A-Frame.
  57546. canvasEl.dataset.aframeCanvas = true;
  57547. sceneEl.appendChild(canvasEl);
  57548. document.addEventListener('fullscreenchange', onFullScreenChange);
  57549. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  57550. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  57551. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  57552. // Prevent overscroll on mobile.
  57553. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  57554. // Set canvas on scene.
  57555. sceneEl.canvas = canvasEl;
  57556. sceneEl.emit('render-target-loaded', {target: canvasEl});
  57557. // For unknown reasons a synchronous resize does not work on desktop when
  57558. // entering/exiting fullscreen.
  57559. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  57560. function onFullScreenChange () {
  57561. var fullscreenEl =
  57562. document.fullscreenElement ||
  57563. document.mozFullScreenElement ||
  57564. document.webkitFullscreenElement;
  57565. // No fullscren element === exit fullscreen
  57566. if (!fullscreenEl) { sceneEl.exitVR(); }
  57567. document.activeElement.blur();
  57568. document.body.focus();
  57569. }
  57570. }
  57571. module.exports.setupCanvas = setupCanvas; // For testing.
  57572. },{"../../lib/three":180,"../../utils/":206,"../../utils/ios-orientationchange-blank-bug":207,"../a-entity":128,"../a-node":130,"../a-register-element":131,"../system":143,"./loadingScreen":136,"./metaTags":137,"./postMessage":138,"./scenes":139,"./wakelock":140}],136:[function(_dereq_,module,exports){
  57573. /* global THREE */
  57574. var utils = _dereq_('../../utils/');
  57575. var styleParser = utils.styleParser;
  57576. var sceneEl;
  57577. var titleEl;
  57578. var getSceneCanvasSize;
  57579. var ATTR_NAME = 'loading-screen';
  57580. var LOADER_TITLE_CLASS = 'a-loader-title';
  57581. module.exports.setup = function setup (el, getCanvasSize) {
  57582. sceneEl = el;
  57583. getSceneCanvasSize = getCanvasSize;
  57584. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  57585. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  57586. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  57587. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  57588. var loaderScene;
  57589. var sphereGeometry;
  57590. var sphereMaterial;
  57591. var sphereMesh1;
  57592. var sphereMesh2;
  57593. var sphereMesh3;
  57594. var camera;
  57595. var clock;
  57596. var time;
  57597. var render;
  57598. if (!loaderEnabled) { return; }
  57599. // Setup Scene.
  57600. loaderScene = new THREE.Scene();
  57601. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  57602. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  57603. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  57604. sphereMesh2 = sphereMesh1.clone();
  57605. sphereMesh3 = sphereMesh1.clone();
  57606. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  57607. clock = new THREE.Clock();
  57608. time = 0;
  57609. render = function () {
  57610. sceneEl.renderer.render(loaderScene, camera);
  57611. time = clock.getElapsedTime() % 4;
  57612. sphereMesh1.visible = time >= 1;
  57613. sphereMesh2.visible = time >= 2;
  57614. sphereMesh3.visible = time >= 3;
  57615. };
  57616. loaderScene.background = new THREE.Color(backgroundColor);
  57617. loaderScene.add(camera);
  57618. sphereMesh1.position.set(-1, 0, -15);
  57619. sphereMesh2.position.set(0, 0, -15);
  57620. sphereMesh3.position.set(1, 0, -15);
  57621. camera.add(sphereMesh1);
  57622. camera.add(sphereMesh2);
  57623. camera.add(sphereMesh3);
  57624. setupTitle();
  57625. // Delay 200ms to avoid loader flashes.
  57626. setTimeout(function () {
  57627. if (sceneEl.hasLoaded) { return; }
  57628. resize(camera);
  57629. titleEl.style.display = 'block';
  57630. window.addEventListener('resize', function () { resize(camera); });
  57631. sceneEl.renderer.setAnimationLoop(render);
  57632. }, 200);
  57633. };
  57634. module.exports.remove = function remove () {
  57635. window.removeEventListener('resize', resize);
  57636. if (!titleEl) { return; }
  57637. // Hide title.
  57638. titleEl.style.display = 'none';
  57639. };
  57640. function resize (camera) {
  57641. var embedded = sceneEl.hasAttribute('embedded');
  57642. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  57643. camera.aspect = size.width / size.height;
  57644. camera.updateProjectionMatrix();
  57645. // Notify renderer of size change.
  57646. sceneEl.renderer.setSize(size.width, size.height, false);
  57647. }
  57648. function setupTitle () {
  57649. titleEl = document.createElement('div');
  57650. titleEl.className = LOADER_TITLE_CLASS;
  57651. titleEl.innerHTML = document.title;
  57652. titleEl.style.display = 'none';
  57653. sceneEl.appendChild(titleEl);
  57654. }
  57655. },{"../../utils/":206}],137:[function(_dereq_,module,exports){
  57656. var constants = _dereq_('../../constants/');
  57657. var extend = _dereq_('../../utils').extend;
  57658. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  57659. 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'}),
  57660. // W3C-standardised meta tags.
  57661. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  57662. Meta({name: 'theme-color', content: 'black'})
  57663. ];
  57664. var MOBILE_IOS_HEAD_TAGS = [
  57665. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  57666. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  57667. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  57668. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  57669. ];
  57670. function Meta (attrs) {
  57671. return {
  57672. tagName: 'meta',
  57673. attributes: attrs,
  57674. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  57675. };
  57676. }
  57677. function Link (attrs) {
  57678. return {
  57679. tagName: 'link',
  57680. attributes: attrs,
  57681. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  57682. };
  57683. }
  57684. /**
  57685. * Injects the necessary metatags in the document for mobile support:
  57686. * 1. Prevent the user to zoom in the document.
  57687. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  57688. * values and the canvas is properly scaled.
  57689. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  57690. * iOS.
  57691. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  57692. *
  57693. * @param {object} scene - Scene element
  57694. * @returns {Array}
  57695. */
  57696. module.exports.inject = function injectHeadTags (scene) {
  57697. var headEl = document.head;
  57698. var headScriptEl = headEl.querySelector('script');
  57699. var tag;
  57700. var headTags = [];
  57701. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  57702. if (scene.isIOS) {
  57703. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  57704. }
  57705. return headTags;
  57706. function createAndInjectTag (tagObj) {
  57707. if (!tagObj || tagObj.exists()) { return; }
  57708. tag = createTag(tagObj);
  57709. if (!tag) { return; }
  57710. if (headScriptEl) {
  57711. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  57712. } else {
  57713. headEl.appendChild(tag);
  57714. }
  57715. headTags.push(tag);
  57716. }
  57717. };
  57718. function createTag (tagObj) {
  57719. if (!tagObj || !tagObj.tagName) { return; }
  57720. var meta = document.createElement(tagObj.tagName);
  57721. meta.setAttribute(constants.AFRAME_INJECTED, '');
  57722. return extend(meta, tagObj.attributes);
  57723. }
  57724. },{"../../constants/":124,"../../utils":206}],138:[function(_dereq_,module,exports){
  57725. var bind = _dereq_('../../utils/bind');
  57726. var isIframed = _dereq_('../../utils/').isIframed;
  57727. /**
  57728. * Provides a post message API for scenes contained
  57729. * in an iframe.
  57730. */
  57731. module.exports = function initPostMessageAPI (scene) {
  57732. // Handles fullscreen behavior when inside an iframe.
  57733. if (!isIframed()) { return; }
  57734. // postMessage API handler
  57735. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  57736. };
  57737. function postMessageAPIHandler (event) {
  57738. var scene = this;
  57739. if (!event.data) { return; }
  57740. switch (event.data.type) {
  57741. case 'vr': {
  57742. switch (event.data.data) {
  57743. case 'enter':
  57744. scene.enterVR();
  57745. break;
  57746. case 'exit':
  57747. scene.exitVR();
  57748. break;
  57749. }
  57750. }
  57751. }
  57752. }
  57753. },{"../../utils/":206,"../../utils/bind":200}],139:[function(_dereq_,module,exports){
  57754. /*
  57755. Scene index for keeping track of created scenes.
  57756. */
  57757. module.exports = [];
  57758. },{}],140:[function(_dereq_,module,exports){
  57759. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  57760. module.exports = function initWakelock (scene) {
  57761. if (!scene.isMobile) { return; }
  57762. var wakelock = scene.wakelock = new Wakelock();
  57763. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  57764. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  57765. };
  57766. },{"../../../vendor/wakelock/wakelock":221}],141:[function(_dereq_,module,exports){
  57767. var utils = _dereq_('../utils/');
  57768. var PropertyTypes = _dereq_('./propertyTypes');
  57769. var debug = utils.debug;
  57770. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  57771. var propertyTypes = PropertyTypes.propertyTypes;
  57772. var warn = debug('core:schema:warn');
  57773. /**
  57774. * A schema is classified as a schema for a single property if:
  57775. * - `type` is defined on the schema as a string.
  57776. * - OR `default` is defined on the schema, as a reserved keyword.
  57777. * - OR schema is empty.
  57778. */
  57779. function isSingleProperty (schema) {
  57780. if ('type' in schema) {
  57781. return typeof schema.type === 'string';
  57782. }
  57783. return 'default' in schema;
  57784. }
  57785. module.exports.isSingleProperty = isSingleProperty;
  57786. /**
  57787. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  57788. *
  57789. * @param {object} schema
  57790. * @param {string} componentName
  57791. * @returns {object} Schema.
  57792. */
  57793. module.exports.process = function (schema, componentName) {
  57794. var propName;
  57795. // For single property schema, run processPropDefinition over the whole schema.
  57796. if (isSingleProperty(schema)) {
  57797. return processPropertyDefinition(schema, componentName);
  57798. }
  57799. // For multi-property schema, run processPropDefinition over each property definition.
  57800. for (propName in schema) {
  57801. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  57802. }
  57803. return schema;
  57804. };
  57805. /**
  57806. * Inject default value, parser, stringifier for single property.
  57807. *
  57808. * @param {object} propDefinition
  57809. * @param {string} componentName
  57810. */
  57811. function processPropertyDefinition (propDefinition, componentName) {
  57812. var defaultVal = propDefinition.default;
  57813. var isCustomType;
  57814. var propType;
  57815. var typeName = propDefinition.type;
  57816. // Type inference.
  57817. if (!propDefinition.type) {
  57818. if (defaultVal !== undefined &&
  57819. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  57820. // Type inference.
  57821. typeName = typeof defaultVal;
  57822. } else if (Array.isArray(defaultVal)) {
  57823. typeName = 'array';
  57824. } else {
  57825. // Fall back to string.
  57826. typeName = 'string';
  57827. }
  57828. } else if (propDefinition.type === 'bool') {
  57829. typeName = 'boolean';
  57830. } else if (propDefinition.type === 'float') {
  57831. typeName = 'number';
  57832. }
  57833. propType = propertyTypes[typeName];
  57834. if (!propType) {
  57835. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  57836. }
  57837. // Fill in parse and stringify using property types.
  57838. isCustomType = !!propDefinition.parse;
  57839. propDefinition.parse = propDefinition.parse || propType.parse;
  57840. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  57841. // Fill in type name.
  57842. propDefinition.type = typeName;
  57843. // Check that default value exists.
  57844. if ('default' in propDefinition) {
  57845. // Check that default values are valid.
  57846. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  57847. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  57848. '` in component `' + componentName + '`');
  57849. }
  57850. } else {
  57851. // Fill in default value.
  57852. propDefinition.default = propType.default;
  57853. }
  57854. return propDefinition;
  57855. }
  57856. module.exports.processPropertyDefinition = processPropertyDefinition;
  57857. /**
  57858. * Parse propData using schema. Use default values if not existing in propData.
  57859. *
  57860. * @param {object} propData - Unparsed properties.
  57861. * @param {object} schema - Property types definition.
  57862. * @param {boolean} getPartialData - Whether to return full component data or just the data
  57863. * with keys in `propData`.
  57864. * @param {string } componentName - Name of the component, used for the property warning.
  57865. * @param {boolean} silent - Suppress warning messages.
  57866. */
  57867. module.exports.parseProperties = (function () {
  57868. var propNames = [];
  57869. return function (propData, schema, getPartialData, componentName, silent) {
  57870. var i;
  57871. var propName;
  57872. var propDefinition;
  57873. var propValue;
  57874. propNames.length = 0;
  57875. for (propName in (getPartialData ? propData : schema)) {
  57876. if (getPartialData && propData[propName] === undefined) { continue; }
  57877. propNames.push(propName);
  57878. }
  57879. if (propData === null || typeof propData !== 'object') { return propData; }
  57880. // Validation errors.
  57881. for (propName in propData) {
  57882. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  57883. warn('Unknown property `' + propName +
  57884. '` for component/system `' + componentName + '`.');
  57885. }
  57886. }
  57887. for (i = 0; i < propNames.length; i++) {
  57888. propName = propNames[i];
  57889. propDefinition = schema[propName];
  57890. propValue = propData[propName];
  57891. if (!(schema[propName])) { return; }
  57892. propData[propName] = parseProperty(propValue, propDefinition);
  57893. }
  57894. return propData;
  57895. };
  57896. })();
  57897. /**
  57898. * Deserialize a single property.
  57899. */
  57900. function parseProperty (value, propDefinition) {
  57901. // Use default value if value is falsy.
  57902. if (value === undefined || value === null || value === '') {
  57903. value = propDefinition.default;
  57904. if (Array.isArray(value)) { value = value.slice(); }
  57905. }
  57906. // Invoke property type parser.
  57907. return propDefinition.parse(value, propDefinition.default);
  57908. }
  57909. module.exports.parseProperty = parseProperty;
  57910. /**
  57911. * Serialize a group of properties.
  57912. */
  57913. module.exports.stringifyProperties = function (propData, schema) {
  57914. var propName;
  57915. var propDefinition;
  57916. var propValue;
  57917. var stringifiedData = {};
  57918. var value;
  57919. for (propName in propData) {
  57920. propDefinition = schema[propName];
  57921. propValue = propData[propName];
  57922. value = propValue;
  57923. if (typeof value === 'object') {
  57924. value = stringifyProperty(propValue, propDefinition);
  57925. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  57926. }
  57927. stringifiedData[propName] = value;
  57928. }
  57929. return stringifiedData;
  57930. };
  57931. /**
  57932. * Serialize a single property.
  57933. */
  57934. function stringifyProperty (value, propDefinition) {
  57935. // This function stringifies but it's used in a context where
  57936. // there's always second stringification pass. By returning the original
  57937. // value when it's not an object we save one unnecessary call
  57938. // to JSON.stringify.
  57939. if (typeof value !== 'object') { return value; }
  57940. // if there's no schema for the property we use standar JSON stringify
  57941. if (!propDefinition || value === null) { return JSON.stringify(value); }
  57942. return propDefinition.stringify(value);
  57943. }
  57944. module.exports.stringifyProperty = stringifyProperty;
  57945. },{"../utils/":206,"./propertyTypes":134}],142:[function(_dereq_,module,exports){
  57946. var schema = _dereq_('./schema');
  57947. var processSchema = schema.process;
  57948. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  57949. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  57950. var THREE = _dereq_('../lib/three');
  57951. var utils = _dereq_('../utils');
  57952. // A-Frame properties to three.js uniform types.
  57953. var propertyToThreeMapping = {
  57954. array: 'v3',
  57955. color: 'v3',
  57956. int: 'i',
  57957. number: 'f',
  57958. map: 't',
  57959. time: 'f',
  57960. vec2: 'v2',
  57961. vec3: 'v3',
  57962. vec4: 'v4'
  57963. };
  57964. /**
  57965. * Shader class definition.
  57966. *
  57967. * Shaders extend the material component API so you can create your own library
  57968. * of customized materials
  57969. *
  57970. */
  57971. var Shader = module.exports.Shader = function () {};
  57972. Shader.prototype = {
  57973. /**
  57974. * Contains the type schema and defaults for the data values.
  57975. * Data is coerced into the types of the values of the defaults.
  57976. */
  57977. schema: {},
  57978. vertexShader:
  57979. 'void main() {' +
  57980. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  57981. '}',
  57982. fragmentShader:
  57983. 'void main() {' +
  57984. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  57985. '}',
  57986. /**
  57987. * Init handler. Similar to attachedCallback.
  57988. * Called during shader initialization and is only run once.
  57989. */
  57990. init: function (data) {
  57991. this.attributes = this.initVariables(data, 'attribute');
  57992. this.uniforms = this.initVariables(data, 'uniform');
  57993. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  57994. // attributes: this.attributes,
  57995. uniforms: this.uniforms,
  57996. vertexShader: this.vertexShader,
  57997. fragmentShader: this.fragmentShader
  57998. });
  57999. return this.material;
  58000. },
  58001. initVariables: function (data, type) {
  58002. var key;
  58003. var schema = this.schema;
  58004. var variables = {};
  58005. var varType;
  58006. for (key in schema) {
  58007. if (schema[key].is !== type) { continue; }
  58008. varType = propertyToThreeMapping[schema[key].type];
  58009. variables[key] = {
  58010. type: varType,
  58011. value: undefined // Let updateVariables handle setting these.
  58012. };
  58013. }
  58014. return variables;
  58015. },
  58016. /**
  58017. * Update handler. Similar to attributeChangedCallback.
  58018. * Called whenever the associated material data changes.
  58019. *
  58020. * @param {object} data - New material data.
  58021. */
  58022. update: function (data) {
  58023. this.updateVariables(data, 'attribute');
  58024. this.updateVariables(data, 'uniform');
  58025. },
  58026. updateVariables: function (data, type) {
  58027. var key;
  58028. var materialKey;
  58029. var schema = this.schema;
  58030. var variables;
  58031. variables = type === 'uniform' ? this.uniforms : this.attributes;
  58032. for (key in data) {
  58033. if (!schema[key] || schema[key].is !== type) { continue; }
  58034. if (schema[key].type === 'map') {
  58035. // If data unchanged, get out early.
  58036. if (!variables[key] || variables[key].value === data[key]) { continue; }
  58037. // Special handling is needed for textures.
  58038. materialKey = '_texture_' + key;
  58039. // We can't actually set the variable correctly until we've loaded the texture.
  58040. this.setMapOnTextureLoad(variables, key, materialKey);
  58041. // Kick off the texture update now that handler is added.
  58042. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  58043. continue;
  58044. }
  58045. variables[key].value = this.parseValue(schema[key].type, data[key]);
  58046. variables[key].needsUpdate = true;
  58047. }
  58048. },
  58049. parseValue: function (type, value) {
  58050. var color;
  58051. switch (type) {
  58052. case 'vec2': {
  58053. return new THREE.Vector2(value.x, value.y);
  58054. }
  58055. case 'vec3': {
  58056. return new THREE.Vector3(value.x, value.y, value.z);
  58057. }
  58058. case 'vec4': {
  58059. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  58060. }
  58061. case 'color': {
  58062. color = new THREE.Color(value);
  58063. return new THREE.Vector3(color.r, color.g, color.b);
  58064. }
  58065. case 'map': {
  58066. return THREE.ImageUtils.loadTexture(value);
  58067. }
  58068. default: {
  58069. return value;
  58070. }
  58071. }
  58072. },
  58073. setMapOnTextureLoad: function (variables, key, materialKey) {
  58074. var self = this;
  58075. this.el.addEventListener('materialtextureloaded', function () {
  58076. variables[key].value = self.material[materialKey];
  58077. variables[key].needsUpdate = true;
  58078. });
  58079. }
  58080. };
  58081. /**
  58082. * Registers a shader to A-Frame.
  58083. *
  58084. * @param {string} name - shader name.
  58085. * @param {object} definition - shader property and methods.
  58086. * @returns {object} Shader.
  58087. */
  58088. module.exports.registerShader = function (name, definition) {
  58089. var NewShader;
  58090. var proto = {};
  58091. // Format definition object to prototype object.
  58092. Object.keys(definition).forEach(function (key) {
  58093. proto[key] = {
  58094. value: definition[key],
  58095. writable: true
  58096. };
  58097. });
  58098. if (shaders[name]) {
  58099. throw new Error('The shader ' + name + ' has been already registered');
  58100. }
  58101. NewShader = function () { Shader.call(this); };
  58102. NewShader.prototype = Object.create(Shader.prototype, proto);
  58103. NewShader.prototype.name = name;
  58104. NewShader.prototype.constructor = NewShader;
  58105. shaders[name] = {
  58106. Shader: NewShader,
  58107. schema: processSchema(NewShader.prototype.schema)
  58108. };
  58109. shaderNames.push(name);
  58110. return NewShader;
  58111. };
  58112. },{"../lib/three":180,"../utils":206,"./schema":141}],143:[function(_dereq_,module,exports){
  58113. var components = _dereq_('./component');
  58114. var schema = _dereq_('./schema');
  58115. var utils = _dereq_('../utils/');
  58116. var parseProperties = schema.parseProperties;
  58117. var parseProperty = schema.parseProperty;
  58118. var processSchema = schema.process;
  58119. var isSingleProp = schema.isSingleProperty;
  58120. var styleParser = utils.styleParser;
  58121. var systems = module.exports.systems = {}; // Keep track of registered systems.
  58122. /**
  58123. * System class definition.
  58124. *
  58125. * Systems provide global scope and services to a group of instantiated components of the
  58126. * same class. They can also help abstract logic away from components such that components
  58127. * only have to worry about data.
  58128. *
  58129. * For example, a physics component that creates a physics world that oversees
  58130. * all entities with a physics or rigid body component.
  58131. *
  58132. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  58133. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  58134. * setAttribute behavior).
  58135. *
  58136. * @member {string} name - Name that system is registered under.
  58137. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  58138. */
  58139. var System = module.exports.System = function (sceneEl) {
  58140. var component = components && components.components[this.name];
  58141. // Set reference to scene.
  58142. this.el = sceneEl;
  58143. this.sceneEl = sceneEl;
  58144. // Set reference to matching component (if exists).
  58145. if (component) { component.Component.prototype.system = this; }
  58146. // Process system configuration.
  58147. this.buildData();
  58148. this.init();
  58149. this.update({});
  58150. };
  58151. System.prototype = {
  58152. /**
  58153. * Schema to configure system.
  58154. */
  58155. schema: {},
  58156. /**
  58157. * Init handler. Called during scene initialization and is only run once.
  58158. * Systems can use this to set initial state.
  58159. */
  58160. init: function () { /* no-op */ },
  58161. /**
  58162. * Update handler. Called during scene attribute updates.
  58163. * Systems can use this to dynamically update their state.
  58164. */
  58165. update: function (oldData) { /* no-op */ },
  58166. /**
  58167. * Build data and call update handler.
  58168. *
  58169. * @private
  58170. */
  58171. updateProperties: function (rawData) {
  58172. var oldData = this.data;
  58173. if (!Object.keys(schema).length) { return; }
  58174. this.buildData(rawData);
  58175. this.update(oldData);
  58176. },
  58177. /**
  58178. * Parse data.
  58179. */
  58180. buildData: function (rawData) {
  58181. var schema = this.schema;
  58182. if (!Object.keys(schema).length) { return; }
  58183. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  58184. if (isSingleProp(schema)) {
  58185. this.data = parseProperty(rawData, schema);
  58186. } else {
  58187. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  58188. }
  58189. },
  58190. /**
  58191. * Tick handler.
  58192. * Called on each tick of the scene render loop.
  58193. * Affected by play and pause.
  58194. *
  58195. * @param {number} time - Scene tick time.
  58196. * @param {number} timeDelta - Difference in current render time and previous render time.
  58197. */
  58198. tick: undefined,
  58199. /**
  58200. * Tock handler.
  58201. * Called on each tock of the scene render loop.
  58202. * Affected by play and pause.
  58203. *
  58204. * @param {number} time - Scene tick time.
  58205. * @param {number} timeDelta - Difference in current render time and previous render time.
  58206. */
  58207. tock: undefined,
  58208. /**
  58209. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  58210. */
  58211. play: function () { /* no-op */ },
  58212. /**
  58213. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  58214. */
  58215. pause: function () { /* no-op */ }
  58216. };
  58217. /**
  58218. * Registers a system to A-Frame.
  58219. *
  58220. * @param {string} name - Component name.
  58221. * @param {object} definition - Component property and methods.
  58222. * @returns {object} Component.
  58223. */
  58224. module.exports.registerSystem = function (name, definition) {
  58225. var i;
  58226. var NewSystem;
  58227. var proto = {};
  58228. var scenes = utils.findAllScenes(document);
  58229. // Format definition object to prototype object.
  58230. Object.keys(definition).forEach(function (key) {
  58231. proto[key] = {
  58232. value: definition[key],
  58233. writable: true
  58234. };
  58235. });
  58236. if (systems[name]) {
  58237. throw new Error('The system `' + name + '` has been already registered. ' +
  58238. 'Check that you are not loading two versions of the same system ' +
  58239. 'or two different systems of the same name.');
  58240. }
  58241. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  58242. NewSystem.prototype = Object.create(System.prototype, proto);
  58243. NewSystem.prototype.name = name;
  58244. NewSystem.prototype.constructor = NewSystem;
  58245. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  58246. systems[name] = NewSystem;
  58247. // Initialize systems for existing scenes
  58248. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  58249. };
  58250. },{"../utils/":206,"./component":132,"./schema":141}],144:[function(_dereq_,module,exports){
  58251. _dereq_('./pivot');
  58252. },{"./pivot":145}],145:[function(_dereq_,module,exports){
  58253. var registerComponent = _dereq_('../../core/component').registerComponent;
  58254. var THREE = _dereq_('../../lib/three');
  58255. var originalPosition = new THREE.Vector3();
  58256. var originalRotation = new THREE.Vector3();
  58257. /**
  58258. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  58259. */
  58260. registerComponent('pivot', {
  58261. dependencies: ['position'],
  58262. schema: {type: 'vec3'},
  58263. init: function () {
  58264. var data = this.data;
  58265. var el = this.el;
  58266. var originalParent = el.object3D.parent;
  58267. var originalGroup = el.object3D;
  58268. var outerGroup = new THREE.Group();
  58269. originalPosition.copy(originalGroup.position);
  58270. originalRotation.copy(originalGroup.rotation);
  58271. // Detach current group from parent.
  58272. originalParent.remove(originalGroup);
  58273. outerGroup.add(originalGroup);
  58274. // Set new group as the outer group.
  58275. originalParent.add(outerGroup);
  58276. // Set outer group as new object3D.
  58277. el.object3D = outerGroup;
  58278. // Apply pivot to original group.
  58279. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  58280. // Offset the pivot so that world position not affected.
  58281. // And restore position onto outer group.
  58282. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  58283. data.z + originalPosition.z);
  58284. // Transfer rotation to outer group.
  58285. outerGroup.rotation.copy(originalGroup.rotation);
  58286. originalGroup.rotation.set(0, 0, 0);
  58287. }
  58288. });
  58289. },{"../../core/component":132,"../../lib/three":180}],146:[function(_dereq_,module,exports){
  58290. /**
  58291. * Common mesh defaults, mappings, and transforms.
  58292. */
  58293. var components = _dereq_('../../core/component').components;
  58294. var shaders = _dereq_('../../core/shader').shaders;
  58295. var utils = _dereq_('../../utils/');
  58296. var materialMappings = {};
  58297. Object.keys(components.material.schema).forEach(addMapping);
  58298. Object.keys(shaders.standard.schema).forEach(addMapping);
  58299. function addMapping (prop) {
  58300. // To hyphenated.
  58301. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58302. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  58303. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  58304. materialMappings[htmlAttrName] = 'material.' + prop;
  58305. }
  58306. module.exports = function getMeshMixin () {
  58307. return {
  58308. defaultComponents: {material: {}},
  58309. mappings: utils.extend({}, materialMappings)
  58310. };
  58311. };
  58312. },{"../../core/component":132,"../../core/shader":142,"../../utils/":206}],147:[function(_dereq_,module,exports){
  58313. _dereq_('./primitives/a-camera');
  58314. _dereq_('./primitives/a-cursor');
  58315. _dereq_('./primitives/a-curvedimage');
  58316. _dereq_('./primitives/a-gltf-model');
  58317. _dereq_('./primitives/a-image');
  58318. _dereq_('./primitives/a-light');
  58319. _dereq_('./primitives/a-link');
  58320. _dereq_('./primitives/a-obj-model');
  58321. _dereq_('./primitives/a-sky');
  58322. _dereq_('./primitives/a-sound');
  58323. _dereq_('./primitives/a-text');
  58324. _dereq_('./primitives/a-video');
  58325. _dereq_('./primitives/a-videosphere');
  58326. _dereq_('./primitives/meshPrimitives');
  58327. },{"./primitives/a-camera":149,"./primitives/a-cursor":150,"./primitives/a-curvedimage":151,"./primitives/a-gltf-model":152,"./primitives/a-image":153,"./primitives/a-light":154,"./primitives/a-link":155,"./primitives/a-obj-model":156,"./primitives/a-sky":157,"./primitives/a-sound":158,"./primitives/a-text":159,"./primitives/a-video":160,"./primitives/a-videosphere":161,"./primitives/meshPrimitives":162}],148:[function(_dereq_,module,exports){
  58328. var AEntity = _dereq_('../../core/a-entity');
  58329. var components = _dereq_('../../core/component').components;
  58330. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  58331. var utils = _dereq_('../../utils/');
  58332. var debug = utils.debug;
  58333. var setComponentProperty = utils.entity.setComponentProperty;
  58334. var log = debug('extras:primitives:debug');
  58335. var warn = debug('extras:primitives:warn');
  58336. var primitives = module.exports.primitives = {};
  58337. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  58338. name = name.toLowerCase();
  58339. log('Registering <%s>', name);
  58340. // Deprecation warning for defaultAttributes usage.
  58341. if (definition.defaultAttributes) {
  58342. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  58343. }
  58344. var primitive = registerElement(name, {
  58345. prototype: Object.create(AEntity.prototype, {
  58346. defaultComponentsFromPrimitive: {
  58347. value: definition.defaultComponents || definition.defaultAttributes || {}
  58348. },
  58349. deprecated: {value: definition.deprecated || null},
  58350. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  58351. mappings: {value: definition.mappings || {}},
  58352. createdCallback: {
  58353. value: function () {
  58354. if (definition.deprecated) { console.warn(definition.deprecated); }
  58355. this.resolveMappingCollisions();
  58356. }
  58357. },
  58358. /**
  58359. * If a mapping collides with a registered component name
  58360. * it renames the mapping to componentname-property
  58361. */
  58362. resolveMappingCollisions: {
  58363. value: function () {
  58364. var mappings = this.mappings;
  58365. var self = this;
  58366. Object.keys(mappings).forEach(function resolveCollision (key) {
  58367. var newAttribute;
  58368. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  58369. if (components[key]) {
  58370. newAttribute = mappings[key].replace('.', '-');
  58371. mappings[newAttribute] = mappings[key];
  58372. delete mappings[key];
  58373. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  58374. 'The attribute ' + key + ' has the same name as a registered component and' +
  58375. ' has been renamed to ' + newAttribute);
  58376. }
  58377. });
  58378. }
  58379. },
  58380. getExtraComponents: {
  58381. value: function () {
  58382. var attr;
  58383. var data;
  58384. var i;
  58385. var mapping;
  58386. var mixins;
  58387. var path;
  58388. var self = this;
  58389. // Gather component data from default components.
  58390. data = utils.clone(this.defaultComponentsFromPrimitive);
  58391. // Factor in mixins to overwrite default components.
  58392. mixins = this.getAttribute('mixin');
  58393. if (mixins) {
  58394. mixins = mixins.trim().split(' ');
  58395. mixins.forEach(function applyMixin (mixinId) {
  58396. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  58397. Object.keys(mixinComponents).forEach(function setComponent (name) {
  58398. data[name] = extend(data[name], mixinComponents[name]);
  58399. });
  58400. });
  58401. }
  58402. // Gather component data from mappings.
  58403. for (i = 0; i < this.attributes.length; i++) {
  58404. attr = this.attributes[i];
  58405. mapping = this.mappings[attr.name];
  58406. if (mapping) {
  58407. path = utils.entity.getComponentPropertyPath(mapping);
  58408. if (path.constructor === Array) {
  58409. data[path[0]] = data[path[0]] || {};
  58410. data[path[0]][path[1]] = attr.value.trim();
  58411. } else {
  58412. data[path] = attr.value.trim();
  58413. }
  58414. continue;
  58415. }
  58416. }
  58417. return data;
  58418. /**
  58419. * For the base to be extensible, both objects must be pure JavaScript objects.
  58420. * The function assumes that base is undefined, or null or a pure object.
  58421. */
  58422. function extend (base, extension) {
  58423. if (isUndefined(base)) {
  58424. return copy(extension);
  58425. }
  58426. if (isUndefined(extension)) {
  58427. return copy(base);
  58428. }
  58429. if (isPureObject(base) && isPureObject(extension)) {
  58430. return utils.extendDeep(base, extension);
  58431. }
  58432. return copy(extension);
  58433. }
  58434. function isUndefined (value) {
  58435. return typeof value === 'undefined';
  58436. }
  58437. function copy (value) {
  58438. if (isPureObject(value)) {
  58439. return utils.extendDeep({}, value);
  58440. }
  58441. return value;
  58442. }
  58443. function isPureObject (value) {
  58444. return value !== null && value.constructor === Object;
  58445. }
  58446. }
  58447. },
  58448. /**
  58449. * Sync to attribute to component property whenever mapped attribute changes.
  58450. * If attribute is mapped to a component property, set the component property using
  58451. * the attribute value.
  58452. */
  58453. attributeChangedCallback: {
  58454. value: function (attr, oldVal, value) {
  58455. var componentName = this.mappings[attr];
  58456. if (attr in this.deprecatedMappings) {
  58457. console.warn(this.deprecatedMappings[attr]);
  58458. }
  58459. if (!attr || !componentName) { return; }
  58460. // Set value.
  58461. setComponentProperty(this, componentName, value);
  58462. }
  58463. }
  58464. })
  58465. });
  58466. // Store.
  58467. primitives[name] = primitive;
  58468. return primitive;
  58469. };
  58470. /**
  58471. * Add component mappings using schema.
  58472. */
  58473. function addComponentMapping (componentName, mappings) {
  58474. var schema = components[componentName].schema;
  58475. Object.keys(schema).map(function (prop) {
  58476. // Hyphenate where there is camelCase.
  58477. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58478. // If there is a mapping collision, prefix with component name and hyphen.
  58479. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  58480. mappings[attrName] = componentName + '.' + prop;
  58481. });
  58482. }
  58483. /**
  58484. * Helper to define a primitive, building mappings using a component schema.
  58485. */
  58486. function definePrimitive (tagName, defaultComponents, mappings) {
  58487. // If no initial mappings provided, start from empty map.
  58488. mappings = mappings || {};
  58489. // From the default components, add mapping automagically.
  58490. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  58491. addComponentMapping(componentName, mappings);
  58492. });
  58493. // Register the primitive.
  58494. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  58495. defaultComponents: defaultComponents,
  58496. mappings: mappings
  58497. }));
  58498. }
  58499. module.exports.definePrimitive = definePrimitive;
  58500. },{"../../core/a-entity":128,"../../core/a-register-element":131,"../../core/component":132,"../../utils/":206}],149:[function(_dereq_,module,exports){
  58501. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58502. registerPrimitive('a-camera', {
  58503. defaultComponents: {
  58504. 'camera': {},
  58505. 'look-controls': {},
  58506. 'wasd-controls': {},
  58507. 'position': {x: 0, y: 1.6, z: 0}
  58508. },
  58509. mappings: {
  58510. active: 'camera.active',
  58511. far: 'camera.far',
  58512. fov: 'camera.fov',
  58513. 'look-controls-enabled': 'look-controls.enabled',
  58514. near: 'camera.near',
  58515. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  58516. 'wasd-controls-enabled': 'wasd-controls.enabled',
  58517. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  58518. zoom: 'camera.zoom'
  58519. }
  58520. });
  58521. },{"../primitives":148}],150:[function(_dereq_,module,exports){
  58522. var getMeshMixin = _dereq_('../getMeshMixin');
  58523. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58524. var utils = _dereq_('../../../utils/');
  58525. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  58526. defaultComponents: {
  58527. cursor: {},
  58528. geometry: {
  58529. primitive: 'ring',
  58530. radiusOuter: 0.016,
  58531. radiusInner: 0.01,
  58532. segmentsTheta: 32
  58533. },
  58534. material: {
  58535. color: '#000',
  58536. shader: 'flat',
  58537. opacity: 0.8
  58538. },
  58539. position: {
  58540. x: 0,
  58541. y: 0,
  58542. z: -1
  58543. }
  58544. },
  58545. mappings: {
  58546. far: 'raycaster.far',
  58547. fuse: 'cursor.fuse',
  58548. 'fuse-timeout': 'cursor.fuseTimeout',
  58549. interval: 'raycaster.interval',
  58550. objects: 'raycaster.objects'
  58551. }
  58552. }));
  58553. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],151:[function(_dereq_,module,exports){
  58554. var getMeshMixin = _dereq_('../getMeshMixin');
  58555. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58556. var utils = _dereq_('../../../utils/');
  58557. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  58558. defaultComponents: {
  58559. geometry: {
  58560. height: 1,
  58561. primitive: 'cylinder',
  58562. radius: 2,
  58563. segmentsRadial: 48,
  58564. thetaLength: 270,
  58565. openEnded: true,
  58566. thetaStart: 0
  58567. },
  58568. material: {
  58569. color: '#FFF',
  58570. shader: 'flat',
  58571. side: 'double',
  58572. transparent: true,
  58573. repeat: '-1 1'
  58574. }
  58575. },
  58576. mappings: {
  58577. height: 'geometry.height',
  58578. 'open-ended': 'geometry.openEnded',
  58579. radius: 'geometry.radius',
  58580. segments: 'geometry.segmentsRadial',
  58581. start: 'geometry.thetaStart',
  58582. 'theta-length': 'geometry.thetaLength',
  58583. 'theta-start': 'geometry.thetaStart',
  58584. 'width': 'geometry.thetaLength'
  58585. }
  58586. }));
  58587. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],152:[function(_dereq_,module,exports){
  58588. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58589. registerPrimitive('a-gltf-model', {
  58590. mappings: {
  58591. src: 'gltf-model'
  58592. }
  58593. });
  58594. },{"../primitives":148}],153:[function(_dereq_,module,exports){
  58595. var getMeshMixin = _dereq_('../getMeshMixin');
  58596. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58597. var utils = _dereq_('../../../utils/');
  58598. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  58599. defaultComponents: {
  58600. geometry: {
  58601. primitive: 'plane'
  58602. },
  58603. material: {
  58604. color: '#FFF',
  58605. shader: 'flat',
  58606. side: 'double',
  58607. transparent: true
  58608. }
  58609. },
  58610. mappings: {
  58611. height: 'geometry.height',
  58612. width: 'geometry.width'
  58613. }
  58614. }));
  58615. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],154:[function(_dereq_,module,exports){
  58616. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58617. registerPrimitive('a-light', {
  58618. defaultComponents: {
  58619. light: {}
  58620. },
  58621. mappings: {
  58622. angle: 'light.angle',
  58623. color: 'light.color',
  58624. 'ground-color': 'light.groundColor',
  58625. decay: 'light.decay',
  58626. distance: 'light.distance',
  58627. intensity: 'light.intensity',
  58628. penumbra: 'light.penumbra',
  58629. type: 'light.type',
  58630. target: 'light.target'
  58631. }
  58632. });
  58633. },{"../primitives":148}],155:[function(_dereq_,module,exports){
  58634. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58635. registerPrimitive('a-link', {
  58636. defaultComponents: {
  58637. link: {
  58638. visualAspectEnabled: true
  58639. }
  58640. },
  58641. mappings: {
  58642. href: 'link.href',
  58643. image: 'link.image',
  58644. title: 'link.title'
  58645. }
  58646. });
  58647. },{"../primitives":148}],156:[function(_dereq_,module,exports){
  58648. var meshMixin = _dereq_('../getMeshMixin')();
  58649. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58650. var utils = _dereq_('../../../utils/');
  58651. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  58652. defaultComponents: {
  58653. 'obj-model': {}
  58654. },
  58655. mappings: {
  58656. src: 'obj-model.obj',
  58657. mtl: 'obj-model.mtl'
  58658. }
  58659. }));
  58660. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],157:[function(_dereq_,module,exports){
  58661. var getMeshMixin = _dereq_('../getMeshMixin');
  58662. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58663. var utils = _dereq_('../../../utils/');
  58664. var meshPrimitives = _dereq_('./meshPrimitives');
  58665. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  58666. defaultComponents: {
  58667. geometry: {
  58668. primitive: 'sphere',
  58669. radius: 500,
  58670. segmentsWidth: 64,
  58671. segmentsHeight: 32
  58672. },
  58673. material: {
  58674. color: '#FFF',
  58675. side: 'back',
  58676. shader: 'flat',
  58677. npot: true
  58678. },
  58679. scale: '-1 1 1'
  58680. },
  58681. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  58682. }));
  58683. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148,"./meshPrimitives":162}],158:[function(_dereq_,module,exports){
  58684. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58685. registerPrimitive('a-sound', {
  58686. defaultComponents: {
  58687. sound: {}
  58688. },
  58689. mappings: {
  58690. src: 'sound.src',
  58691. on: 'sound.on',
  58692. autoplay: 'sound.autoplay',
  58693. loop: 'sound.loop',
  58694. volume: 'sound.volume'
  58695. }
  58696. });
  58697. },{"../primitives":148}],159:[function(_dereq_,module,exports){
  58698. // <a-text> using `definePrimitive` helper.
  58699. var definePrimitive = _dereq_('../primitives').definePrimitive;
  58700. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  58701. },{"../primitives":148}],160:[function(_dereq_,module,exports){
  58702. var getMeshMixin = _dereq_('../getMeshMixin');
  58703. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58704. var utils = _dereq_('../../../utils/');
  58705. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  58706. defaultComponents: {
  58707. geometry: {
  58708. primitive: 'plane'
  58709. },
  58710. material: {
  58711. color: '#FFF',
  58712. shader: 'flat',
  58713. side: 'double',
  58714. transparent: true
  58715. }
  58716. },
  58717. mappings: {
  58718. height: 'geometry.height',
  58719. width: 'geometry.width'
  58720. }
  58721. }));
  58722. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],161:[function(_dereq_,module,exports){
  58723. var getMeshMixin = _dereq_('../getMeshMixin');
  58724. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58725. var utils = _dereq_('../../../utils/');
  58726. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  58727. defaultComponents: {
  58728. geometry: {
  58729. primitive: 'sphere',
  58730. radius: 500,
  58731. segmentsWidth: 64,
  58732. segmentsHeight: 32
  58733. },
  58734. material: {
  58735. color: '#FFF',
  58736. shader: 'flat',
  58737. side: 'back',
  58738. npot: true
  58739. },
  58740. scale: '-1 1 1'
  58741. },
  58742. mappings: {
  58743. radius: 'geometry.radius',
  58744. 'segments-height': 'geometry.segmentsHeight',
  58745. 'segments-width': 'geometry.segmentsWidth'
  58746. }
  58747. }));
  58748. },{"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],162:[function(_dereq_,module,exports){
  58749. /**
  58750. * Automated mesh primitive registration.
  58751. */
  58752. var getMeshMixin = _dereq_('../getMeshMixin');
  58753. var geometries = _dereq_('../../../core/geometry').geometries;
  58754. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  58755. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58756. var utils = _dereq_('../../../utils/');
  58757. // For testing.
  58758. var meshPrimitives = module.exports = {};
  58759. // Generate primitive for each geometry type.
  58760. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  58761. var geometry = geometries[geometryName];
  58762. var geometryHyphened = unCamelCase(geometryName);
  58763. // Generate mappings.
  58764. var mappings = {};
  58765. Object.keys(geometry.schema).forEach(function createMapping (property) {
  58766. mappings[unCamelCase(property)] = 'geometry.' + property;
  58767. });
  58768. // Register.
  58769. var tagName = 'a-' + geometryHyphened;
  58770. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  58771. defaultComponents: {geometry: {primitive: geometryName}},
  58772. mappings: mappings
  58773. }));
  58774. meshPrimitives[tagName] = primitive;
  58775. });
  58776. /**
  58777. * camelCase to hyphened-string.
  58778. */
  58779. function unCamelCase (str) {
  58780. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58781. }
  58782. },{"../../../core/geometry":133,"../../../utils/":206,"../getMeshMixin":146,"../primitives":148}],163:[function(_dereq_,module,exports){
  58783. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58784. var THREE = _dereq_('../lib/three');
  58785. registerGeometry('box', {
  58786. schema: {
  58787. depth: {default: 1, min: 0},
  58788. height: {default: 1, min: 0},
  58789. width: {default: 1, min: 0},
  58790. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58791. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  58792. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  58793. },
  58794. init: function (data) {
  58795. this.geometry = new THREE.BoxGeometry(
  58796. data.width, data.height, data.depth,
  58797. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  58798. }
  58799. });
  58800. },{"../core/geometry":133,"../lib/three":180}],164:[function(_dereq_,module,exports){
  58801. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58802. var THREE = _dereq_('../lib/three');
  58803. var degToRad = THREE.Math.degToRad;
  58804. registerGeometry('circle', {
  58805. schema: {
  58806. radius: {default: 1, min: 0},
  58807. segments: {default: 32, min: 3, type: 'int'},
  58808. thetaLength: {default: 360, min: 0},
  58809. thetaStart: {default: 0}
  58810. },
  58811. init: function (data) {
  58812. this.geometry = new THREE.CircleGeometry(
  58813. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58814. }
  58815. });
  58816. },{"../core/geometry":133,"../lib/three":180}],165:[function(_dereq_,module,exports){
  58817. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58818. var THREE = _dereq_('../lib/three');
  58819. var degToRad = THREE.Math.degToRad;
  58820. registerGeometry('cone', {
  58821. schema: {
  58822. height: {default: 1, min: 0},
  58823. openEnded: {default: false},
  58824. radiusBottom: {default: 1, min: 0},
  58825. radiusTop: {default: 0.01, min: 0},
  58826. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58827. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58828. thetaLength: {default: 360, min: 0},
  58829. thetaStart: {default: 0}
  58830. },
  58831. init: function (data) {
  58832. this.geometry = new THREE.CylinderGeometry(
  58833. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  58834. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  58835. degToRad(data.thetaLength));
  58836. }
  58837. });
  58838. },{"../core/geometry":133,"../lib/three":180}],166:[function(_dereq_,module,exports){
  58839. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58840. var THREE = _dereq_('../lib/three');
  58841. var degToRad = THREE.Math.degToRad;
  58842. registerGeometry('cylinder', {
  58843. schema: {
  58844. height: {default: 1, min: 0},
  58845. openEnded: {default: false},
  58846. radius: {default: 1, min: 0},
  58847. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58848. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58849. thetaLength: {default: 360, min: 0},
  58850. thetaStart: {default: 0}
  58851. },
  58852. init: function (data) {
  58853. this.geometry = new THREE.CylinderGeometry(
  58854. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  58855. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58856. }
  58857. });
  58858. },{"../core/geometry":133,"../lib/three":180}],167:[function(_dereq_,module,exports){
  58859. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58860. var THREE = _dereq_('../lib/three');
  58861. registerGeometry('dodecahedron', {
  58862. schema: {
  58863. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58864. radius: {default: 1, min: 0}
  58865. },
  58866. init: function (data) {
  58867. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  58868. }
  58869. });
  58870. },{"../core/geometry":133,"../lib/three":180}],168:[function(_dereq_,module,exports){
  58871. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58872. var THREE = _dereq_('../lib/three');
  58873. registerGeometry('icosahedron', {
  58874. schema: {
  58875. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58876. radius: {default: 1, min: 0}
  58877. },
  58878. init: function (data) {
  58879. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  58880. }
  58881. });
  58882. },{"../core/geometry":133,"../lib/three":180}],169:[function(_dereq_,module,exports){
  58883. _dereq_('./box.js');
  58884. _dereq_('./circle.js');
  58885. _dereq_('./cone.js');
  58886. _dereq_('./cylinder.js');
  58887. _dereq_('./dodecahedron.js');
  58888. _dereq_('./icosahedron.js');
  58889. _dereq_('./octahedron.js');
  58890. _dereq_('./plane.js');
  58891. _dereq_('./ring.js');
  58892. _dereq_('./sphere.js');
  58893. _dereq_('./tetrahedron.js');
  58894. _dereq_('./torus.js');
  58895. _dereq_('./torusKnot.js');
  58896. _dereq_('./triangle.js');
  58897. },{"./box.js":163,"./circle.js":164,"./cone.js":165,"./cylinder.js":166,"./dodecahedron.js":167,"./icosahedron.js":168,"./octahedron.js":170,"./plane.js":171,"./ring.js":172,"./sphere.js":173,"./tetrahedron.js":174,"./torus.js":175,"./torusKnot.js":176,"./triangle.js":177}],170:[function(_dereq_,module,exports){
  58898. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58899. var THREE = _dereq_('../lib/three');
  58900. registerGeometry('octahedron', {
  58901. schema: {
  58902. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58903. radius: {default: 1, min: 0}
  58904. },
  58905. init: function (data) {
  58906. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  58907. }
  58908. });
  58909. },{"../core/geometry":133,"../lib/three":180}],171:[function(_dereq_,module,exports){
  58910. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58911. var THREE = _dereq_('../lib/three');
  58912. registerGeometry('plane', {
  58913. schema: {
  58914. height: {default: 1, min: 0},
  58915. width: {default: 1, min: 0},
  58916. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58917. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  58918. },
  58919. init: function (data) {
  58920. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  58921. }
  58922. });
  58923. },{"../core/geometry":133,"../lib/three":180}],172:[function(_dereq_,module,exports){
  58924. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58925. var THREE = _dereq_('../lib/three');
  58926. var degToRad = THREE.Math.degToRad;
  58927. registerGeometry('ring', {
  58928. schema: {
  58929. radiusInner: {default: 0.8, min: 0},
  58930. radiusOuter: {default: 1.2, min: 0},
  58931. segmentsPhi: {default: 10, min: 1, type: 'int'},
  58932. segmentsTheta: {default: 32, min: 3, type: 'int'},
  58933. thetaLength: {default: 360, min: 0},
  58934. thetaStart: {default: 0}
  58935. },
  58936. init: function (data) {
  58937. this.geometry = new THREE.RingGeometry(
  58938. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  58939. degToRad(data.thetaStart), degToRad(data.thetaLength));
  58940. }
  58941. });
  58942. },{"../core/geometry":133,"../lib/three":180}],173:[function(_dereq_,module,exports){
  58943. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58944. var THREE = _dereq_('../lib/three');
  58945. var degToRad = THREE.Math.degToRad;
  58946. registerGeometry('sphere', {
  58947. schema: {
  58948. radius: {default: 1, min: 0},
  58949. phiLength: {default: 360},
  58950. phiStart: {default: 0, min: 0},
  58951. thetaLength: {default: 180, min: 0},
  58952. thetaStart: {default: 0},
  58953. segmentsHeight: {default: 18, min: 2, type: 'int'},
  58954. segmentsWidth: {default: 36, min: 3, type: 'int'}
  58955. },
  58956. init: function (data) {
  58957. this.geometry = new THREE.SphereGeometry(
  58958. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  58959. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  58960. }
  58961. });
  58962. },{"../core/geometry":133,"../lib/three":180}],174:[function(_dereq_,module,exports){
  58963. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58964. var THREE = _dereq_('../lib/three');
  58965. registerGeometry('tetrahedron', {
  58966. schema: {
  58967. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58968. radius: {default: 1, min: 0}
  58969. },
  58970. init: function (data) {
  58971. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  58972. }
  58973. });
  58974. },{"../core/geometry":133,"../lib/three":180}],175:[function(_dereq_,module,exports){
  58975. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58976. var THREE = _dereq_('../lib/three');
  58977. var degToRad = THREE.Math.degToRad;
  58978. registerGeometry('torus', {
  58979. schema: {
  58980. arc: {default: 360},
  58981. radius: {default: 1, min: 0},
  58982. radiusTubular: {default: 0.2, min: 0},
  58983. segmentsRadial: {default: 36, min: 2, type: 'int'},
  58984. segmentsTubular: {default: 32, min: 3, type: 'int'}
  58985. },
  58986. init: function (data) {
  58987. this.geometry = new THREE.TorusGeometry(
  58988. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  58989. degToRad(data.arc));
  58990. }
  58991. });
  58992. },{"../core/geometry":133,"../lib/three":180}],176:[function(_dereq_,module,exports){
  58993. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58994. var THREE = _dereq_('../lib/three');
  58995. registerGeometry('torusKnot', {
  58996. schema: {
  58997. p: {default: 2, min: 1},
  58998. q: {default: 3, min: 1},
  58999. radius: {default: 1, min: 0},
  59000. radiusTubular: {default: 0.2, min: 0},
  59001. segmentsRadial: {default: 8, min: 3, type: 'int'},
  59002. segmentsTubular: {default: 100, min: 3, type: 'int'}
  59003. },
  59004. init: function (data) {
  59005. this.geometry = new THREE.TorusKnotGeometry(
  59006. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  59007. data.p, data.q);
  59008. }
  59009. });
  59010. },{"../core/geometry":133,"../lib/three":180}],177:[function(_dereq_,module,exports){
  59011. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  59012. var THREE = _dereq_('../lib/three');
  59013. var quaternion = new THREE.Quaternion();
  59014. var rotateVector = new THREE.Vector3(0, 0, 1);
  59015. var uvMinVector = new THREE.Vector2();
  59016. var uvMaxVector = new THREE.Vector2();
  59017. var uvScaleVector = new THREE.Vector2();
  59018. registerGeometry('triangle', {
  59019. schema: {
  59020. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  59021. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  59022. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  59023. },
  59024. init: function (data) {
  59025. var geometry;
  59026. var normal;
  59027. var triangle;
  59028. var uvA;
  59029. var uvB;
  59030. var uvC;
  59031. var vertices;
  59032. var normals;
  59033. var uvs;
  59034. triangle = new THREE.Triangle();
  59035. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  59036. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  59037. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  59038. normal = triangle.getNormal(new THREE.Vector3());
  59039. // Rotate the 3D triangle to be parallel to XY plane.
  59040. quaternion.setFromUnitVectors(normal, rotateVector);
  59041. uvA = triangle.a.clone().applyQuaternion(quaternion);
  59042. uvB = triangle.b.clone().applyQuaternion(quaternion);
  59043. uvC = triangle.c.clone().applyQuaternion(quaternion);
  59044. // Compute UVs.
  59045. // Normalize x/y values of UV so they are within 0 to 1.
  59046. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  59047. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  59048. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  59049. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  59050. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  59051. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  59052. geometry = this.geometry = new THREE.BufferGeometry();
  59053. vertices = [
  59054. triangle.a.x, triangle.a.y, triangle.a.z,
  59055. triangle.b.x, triangle.b.y, triangle.b.z,
  59056. triangle.c.x, triangle.c.y, triangle.c.z
  59057. ];
  59058. normals = [
  59059. normal.x, normal.y, normal.z,
  59060. normal.x, normal.y, normal.z,
  59061. normal.x, normal.y, normal.z
  59062. ];
  59063. uvs = [
  59064. uvA.x, uvA.y,
  59065. uvB.x, uvB.y,
  59066. uvC.x, uvC.y
  59067. ];
  59068. geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
  59069. geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
  59070. geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
  59071. }
  59072. });
  59073. },{"../core/geometry":133,"../lib/three":180}],178:[function(_dereq_,module,exports){
  59074. // Polyfill `Promise`.
  59075. window.Promise = window.Promise || _dereq_('promise-polyfill');
  59076. // WebVR polyfill
  59077. // Check before the polyfill runs.
  59078. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  59079. !!window.navigator.getVRDevices;
  59080. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  59081. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  59082. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  59083. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  59084. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  59085. // Only for iOS on versions older than 10.
  59086. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  59087. var WebVRPolyfill = _dereq_('webvr-polyfill');
  59088. var polyfillConfig = {
  59089. BUFFER_SCALE: bufferScale,
  59090. CARDBOARD_UI_DISABLED: true,
  59091. ROTATE_INSTRUCTIONS_DISABLED: true,
  59092. MOBILE_WAKE_LOCK: !!window.cordova
  59093. };
  59094. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  59095. }
  59096. var utils = _dereq_('./utils/');
  59097. var debug = utils.debug;
  59098. if (utils.isIE11) {
  59099. // Polyfill `CustomEvent`.
  59100. _dereq_('custom-event-polyfill');
  59101. // Polyfill String.startsWith.
  59102. _dereq_('../vendor/starts-with-polyfill');
  59103. }
  59104. var error = debug('A-Frame:error');
  59105. var warn = debug('A-Frame:warn');
  59106. if (window.document.currentScript && window.document.currentScript.parentNode !==
  59107. window.document.head && !window.debug) {
  59108. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  59109. 'ensure everything for A-Frame is properly registered before they are used from ' +
  59110. 'HTML.');
  59111. }
  59112. // Error if not using a server.
  59113. if (!window.cordova && window.location.protocol === 'file:') {
  59114. error(
  59115. 'This HTML file is currently being served via the file:// protocol. ' +
  59116. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  59117. 'Please use a local or hosted server: ' +
  59118. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  59119. }
  59120. _dereq_('present'); // Polyfill `performance.now()`.
  59121. // CSS.
  59122. if (utils.device.isBrowserEnvironment) {
  59123. _dereq_('./style/aframe.css');
  59124. _dereq_('./style/rStats.css');
  59125. }
  59126. // Required before `AEntity` so that all components are registered.
  59127. var AScene = _dereq_('./core/scene/a-scene').AScene;
  59128. var components = _dereq_('./core/component').components;
  59129. var registerComponent = _dereq_('./core/component').registerComponent;
  59130. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  59131. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  59132. var registerShader = _dereq_('./core/shader').registerShader;
  59133. var registerSystem = _dereq_('./core/system').registerSystem;
  59134. var shaders = _dereq_('./core/shader').shaders;
  59135. var systems = _dereq_('./core/system').systems;
  59136. // Exports THREE to window so three.js can be used without alteration.
  59137. var THREE = window.THREE = _dereq_('./lib/three');
  59138. var pkg = _dereq_('../package');
  59139. _dereq_('./components/index'); // Register standard components.
  59140. _dereq_('./geometries/index'); // Register standard geometries.
  59141. _dereq_('./shaders/index'); // Register standard shaders.
  59142. _dereq_('./systems/index'); // Register standard systems.
  59143. var ANode = _dereq_('./core/a-node');
  59144. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  59145. _dereq_('./core/a-assets');
  59146. _dereq_('./core/a-cubemap');
  59147. _dereq_('./core/a-mixin');
  59148. // Extras.
  59149. _dereq_('./extras/components/');
  59150. _dereq_('./extras/primitives/');
  59151. console.log('A-Frame Version: 1.2.0 (Date 2021-04-28, Commit #66e0c624)');
  59152. console.log('THREE Version (https://github.com/supermedium/three.js):',
  59153. pkg.dependencies['super-three']);
  59154. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  59155. module.exports = window.AFRAME = {
  59156. AComponent: _dereq_('./core/component').Component,
  59157. AEntity: AEntity,
  59158. ANode: ANode,
  59159. ANIME: _dereq_('super-animejs'),
  59160. AScene: AScene,
  59161. components: components,
  59162. coreComponents: Object.keys(components),
  59163. geometries: _dereq_('./core/geometry').geometries,
  59164. registerComponent: registerComponent,
  59165. registerElement: _dereq_('./core/a-register-element').registerElement,
  59166. registerGeometry: registerGeometry,
  59167. registerPrimitive: registerPrimitive,
  59168. registerShader: registerShader,
  59169. registerSystem: registerSystem,
  59170. primitives: {
  59171. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  59172. primitives: _dereq_('./extras/primitives/primitives').primitives
  59173. },
  59174. scenes: _dereq_('./core/scene/scenes'),
  59175. schema: _dereq_('./core/schema'),
  59176. shaders: shaders,
  59177. systems: systems,
  59178. THREE: THREE,
  59179. utils: utils,
  59180. version: pkg.version
  59181. };
  59182. },{"../package":73,"../vendor/starts-with-polyfill":219,"./components/index":85,"./core/a-assets":126,"./core/a-cubemap":127,"./core/a-entity":128,"./core/a-mixin":129,"./core/a-node":130,"./core/a-register-element":131,"./core/component":132,"./core/geometry":133,"./core/scene/a-scene":135,"./core/scene/scenes":139,"./core/schema":141,"./core/shader":142,"./core/system":143,"./extras/components/":144,"./extras/primitives/":147,"./extras/primitives/getMeshMixin":146,"./extras/primitives/primitives":148,"./geometries/index":169,"./lib/three":180,"./shaders/index":182,"./style/aframe.css":187,"./style/rStats.css":188,"./systems/index":192,"./utils/":206,"./utils/isIOSOlderThan10":209,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":68}],179:[function(_dereq_,module,exports){
  59183. window.aframeStats = function (scene) {
  59184. var _rS = null;
  59185. var _scene = scene;
  59186. var _values = {
  59187. te: {
  59188. caption: 'Entities'
  59189. },
  59190. lt: {
  59191. caption: 'Load Time'
  59192. }
  59193. };
  59194. var _groups = [ {
  59195. caption: 'A-Frame',
  59196. values: [ 'te', 'lt' ]
  59197. } ];
  59198. function _update () {
  59199. _rS('te').set(getEntityCount());
  59200. if (window.performance.getEntriesByName) {
  59201. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  59202. }
  59203. }
  59204. function getEntityCount () {
  59205. var elements = _scene.querySelectorAll('*');
  59206. Array.prototype.slice.call(elements).filter(function (el) {
  59207. return el.isEntity;
  59208. });
  59209. return elements.length;
  59210. }
  59211. function _start () {}
  59212. function _end () {}
  59213. function _attach (r) {
  59214. _rS = r;
  59215. }
  59216. return {
  59217. update: _update,
  59218. start: _start,
  59219. end: _end,
  59220. attach: _attach,
  59221. values: _values,
  59222. groups: _groups,
  59223. fractions: []
  59224. };
  59225. };
  59226. if (typeof module === 'object') {
  59227. module.exports = {
  59228. aframeStats: window.aframeStats
  59229. };
  59230. }
  59231. },{}],180:[function(_dereq_,module,exports){
  59232. (function (global){
  59233. var THREE = global.THREE = _dereq_('super-three');
  59234. // Allow cross-origin images to be loaded.
  59235. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  59236. // Must be on `THREE.TextureLoader`.
  59237. if (THREE.TextureLoader) {
  59238. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  59239. }
  59240. // This is for images loaded from the model loaders.
  59241. if (THREE.ImageLoader) {
  59242. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  59243. }
  59244. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  59245. if (THREE.Cache) {
  59246. THREE.Cache.enabled = true;
  59247. }
  59248. // TODO: Eventually include these only if they are needed by a component.
  59249. _dereq_('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  59250. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  59251. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  59252. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  59253. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  59254. _dereq_('super-three/examples/js/utils/BufferGeometryUtils'); // THREE.BufferGeometryUtils
  59255. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  59256. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  59257. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  59258. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  59259. module.exports = THREE;
  59260. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  59261. },{"../../vendor/DeviceOrientationControls":216,"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,"super-three/examples/js/utils/BufferGeometryUtils":62}],181:[function(_dereq_,module,exports){
  59262. var registerShader = _dereq_('../core/shader').registerShader;
  59263. var THREE = _dereq_('../lib/three');
  59264. var utils = _dereq_('../utils/');
  59265. /**
  59266. * Flat shader using THREE.MeshBasicMaterial.
  59267. */
  59268. module.exports.Shader = registerShader('flat', {
  59269. schema: {
  59270. color: {type: 'color'},
  59271. fog: {default: true},
  59272. height: {default: 256},
  59273. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59274. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59275. src: {type: 'map'},
  59276. width: {default: 512},
  59277. wireframe: {default: false},
  59278. wireframeLinewidth: {default: 2}
  59279. },
  59280. /**
  59281. * Initializes the shader.
  59282. * Adds a reference from the scene to this entity as the camera.
  59283. */
  59284. init: function (data) {
  59285. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59286. this.materialData = {color: new THREE.Color()};
  59287. this.textureSrc = null;
  59288. getMaterialData(data, this.materialData);
  59289. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59290. this.material = new THREE.MeshBasicMaterial(this.materialData);
  59291. utils.material.updateMap(this, data);
  59292. },
  59293. update: function (data) {
  59294. this.updateMaterial(data);
  59295. utils.material.updateMap(this, data);
  59296. },
  59297. /**
  59298. * Updating existing material.
  59299. *
  59300. * @param {object} data - Material component data.
  59301. */
  59302. updateMaterial: function (data) {
  59303. var key;
  59304. getMaterialData(data, this.materialData);
  59305. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59306. for (key in this.materialData) {
  59307. this.material[key] = this.materialData[key];
  59308. }
  59309. }
  59310. });
  59311. /**
  59312. * Builds and normalize material data, normalizing stuff along the way.
  59313. *
  59314. * @param {object} data - Material data.
  59315. * @param {object} materialData - Object to reuse.
  59316. * @returns {object} Updated material data.
  59317. */
  59318. function getMaterialData (data, materialData) {
  59319. materialData.color.set(data.color);
  59320. materialData.fog = data.fog;
  59321. materialData.wireframe = data.wireframe;
  59322. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59323. return materialData;
  59324. }
  59325. },{"../core/shader":142,"../lib/three":180,"../utils/":206}],182:[function(_dereq_,module,exports){
  59326. _dereq_('./flat');
  59327. _dereq_('./standard');
  59328. _dereq_('./sdf');
  59329. _dereq_('./msdf');
  59330. _dereq_('./ios10hls');
  59331. },{"./flat":181,"./ios10hls":183,"./msdf":184,"./sdf":185,"./standard":186}],183:[function(_dereq_,module,exports){
  59332. var registerShader = _dereq_('../core/shader').registerShader;
  59333. /**
  59334. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  59335. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  59336. */
  59337. module.exports.Shader = registerShader('ios10hls', {
  59338. schema: {
  59339. src: {type: 'map', is: 'uniform'},
  59340. opacity: {type: 'number', is: 'uniform', default: 1}
  59341. },
  59342. vertexShader: [
  59343. 'varying vec2 vUV;',
  59344. 'void main(void) {',
  59345. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59346. ' vUV = uv;',
  59347. '}'
  59348. ].join('\n'),
  59349. fragmentShader: [
  59350. 'uniform sampler2D src;',
  59351. 'uniform float opacity;',
  59352. 'varying vec2 vUV;',
  59353. 'void main() {',
  59354. ' vec2 offset = vec2(0, 0);',
  59355. ' vec2 repeat = vec2(1, 1);',
  59356. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  59357. ' gl_FragColor = vec4(color.rgb, opacity);',
  59358. '}'
  59359. ].join('\n')
  59360. });
  59361. },{"../core/shader":142}],184:[function(_dereq_,module,exports){
  59362. var registerShader = _dereq_('../core/shader').registerShader;
  59363. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  59364. var VERTEX_SHADER_WEBGL1 = [
  59365. 'attribute vec2 uv;',
  59366. 'attribute vec3 position;',
  59367. 'uniform mat4 projectionMatrix;',
  59368. 'uniform mat4 modelViewMatrix;',
  59369. 'varying vec2 vUV;',
  59370. 'void main(void) {',
  59371. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59372. ' vUV = uv;',
  59373. '}'
  59374. ].join('\n');
  59375. var VERTEX_SHADER_WEBGL2 = [
  59376. '#version 300 es',
  59377. 'in vec2 uv;',
  59378. 'in vec3 position;',
  59379. 'uniform mat4 projectionMatrix;',
  59380. 'uniform mat4 modelViewMatrix;',
  59381. 'out vec2 vUV;',
  59382. 'void main(void) {',
  59383. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59384. ' vUV = uv;',
  59385. '}'
  59386. ].join('\n');
  59387. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  59388. var FRAGMENT_SHADER_WEBGL1 = [
  59389. '#ifdef GL_OES_standard_derivatives',
  59390. '#extension GL_OES_standard_derivatives: enable',
  59391. '#endif',
  59392. 'precision highp float;',
  59393. 'uniform bool negate;',
  59394. 'uniform float alphaTest;',
  59395. 'uniform float opacity;',
  59396. 'uniform sampler2D map;',
  59397. 'uniform vec3 color;',
  59398. 'varying vec2 vUV;',
  59399. 'float median(float r, float g, float b) {',
  59400. ' return max(min(r, g), min(max(r, g), b));',
  59401. '}',
  59402. // FIXME: Experimentally determined constants.
  59403. '#define BIG_ENOUGH 0.001',
  59404. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59405. 'void main() {',
  59406. ' vec3 sampleColor = texture2D(map, vUV).rgb;',
  59407. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59408. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59409. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59410. ' float dscale = 0.353505;',
  59411. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59412. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59413. // When texel is too small, blend raw alpha value rather than supersampling.
  59414. // FIXME: Experimentally determined constant.
  59415. ' // Do modified alpha test.',
  59416. ' if (isBigEnough > BIG_ENOUGH) {',
  59417. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59418. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59419. ' }',
  59420. ' // Do modified alpha test.',
  59421. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59422. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  59423. '}'
  59424. ].join('\n');
  59425. var FRAGMENT_SHADER_WEBGL2 = [
  59426. '#version 300 es',
  59427. 'precision highp float;',
  59428. 'uniform bool negate;',
  59429. 'uniform float alphaTest;',
  59430. 'uniform float opacity;',
  59431. 'uniform sampler2D map;',
  59432. 'uniform vec3 color;',
  59433. 'in vec2 vUV;',
  59434. 'out vec4 fragColor;',
  59435. 'float median(float r, float g, float b) {',
  59436. ' return max(min(r, g), min(max(r, g), b));',
  59437. '}',
  59438. // FIXME: Experimentally determined constants.
  59439. '#define BIG_ENOUGH 0.001',
  59440. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59441. 'void main() {',
  59442. ' vec3 sampleColor = texture(map, vUV).rgb;',
  59443. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59444. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59445. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59446. ' float dscale = 0.353505;',
  59447. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59448. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59449. // When texel is too small, blend raw alpha value rather than supersampling.
  59450. // FIXME: Experimentally determined constant.
  59451. ' // Do modified alpha test.',
  59452. ' if (isBigEnough > BIG_ENOUGH) {',
  59453. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59454. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59455. ' }',
  59456. ' // Do modified alpha test.',
  59457. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59458. ' fragColor = vec4(color.xyz, alpha * opacity);',
  59459. '}'
  59460. ].join('\n');
  59461. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59462. /**
  59463. * Multi-channel signed distance field.
  59464. * Used by text component.
  59465. */
  59466. module.exports.Shader = registerShader('msdf', {
  59467. schema: {
  59468. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59469. color: {type: 'color', is: 'uniform', default: 'white'},
  59470. map: {type: 'map', is: 'uniform'},
  59471. negate: {type: 'boolean', is: 'uniform', default: true},
  59472. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59473. },
  59474. raw: true,
  59475. vertexShader: VERTEX_SHADER,
  59476. fragmentShader: FRAGMENT_SHADER
  59477. });
  59478. },{"../core/shader":142}],185:[function(_dereq_,module,exports){
  59479. var registerShader = _dereq_('../core/shader').registerShader;
  59480. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  59481. var VERTEX_SHADER_WEBGL1 = [
  59482. 'attribute vec2 uv;',
  59483. 'attribute vec3 position;',
  59484. 'uniform mat4 projectionMatrix;',
  59485. 'uniform mat4 modelViewMatrix;',
  59486. 'varying vec2 vUV;',
  59487. 'void main(void) {',
  59488. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59489. ' vUV = uv;',
  59490. '}'
  59491. ].join('\n');
  59492. var VERTEX_SHADER_WEBGL2 = [
  59493. '#version 300 es',
  59494. 'in vec2 uv;',
  59495. 'in vec3 position;',
  59496. 'uniform mat4 projectionMatrix;',
  59497. 'uniform mat4 modelViewMatrix;',
  59498. 'out vec2 vUV;',
  59499. 'void main(void) {',
  59500. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59501. ' vUV = uv;',
  59502. '}'
  59503. ].join('\n');
  59504. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  59505. var FRAGMENT_SHADER_WEBGL1 = [
  59506. '#ifdef GL_OES_standard_derivatives',
  59507. '#extension GL_OES_standard_derivatives: enable',
  59508. '#endif',
  59509. 'precision highp float;',
  59510. 'uniform float alphaTest;',
  59511. 'uniform float opacity;',
  59512. 'uniform sampler2D map;',
  59513. 'uniform vec3 color;',
  59514. 'varying vec2 vUV;',
  59515. '#ifdef GL_OES_standard_derivatives',
  59516. ' float contour(float width, float value) {',
  59517. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59518. ' }',
  59519. '#else',
  59520. ' float aastep(float value, float afwidth) {',
  59521. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59522. ' }',
  59523. '#endif',
  59524. // FIXME: Experimentally determined constants.
  59525. '#define BIG_ENOUGH 0.001',
  59526. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59527. '#define ALL_SMOOTH 0.4',
  59528. '#define ALL_ROUGH 0.02',
  59529. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59530. 'void main() {',
  59531. // When we have derivatives and can get texel size for supersampling.
  59532. ' #ifdef GL_OES_standard_derivatives',
  59533. ' vec2 uv = vUV;',
  59534. ' vec4 texColor = texture2D(map, uv);',
  59535. ' float dist = texColor.a;',
  59536. ' float width = fwidth(dist);',
  59537. ' float alpha = contour(dist, width);',
  59538. ' float dscale = 0.353505;',
  59539. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59540. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59541. // When texel is too small, blend raw alpha value rather than supersampling.
  59542. // FIXME: experimentally determined constant
  59543. ' if (isBigEnough > BIG_ENOUGH) {',
  59544. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59545. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59546. ' }',
  59547. // Otherwise do weighted supersampling.
  59548. // FIXME: why this weighting?
  59549. ' if (isBigEnough <= BIG_ENOUGH) {',
  59550. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59551. ' alpha = (alpha + 0.5 * (',
  59552. ' contour(texture2D(map, box.xy).a, width)',
  59553. ' + contour(texture2D(map, box.zw).a, width)',
  59554. ' + contour(texture2D(map, box.xw).a, width)',
  59555. ' + contour(texture2D(map, box.zy).a, width)',
  59556. ' )) / 3.0;',
  59557. ' }',
  59558. // Do modified alpha test.
  59559. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59560. ' #else',
  59561. // When we don't have derivatives, use approximations.
  59562. ' vec4 texColor = texture2D(map, vUV);',
  59563. ' float value = texColor.a;',
  59564. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59565. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59566. ' float alpha = aastep(value, afwidth);',
  59567. // Use gl_FragCoord.w to guess when we should blend.
  59568. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59569. ' 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);',
  59570. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59571. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59572. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59573. ' #endif',
  59574. ' gl_FragColor = vec4(color, opacity * alpha);',
  59575. '}'
  59576. ].join('\n');
  59577. var FRAGMENT_SHADER_WEBGL2 = [
  59578. '#version 300 es',
  59579. 'precision highp float;',
  59580. 'uniform float alphaTest;',
  59581. 'uniform float opacity;',
  59582. 'uniform sampler2D map;',
  59583. 'uniform vec3 color;',
  59584. 'in vec2 vUV;',
  59585. 'out vec4 fragColor;',
  59586. '#ifdef GL_OES_standard_derivatives',
  59587. ' float contour(float width, float value) {',
  59588. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59589. ' }',
  59590. '#else',
  59591. ' float aastep(float value, float afwidth) {',
  59592. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59593. ' }',
  59594. '#endif',
  59595. // FIXME: Experimentally determined constants.
  59596. '#define BIG_ENOUGH 0.001',
  59597. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59598. '#define ALL_SMOOTH 0.4',
  59599. '#define ALL_ROUGH 0.02',
  59600. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59601. 'void main() {',
  59602. // When we have derivatives and can get texel size for supersampling.
  59603. ' #ifdef GL_OES_standard_derivatives',
  59604. ' vec2 uv = vUV;',
  59605. ' vec4 texColor = texture(map, uv);',
  59606. ' float dist = texColor.a;',
  59607. ' float width = fwidth(dist);',
  59608. ' float alpha = contour(dist, width);',
  59609. ' float dscale = 0.353505;',
  59610. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59611. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59612. // When texel is too small, blend raw alpha value rather than supersampling.
  59613. // FIXME: experimentally determined constant
  59614. ' if (isBigEnough > BIG_ENOUGH) {',
  59615. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59616. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59617. ' }',
  59618. // Otherwise do weighted supersampling.
  59619. // FIXME: why this weighting?
  59620. ' if (isBigEnough <= BIG_ENOUGH) {',
  59621. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59622. ' alpha = (alpha + 0.5 * (',
  59623. ' contour(texture(map, box.xy).a, width)',
  59624. ' + contour(texture(map, box.zw).a, width)',
  59625. ' + contour(texture(map, box.xw).a, width)',
  59626. ' + contour(texture(map, box.zy).a, width)',
  59627. ' )) / 3.0;',
  59628. ' }',
  59629. // Do modified alpha test.
  59630. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59631. ' #else',
  59632. // When we don't have derivatives, use approximations.
  59633. ' vec4 texColor = texture(map, vUV);',
  59634. ' float value = texColor.a;',
  59635. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59636. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59637. ' float alpha = aastep(value, afwidth);',
  59638. // Use gl_FragCoord.w to guess when we should blend.
  59639. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59640. ' 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);',
  59641. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59642. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59643. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59644. ' #endif',
  59645. ' fragColor = vec4(color, opacity * alpha);',
  59646. '}'
  59647. ].join('\n');
  59648. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59649. /**
  59650. * Signed distance field.
  59651. * Used by text component.
  59652. */
  59653. module.exports.Shader = registerShader('sdf', {
  59654. schema: {
  59655. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59656. color: {type: 'color', is: 'uniform', default: 'white'},
  59657. map: {type: 'map', is: 'uniform'},
  59658. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59659. },
  59660. raw: true,
  59661. vertexShader: VERTEX_SHADER,
  59662. fragmentShader: FRAGMENT_SHADER
  59663. });
  59664. },{"../core/shader":142}],186:[function(_dereq_,module,exports){
  59665. var registerShader = _dereq_('../core/shader').registerShader;
  59666. var THREE = _dereq_('../lib/three');
  59667. var utils = _dereq_('../utils/');
  59668. var CubeLoader = new THREE.CubeTextureLoader();
  59669. var texturePromises = {};
  59670. /**
  59671. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  59672. */
  59673. module.exports.Shader = registerShader('standard', {
  59674. schema: {
  59675. ambientOcclusionMap: {type: 'map'},
  59676. ambientOcclusionMapIntensity: {default: 1},
  59677. ambientOcclusionTextureOffset: {type: 'vec2'},
  59678. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59679. color: {type: 'color'},
  59680. displacementMap: {type: 'map'},
  59681. displacementScale: {default: 1},
  59682. displacementBias: {default: 0.5},
  59683. displacementTextureOffset: {type: 'vec2'},
  59684. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59685. emissive: {type: 'color', default: '#000'},
  59686. emissiveIntensity: {default: 1},
  59687. envMap: {default: ''},
  59688. fog: {default: true},
  59689. height: {default: 256},
  59690. metalness: {default: 0.0, min: 0.0, max: 1.0},
  59691. metalnessMap: {type: 'map'},
  59692. metalnessTextureOffset: {type: 'vec2'},
  59693. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59694. normalMap: {type: 'map'},
  59695. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  59696. normalTextureOffset: {type: 'vec2'},
  59697. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59698. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59699. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59700. roughness: {default: 0.5, min: 0.0, max: 1.0},
  59701. roughnessMap: {type: 'map'},
  59702. roughnessTextureOffset: {type: 'vec2'},
  59703. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59704. sphericalEnvMap: {type: 'map'},
  59705. src: {type: 'map'},
  59706. width: {default: 512},
  59707. wireframe: {default: false},
  59708. wireframeLinewidth: {default: 2}
  59709. },
  59710. /**
  59711. * Initializes the shader.
  59712. * Adds a reference from the scene to this entity as the camera.
  59713. */
  59714. init: function (data) {
  59715. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59716. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  59717. getMaterialData(data, this.materialData);
  59718. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59719. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59720. this.material = new THREE.MeshStandardMaterial(this.materialData);
  59721. utils.material.updateMap(this, data);
  59722. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59723. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59724. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59725. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59726. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59727. this.updateEnvMap(data);
  59728. },
  59729. update: function (data) {
  59730. this.updateMaterial(data);
  59731. utils.material.updateMap(this, data);
  59732. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59733. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59734. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59735. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59736. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59737. this.updateEnvMap(data);
  59738. },
  59739. /**
  59740. * Updating existing material.
  59741. *
  59742. * @param {object} data - Material component data.
  59743. * @returns {object} Material.
  59744. */
  59745. updateMaterial: function (data) {
  59746. var key;
  59747. var material = this.material;
  59748. getMaterialData(data, this.materialData);
  59749. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59750. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59751. for (key in this.materialData) {
  59752. material[key] = this.materialData[key];
  59753. }
  59754. },
  59755. /**
  59756. * Handle environment cubemap. Textures are cached in texturePromises.
  59757. */
  59758. updateEnvMap: function (data) {
  59759. var self = this;
  59760. var material = this.material;
  59761. var envMap = data.envMap;
  59762. var sphericalEnvMap = data.sphericalEnvMap;
  59763. // No envMap defined or already loading.
  59764. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  59765. material.envMap = null;
  59766. material.needsUpdate = true;
  59767. return;
  59768. }
  59769. this.isLoadingEnvMap = true;
  59770. // if a spherical env map is defined then use it.
  59771. if (sphericalEnvMap) {
  59772. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  59773. self.isLoadingEnvMap = false;
  59774. texture.mapping = THREE.EquirectangularReflectionMapping;
  59775. material.envMap = texture;
  59776. utils.material.handleTextureEvents(self.el, texture);
  59777. material.needsUpdate = true;
  59778. });
  59779. return;
  59780. }
  59781. // Another material is already loading this texture. Wait on promise.
  59782. if (texturePromises[envMap]) {
  59783. texturePromises[envMap].then(function (cube) {
  59784. self.isLoadingEnvMap = false;
  59785. material.envMap = cube;
  59786. utils.material.handleTextureEvents(self.el, cube);
  59787. material.needsUpdate = true;
  59788. });
  59789. return;
  59790. }
  59791. // Material is first to load this texture. Load and resolve texture.
  59792. texturePromises[envMap] = new Promise(function (resolve) {
  59793. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  59794. CubeLoader.load(urls, function (cube) {
  59795. // Texture loaded.
  59796. self.isLoadingEnvMap = false;
  59797. material.envMap = cube;
  59798. utils.material.handleTextureEvents(self.el, cube);
  59799. resolve(cube);
  59800. });
  59801. });
  59802. });
  59803. }
  59804. });
  59805. /**
  59806. * Builds and normalize material data, normalizing stuff along the way.
  59807. *
  59808. * @param {object} data - Material data.
  59809. * @param {object} materialData - Object to use.
  59810. * @returns {object} Updated materialData.
  59811. */
  59812. function getMaterialData (data, materialData) {
  59813. materialData.color.set(data.color);
  59814. materialData.emissive.set(data.emissive);
  59815. materialData.emissiveIntensity = data.emissiveIntensity;
  59816. materialData.fog = data.fog;
  59817. materialData.metalness = data.metalness;
  59818. materialData.roughness = data.roughness;
  59819. materialData.wireframe = data.wireframe;
  59820. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59821. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  59822. if (data.ambientOcclusionMap) {
  59823. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  59824. }
  59825. if (data.displacementMap) {
  59826. materialData.displacementScale = data.displacementScale;
  59827. materialData.displacementBias = data.displacementBias;
  59828. }
  59829. return materialData;
  59830. }
  59831. },{"../core/shader":142,"../lib/three":180,"../utils/":206}],187:[function(_dereq_,module,exports){
  59832. 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;
  59833. },{"browserify-css":4}],188:[function(_dereq_,module,exports){
  59834. 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;
  59835. },{"browserify-css":4}],189:[function(_dereq_,module,exports){
  59836. var constants = _dereq_('../constants/');
  59837. var registerSystem = _dereq_('../core/system').registerSystem;
  59838. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  59839. /**
  59840. * Camera system. Manages which camera is active among multiple cameras in scene.
  59841. *
  59842. * @member {object} activeCameraEl - Active camera entity.
  59843. */
  59844. module.exports.System = registerSystem('camera', {
  59845. init: function () {
  59846. this.activeCameraEl = null;
  59847. this.render = this.render.bind(this);
  59848. this.unwrapRender = this.unwrapRender.bind(this);
  59849. this.wrapRender = this.wrapRender.bind(this);
  59850. this.initialCameraFound = false;
  59851. this.numUserCameras = 0;
  59852. this.numUserCamerasChecked = 0;
  59853. this.setupInitialCamera();
  59854. },
  59855. /**
  59856. * Setup initial camera, either searching for camera or
  59857. * creating a default camera if user has not added one during the initial scene traversal.
  59858. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  59859. * loads.
  59860. *
  59861. * Default camera offset height is at average eye level (~1.6m).
  59862. */
  59863. setupInitialCamera: function () {
  59864. var cameraEls;
  59865. var i;
  59866. var sceneEl = this.sceneEl;
  59867. var self = this;
  59868. // Camera already defined or the one defined it is an spectator one.
  59869. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  59870. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  59871. return;
  59872. }
  59873. // Search for initial user-defined camera.
  59874. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  59875. // No user cameras, create default one.
  59876. if (!cameraEls.length) {
  59877. this.createDefaultCamera();
  59878. return;
  59879. }
  59880. this.numUserCameras = cameraEls.length;
  59881. for (i = 0; i < cameraEls.length; i++) {
  59882. cameraEls[i].addEventListener('object3dset', function (evt) {
  59883. if (evt.detail.type !== 'camera') { return; }
  59884. self.checkUserCamera(this);
  59885. });
  59886. // Load camera and wait for camera to initialize.
  59887. if (cameraEls[i].isNode) {
  59888. cameraEls[i].load();
  59889. } else {
  59890. cameraEls[i].addEventListener('nodeready', function () {
  59891. this.load();
  59892. });
  59893. }
  59894. }
  59895. },
  59896. /**
  59897. * Check if a user-defined camera entity is appropriate to be initial camera.
  59898. * (active + non-spectator).
  59899. *
  59900. * Keep track of the number of cameras we checked and whether we found one.
  59901. */
  59902. checkUserCamera: function (cameraEl) {
  59903. var cameraData;
  59904. var sceneEl = this.el.sceneEl;
  59905. this.numUserCamerasChecked++;
  59906. // Already found one.
  59907. if (this.initialCameraFound) { return; }
  59908. // Check if camera is appropriate for being the initial camera.
  59909. cameraData = cameraEl.getAttribute('camera');
  59910. if (!cameraData.active || cameraData.spectator) {
  59911. // No user cameras eligible, create default camera.
  59912. if (this.numUserCamerasChecked === this.numUserCameras) {
  59913. this.createDefaultCamera();
  59914. }
  59915. return;
  59916. }
  59917. this.initialCameraFound = true;
  59918. sceneEl.camera = cameraEl.getObject3D('camera');
  59919. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  59920. },
  59921. createDefaultCamera: function () {
  59922. var defaultCameraEl;
  59923. var sceneEl = this.sceneEl;
  59924. // Set up default camera.
  59925. defaultCameraEl = document.createElement('a-entity');
  59926. defaultCameraEl.setAttribute('camera', {active: true});
  59927. defaultCameraEl.setAttribute('position', {
  59928. x: 0,
  59929. y: constants.DEFAULT_CAMERA_HEIGHT,
  59930. z: 0
  59931. });
  59932. defaultCameraEl.setAttribute('wasd-controls', '');
  59933. defaultCameraEl.setAttribute('look-controls', '');
  59934. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  59935. defaultCameraEl.addEventListener('object3dset', function (evt) {
  59936. if (evt.detail.type !== 'camera') { return; }
  59937. sceneEl.camera = evt.detail.object;
  59938. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  59939. });
  59940. sceneEl.appendChild(defaultCameraEl);
  59941. },
  59942. /**
  59943. * Set a different active camera.
  59944. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  59945. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  59946. * the new camera.
  59947. */
  59948. disableActiveCamera: function () {
  59949. var cameraEls;
  59950. var newActiveCameraEl;
  59951. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  59952. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  59953. newActiveCameraEl.setAttribute('camera', 'active', true);
  59954. },
  59955. /**
  59956. * Set active camera to be used by renderer.
  59957. * Removes the default camera (if present).
  59958. * Disables all other cameras in the scene.
  59959. *
  59960. * @param {Element} newCameraEl - Entity with camera component.
  59961. */
  59962. setActiveCamera: function (newCameraEl) {
  59963. var cameraEl;
  59964. var cameraEls;
  59965. var i;
  59966. var newCamera;
  59967. var previousCamera = this.activeCameraEl;
  59968. var sceneEl = this.sceneEl;
  59969. // Same camera.
  59970. newCamera = newCameraEl.getObject3D('camera');
  59971. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  59972. // Grab the default camera.
  59973. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59974. var defaultCameraEl = defaultCameraWrapper &&
  59975. defaultCameraWrapper.querySelector('[camera]');
  59976. // Remove default camera if new camera is not the default camera.
  59977. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  59978. // Make new camera active.
  59979. this.activeCameraEl = newCameraEl;
  59980. this.activeCameraEl.play();
  59981. sceneEl.camera = newCamera;
  59982. // Disable current camera
  59983. if (previousCamera) {
  59984. previousCamera.setAttribute('camera', 'active', false);
  59985. }
  59986. // Disable other cameras in the scene
  59987. cameraEls = sceneEl.querySelectorAll('[camera]');
  59988. for (i = 0; i < cameraEls.length; i++) {
  59989. cameraEl = cameraEls[i];
  59990. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  59991. cameraEl.setAttribute('camera', 'active', false);
  59992. cameraEl.pause();
  59993. }
  59994. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  59995. },
  59996. /**
  59997. * Set spectator camera to render the scene on a 2D display.
  59998. *
  59999. * @param {Element} newCameraEl - Entity with camera component.
  60000. */
  60001. setSpectatorCamera: function (newCameraEl) {
  60002. var newCamera;
  60003. var previousCamera = this.spectatorCameraEl;
  60004. var sceneEl = this.sceneEl;
  60005. var spectatorCameraEl;
  60006. // Same camera.
  60007. newCamera = newCameraEl.getObject3D('camera');
  60008. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  60009. // Disable current camera
  60010. if (previousCamera) {
  60011. previousCamera.setAttribute('camera', 'spectator', false);
  60012. }
  60013. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  60014. sceneEl.addEventListener('enter-vr', this.wrapRender);
  60015. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  60016. spectatorCameraEl.setAttribute('camera', 'active', false);
  60017. spectatorCameraEl.play();
  60018. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  60019. },
  60020. /**
  60021. * Disables current spectator camera.
  60022. */
  60023. disableSpectatorCamera: function () {
  60024. this.spectatorCameraEl = undefined;
  60025. },
  60026. /**
  60027. * Wrap the render method of the renderer to render
  60028. * the spectator camera after vrDisplay.submitFrame.
  60029. */
  60030. wrapRender: function () {
  60031. if (!this.spectatorCameraEl || this.originalRender) { return; }
  60032. this.originalRender = this.sceneEl.renderer.render;
  60033. this.sceneEl.renderer.render = this.render;
  60034. },
  60035. unwrapRender: function () {
  60036. if (!this.originalRender) { return; }
  60037. this.sceneEl.renderer.render = this.originalRender;
  60038. this.originalRender = undefined;
  60039. },
  60040. render: function (scene, camera) {
  60041. var isVREnabled;
  60042. var sceneEl = this.sceneEl;
  60043. var spectatorCamera;
  60044. isVREnabled = sceneEl.renderer.xr.enabled;
  60045. this.originalRender.call(sceneEl.renderer, scene, camera);
  60046. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  60047. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  60048. sceneEl.renderer.xr.enabled = false;
  60049. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  60050. sceneEl.renderer.xr.enabled = isVREnabled;
  60051. }
  60052. });
  60053. /**
  60054. * Remove injected default camera from scene, if present.
  60055. *
  60056. * @param {Element} sceneEl
  60057. */
  60058. function removeDefaultCamera (sceneEl) {
  60059. var defaultCamera;
  60060. var camera = sceneEl.camera;
  60061. if (!camera) { return; }
  60062. // Remove default camera if present.
  60063. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  60064. if (!defaultCamera) { return; }
  60065. sceneEl.removeChild(defaultCamera);
  60066. }
  60067. },{"../constants/":124,"../core/system":143}],190:[function(_dereq_,module,exports){
  60068. var geometries = _dereq_('../core/geometry').geometries;
  60069. var registerSystem = _dereq_('../core/system').registerSystem;
  60070. /**
  60071. * System for geometry component.
  60072. * Handle geometry caching.
  60073. *
  60074. * @member {object} cache - Mapping of stringified component data to THREE.BufferGeometry objects.
  60075. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  60076. * know whether to dispose on removal.
  60077. */
  60078. module.exports.System = registerSystem('geometry', {
  60079. init: function () {
  60080. this.cache = {};
  60081. this.cacheCount = {};
  60082. },
  60083. /**
  60084. * Reset cache. Mainly for testing.
  60085. */
  60086. clearCache: function () {
  60087. this.cache = {};
  60088. this.cacheCount = {};
  60089. },
  60090. /**
  60091. * Attempt to retrieve from cache.
  60092. *
  60093. * @returns {Object|null} A geometry if it exists, else null.
  60094. */
  60095. getOrCreateGeometry: function (data) {
  60096. var cache = this.cache;
  60097. var cachedGeometry;
  60098. var hash;
  60099. // Skip all caching logic.
  60100. if (data.skipCache) { return createGeometry(data); }
  60101. // Try to retrieve from cache first.
  60102. hash = this.hash(data);
  60103. cachedGeometry = cache[hash];
  60104. incrementCacheCount(this.cacheCount, hash);
  60105. if (cachedGeometry) { return cachedGeometry; }
  60106. // Create geometry.
  60107. cachedGeometry = createGeometry(data);
  60108. // Cache and return geometry.
  60109. cache[hash] = cachedGeometry;
  60110. return cachedGeometry;
  60111. },
  60112. /**
  60113. * Let system know that an entity is no longer using a geometry.
  60114. */
  60115. unuseGeometry: function (data) {
  60116. var cache = this.cache;
  60117. var cacheCount = this.cacheCount;
  60118. var geometry;
  60119. var hash;
  60120. if (data.skipCache) { return; }
  60121. hash = this.hash(data);
  60122. if (!cache[hash]) { return; }
  60123. decrementCacheCount(cacheCount, hash);
  60124. // Another entity is still using this geometry. No need to do anything.
  60125. if (cacheCount[hash] > 0) { return; }
  60126. // No more entities are using this geometry. Dispose.
  60127. geometry = cache[hash];
  60128. geometry.dispose();
  60129. delete cache[hash];
  60130. delete cacheCount[hash];
  60131. },
  60132. /**
  60133. * Use JSON.stringify to turn component data into hash.
  60134. * Should be deterministic within a single browser engine.
  60135. * If not, then look into json-stable-stringify.
  60136. */
  60137. hash: function (data) {
  60138. return JSON.stringify(data);
  60139. }
  60140. });
  60141. /**
  60142. * Create geometry using component data.
  60143. *
  60144. * @param {object} data - Component data.
  60145. * @returns {object} Geometry.
  60146. */
  60147. function createGeometry (data) {
  60148. var geometryType = data.primitive;
  60149. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  60150. var geometryInstance = new GeometryClass();
  60151. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  60152. geometryInstance.init(data);
  60153. return geometryInstance.geometry;
  60154. }
  60155. /**
  60156. * Decreate count of entity using a geometry.
  60157. */
  60158. function decrementCacheCount (cacheCount, hash) {
  60159. cacheCount[hash]--;
  60160. }
  60161. /**
  60162. * Increase count of entity using a geometry.
  60163. */
  60164. function incrementCacheCount (cacheCount, hash) {
  60165. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  60166. }
  60167. },{"../core/geometry":133,"../core/system":143}],191:[function(_dereq_,module,exports){
  60168. var registerSystem = _dereq_('../core/system').registerSystem;
  60169. var THREE = _dereq_('../lib/three');
  60170. /**
  60171. * glTF model system.
  60172. *
  60173. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  60174. * provided externally.
  60175. *
  60176. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  60177. */
  60178. module.exports.System = registerSystem('gltf-model', {
  60179. schema: {
  60180. dracoDecoderPath: {default: ''}
  60181. },
  60182. init: function () {
  60183. var path = this.data.dracoDecoderPath;
  60184. this.dracoLoader = new THREE.DRACOLoader();
  60185. this.dracoLoader.setDecoderPath(path);
  60186. },
  60187. update: function () {
  60188. var path;
  60189. if (this.dracoLoader) { return; }
  60190. path = this.data.dracoDecoderPath;
  60191. this.dracoLoader = new THREE.DRACOLoader();
  60192. this.dracoLoader.setDecoderPath(path);
  60193. },
  60194. getDRACOLoader: function () {
  60195. return this.dracoLoader;
  60196. }
  60197. });
  60198. },{"../core/system":143,"../lib/three":180}],192:[function(_dereq_,module,exports){
  60199. _dereq_('./camera');
  60200. _dereq_('./geometry');
  60201. _dereq_('./gltf-model');
  60202. _dereq_('./light');
  60203. _dereq_('./material');
  60204. _dereq_('./renderer');
  60205. _dereq_('./shadow');
  60206. _dereq_('./tracked-controls-webvr');
  60207. _dereq_('./tracked-controls-webxr');
  60208. _dereq_('./webxr');
  60209. },{"./camera":189,"./geometry":190,"./gltf-model":191,"./light":193,"./material":194,"./renderer":195,"./shadow":196,"./tracked-controls-webvr":197,"./tracked-controls-webxr":198,"./webxr":199}],193:[function(_dereq_,module,exports){
  60210. var registerSystem = _dereq_('../core/system').registerSystem;
  60211. var bind = _dereq_('../utils/bind');
  60212. var constants = _dereq_('../constants/');
  60213. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  60214. /**
  60215. * Light system.
  60216. *
  60217. * Prescribes default lighting if not specified (one ambient, one directional).
  60218. * Removes default lighting from the scene when a new light is added.
  60219. *
  60220. * @param {bool} defaultLights - Whether default lighting are defined.
  60221. * @param {bool} userDefinedLights - Whether user lighting is defined.
  60222. */
  60223. module.exports.System = registerSystem('light', {
  60224. schema: {
  60225. defaultLightsEnabled: {default: true}
  60226. },
  60227. init: function () {
  60228. this.defaultLights = false;
  60229. this.userDefinedLights = false;
  60230. // Wait for all entities to fully load before checking for existence of lights.
  60231. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  60232. // will do so asynchronously.
  60233. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  60234. },
  60235. /**
  60236. * Notify scene that light has been added and to remove the default.
  60237. *
  60238. * @param {object} el - element holding the light component.
  60239. */
  60240. registerLight: function (el) {
  60241. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  60242. // User added a light, remove default lights through DOM.
  60243. this.removeDefaultLights();
  60244. this.userDefinedLights = true;
  60245. }
  60246. },
  60247. removeDefaultLights: function () {
  60248. var defaultLights;
  60249. var sceneEl = this.sceneEl;
  60250. if (!this.defaultLights) { return; }
  60251. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  60252. for (var i = 0; i < defaultLights.length; i++) {
  60253. sceneEl.removeChild(defaultLights[i]);
  60254. }
  60255. this.defaultLights = false;
  60256. },
  60257. /**
  60258. * Prescibe default lights to the scene.
  60259. * Does so by injecting markup such that this state is not invisible.
  60260. * These lights are removed if the user adds any lights.
  60261. */
  60262. setupDefaultLights: function () {
  60263. var sceneEl = this.sceneEl;
  60264. var ambientLight;
  60265. var directionalLight;
  60266. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  60267. return;
  60268. }
  60269. ambientLight = document.createElement('a-entity');
  60270. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  60271. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60272. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  60273. sceneEl.appendChild(ambientLight);
  60274. directionalLight = document.createElement('a-entity');
  60275. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  60276. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  60277. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60278. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  60279. sceneEl.appendChild(directionalLight);
  60280. this.defaultLights = true;
  60281. }
  60282. });
  60283. },{"../constants/":124,"../core/system":143,"../utils/bind":200}],194:[function(_dereq_,module,exports){
  60284. var registerSystem = _dereq_('../core/system').registerSystem;
  60285. var THREE = _dereq_('../lib/three');
  60286. var utils = _dereq_('../utils/');
  60287. var isHLS = _dereq_('../utils/material').isHLS;
  60288. var bind = utils.bind;
  60289. var debug = utils.debug;
  60290. var error = debug('components:texture:error');
  60291. var TextureLoader = new THREE.TextureLoader();
  60292. var warn = debug('components:texture:warn');
  60293. TextureLoader.setCrossOrigin('anonymous');
  60294. /**
  60295. * System for material component.
  60296. * Handle material registration, updates (for fog), and texture caching.
  60297. *
  60298. * @member {object} materials - Registered materials.
  60299. * @member {object} textureCounts - Number of times each texture is used. Tracked
  60300. * separately from textureCache, because the cache (1) is populated in
  60301. * multiple places, and (2) may be cleared at any time.
  60302. * @member {object} textureCache - Texture cache for:
  60303. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  60304. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  60305. */
  60306. module.exports.System = registerSystem('material', {
  60307. init: function () {
  60308. this.materials = {};
  60309. this.textureCounts = {};
  60310. this.textureCache = {};
  60311. this.sceneEl.addEventListener(
  60312. 'materialtextureloaded',
  60313. bind(this.onMaterialTextureLoaded, this)
  60314. );
  60315. },
  60316. clearTextureCache: function () {
  60317. this.textureCache = {};
  60318. },
  60319. /**
  60320. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  60321. *
  60322. * @param {string, or element} src - Texture URL or element.
  60323. * @param {string} data - Relevant texture data used for caching.
  60324. * @param {function} cb - Callback to pass texture to.
  60325. */
  60326. loadTexture: function (src, data, cb) {
  60327. var self = this;
  60328. // Canvas.
  60329. if (src.tagName === 'CANVAS') {
  60330. this.loadCanvas(src, data, cb);
  60331. return;
  60332. }
  60333. // Video element.
  60334. if (src.tagName === 'VIDEO') {
  60335. if (!src.src && !src.srcObject && !src.childElementCount) {
  60336. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  60337. }
  60338. this.loadVideo(src, data, cb);
  60339. return;
  60340. }
  60341. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  60342. function loadImageCb (src) { self.loadImage(src, data, cb); }
  60343. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  60344. },
  60345. /**
  60346. * High-level function for loading image textures (THREE.Texture).
  60347. *
  60348. * @param {Element|string} src - Texture source.
  60349. * @param {object} data - Texture data.
  60350. * @param {function} cb - Callback to pass texture to.
  60351. */
  60352. loadImage: function (src, data, handleImageTextureLoaded) {
  60353. var hash = this.hash(data);
  60354. var textureCache = this.textureCache;
  60355. // Texture already being loaded or already loaded. Wait on promise.
  60356. if (textureCache[hash]) {
  60357. textureCache[hash].then(handleImageTextureLoaded);
  60358. return;
  60359. }
  60360. // Texture not yet being loaded. Start loading it.
  60361. textureCache[hash] = loadImageTexture(src, data);
  60362. textureCache[hash].then(handleImageTextureLoaded);
  60363. },
  60364. /**
  60365. * High-level function for loading canvas textures (THREE.Texture).
  60366. *
  60367. * @param {Element|string} src - Texture source.
  60368. * @param {object} data - Texture data.
  60369. * @param {function} cb - Callback to pass texture to.
  60370. */
  60371. loadCanvas: function (src, data, cb) {
  60372. var texture;
  60373. texture = new THREE.CanvasTexture(src);
  60374. setTextureProperties(texture, data);
  60375. cb(texture);
  60376. },
  60377. /**
  60378. * Load video texture (THREE.VideoTexture).
  60379. * Which is just an image texture that RAFs + needsUpdate.
  60380. * Note that creating a video texture is synchronous unlike loading an image texture.
  60381. * Made asynchronous to be consistent with image textures.
  60382. *
  60383. * @param {Element|string} src - Texture source.
  60384. * @param {object} data - Texture data.
  60385. * @param {function} cb - Callback to pass texture to.
  60386. */
  60387. loadVideo: function (src, data, cb) {
  60388. var hash;
  60389. var texture;
  60390. var textureCache = this.textureCache;
  60391. var videoEl;
  60392. var videoTextureResult;
  60393. function handleVideoTextureLoaded (result) {
  60394. result.texture.needsUpdate = true;
  60395. cb(result.texture, result.videoEl);
  60396. }
  60397. // Video element provided.
  60398. if (typeof src !== 'string') {
  60399. // Check cache before creating texture.
  60400. videoEl = src;
  60401. hash = this.hashVideo(data, videoEl);
  60402. if (textureCache[hash]) {
  60403. textureCache[hash].then(handleVideoTextureLoaded);
  60404. return;
  60405. }
  60406. // If not in cache, fix up the attributes then start to create the texture.
  60407. fixVideoAttributes(videoEl);
  60408. }
  60409. // Only URL provided. Use video element to create texture.
  60410. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  60411. // Generated video element already cached. Use that.
  60412. hash = this.hashVideo(data, videoEl);
  60413. if (textureCache[hash]) {
  60414. textureCache[hash].then(handleVideoTextureLoaded);
  60415. return;
  60416. }
  60417. // Create new video texture.
  60418. texture = new THREE.VideoTexture(videoEl);
  60419. texture.minFilter = THREE.LinearFilter;
  60420. setTextureProperties(texture, data);
  60421. // If iOS and video is HLS, do some hacks.
  60422. if (this.sceneEl.isIOS &&
  60423. isHLS(videoEl.src || videoEl.getAttribute('src'),
  60424. videoEl.type || videoEl.getAttribute('type'))) {
  60425. // Actually BGRA. Tell shader to correct later.
  60426. texture.format = THREE.RGBAFormat;
  60427. texture.needsCorrectionBGRA = true;
  60428. // Apparently needed for HLS. Tell shader to correct later.
  60429. texture.flipY = false;
  60430. texture.needsCorrectionFlipY = true;
  60431. }
  60432. // Cache as promise to be consistent with image texture caching.
  60433. videoTextureResult = {texture: texture, videoEl: videoEl};
  60434. textureCache[hash] = Promise.resolve(videoTextureResult);
  60435. handleVideoTextureLoaded(videoTextureResult);
  60436. },
  60437. /**
  60438. * Create a hash of the material properties for texture cache key.
  60439. */
  60440. hash: function (data) {
  60441. if (data.src.tagName) {
  60442. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  60443. data = utils.extendDeep({}, data);
  60444. data.src = data.src.src;
  60445. }
  60446. return JSON.stringify(data);
  60447. },
  60448. hashVideo: function (data, videoEl) {
  60449. return calculateVideoCacheHash(data, videoEl);
  60450. },
  60451. /**
  60452. * Keep track of material in case an update trigger is needed (e.g., fog).
  60453. *
  60454. * @param {object} material
  60455. */
  60456. registerMaterial: function (material) {
  60457. this.materials[material.uuid] = material;
  60458. },
  60459. /**
  60460. * Stop tracking material, and dispose of any textures not being used by
  60461. * another material component.
  60462. *
  60463. * @param {object} material
  60464. */
  60465. unregisterMaterial: function (material) {
  60466. delete this.materials[material.uuid];
  60467. // If any textures on this material are no longer in use, dispose of them.
  60468. var textureCounts = this.textureCounts;
  60469. Object.keys(material)
  60470. .filter(function (propName) {
  60471. return material[propName] && material[propName].isTexture;
  60472. })
  60473. .forEach(function (mapName) {
  60474. textureCounts[material[mapName].uuid]--;
  60475. if (textureCounts[material[mapName].uuid] <= 0) {
  60476. material[mapName].dispose();
  60477. }
  60478. });
  60479. },
  60480. /**
  60481. * Trigger update to all registered materials.
  60482. */
  60483. updateMaterials: function (material) {
  60484. var materials = this.materials;
  60485. Object.keys(materials).forEach(function (uuid) {
  60486. materials[uuid].needsUpdate = true;
  60487. });
  60488. },
  60489. /**
  60490. * Track textures used by material components, so that they can be safely
  60491. * disposed when no longer in use. Textures must be registered here, and not
  60492. * through registerMaterial(), because textures may not be attached at the
  60493. * time the material is registered.
  60494. *
  60495. * @param {Event} e
  60496. */
  60497. onMaterialTextureLoaded: function (e) {
  60498. if (!this.textureCounts[e.detail.texture.uuid]) {
  60499. this.textureCounts[e.detail.texture.uuid] = 0;
  60500. }
  60501. this.textureCounts[e.detail.texture.uuid]++;
  60502. }
  60503. });
  60504. /**
  60505. * Calculates consistent hash from a video element using its attributes.
  60506. * If the video element has an ID, use that.
  60507. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  60508. *
  60509. * @param data {object} - Texture data such as repeat.
  60510. * @param videoEl {Element} - Video element.
  60511. * @returns {string}
  60512. */
  60513. function calculateVideoCacheHash (data, videoEl) {
  60514. var i;
  60515. var id = videoEl.getAttribute('id');
  60516. var hash;
  60517. var videoAttributes;
  60518. if (id) { return id; }
  60519. // Calculate hash using sorted video attributes.
  60520. hash = '';
  60521. videoAttributes = data || {};
  60522. for (i = 0; i < videoEl.attributes.length; i++) {
  60523. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  60524. }
  60525. Object.keys(videoAttributes).sort().forEach(function (name) {
  60526. hash += name + ':' + videoAttributes[name] + ';';
  60527. });
  60528. return hash;
  60529. }
  60530. /**
  60531. * Load image texture.
  60532. *
  60533. * @private
  60534. * @param {string|object} src - An <img> element or url to an image file.
  60535. * @param {object} data - Data to set texture properties like `repeat`.
  60536. * @returns {Promise} Resolves once texture is loaded.
  60537. */
  60538. function loadImageTexture (src, data) {
  60539. return new Promise(doLoadImageTexture);
  60540. function doLoadImageTexture (resolve, reject) {
  60541. var isEl = typeof src !== 'string';
  60542. function resolveTexture (texture) {
  60543. setTextureProperties(texture, data);
  60544. texture.needsUpdate = true;
  60545. resolve(texture);
  60546. }
  60547. // Create texture from an element.
  60548. if (isEl) {
  60549. resolveTexture(new THREE.Texture(src));
  60550. return;
  60551. }
  60552. // Request and load texture from src string. THREE will create underlying element.
  60553. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  60554. TextureLoader.load(
  60555. src,
  60556. resolveTexture,
  60557. function () { /* no-op */ },
  60558. function (xhr) {
  60559. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  60560. xhr.statusText);
  60561. }
  60562. );
  60563. }
  60564. }
  60565. /**
  60566. * Set texture properties such as repeat and offset.
  60567. *
  60568. * @param {object} data - With keys like `repeat`.
  60569. */
  60570. function setTextureProperties (texture, data) {
  60571. var offset = data.offset || {x: 0, y: 0};
  60572. var repeat = data.repeat || {x: 1, y: 1};
  60573. var npot = data.npot || false;
  60574. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  60575. // and filters must not use mipmaps (i.e. Nearest or Linear).
  60576. if (npot) {
  60577. texture.wrapS = THREE.ClampToEdgeWrapping;
  60578. texture.wrapT = THREE.ClampToEdgeWrapping;
  60579. texture.magFilter = THREE.LinearFilter;
  60580. texture.minFilter = THREE.LinearFilter;
  60581. }
  60582. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  60583. if (repeat.x !== 1 || repeat.y !== 1) {
  60584. texture.wrapS = THREE.RepeatWrapping;
  60585. texture.wrapT = THREE.RepeatWrapping;
  60586. texture.repeat.set(repeat.x, repeat.y);
  60587. }
  60588. // Don't bother setting offset if it is 0/0.
  60589. if (offset.x !== 0 || offset.y !== 0) {
  60590. texture.offset.set(offset.x, offset.y);
  60591. }
  60592. }
  60593. /**
  60594. * Create video element to be used as a texture.
  60595. *
  60596. * @param {string} src - Url to a video file.
  60597. * @param {number} width - Width of the video.
  60598. * @param {number} height - Height of the video.
  60599. * @returns {Element} Video element.
  60600. */
  60601. function createVideoEl (src, width, height) {
  60602. var videoEl = document.createElement('video');
  60603. videoEl.width = width;
  60604. videoEl.height = height;
  60605. // Support inline videos for iOS webviews.
  60606. videoEl.setAttribute('playsinline', '');
  60607. videoEl.setAttribute('webkit-playsinline', '');
  60608. videoEl.autoplay = true;
  60609. videoEl.loop = true;
  60610. videoEl.crossOrigin = 'anonymous';
  60611. videoEl.addEventListener('error', function () {
  60612. warn('`$s` is not a valid video', src);
  60613. }, true);
  60614. videoEl.src = src;
  60615. return videoEl;
  60616. }
  60617. /**
  60618. * Fixes a video element's attributes to prevent developers from accidentally passing the
  60619. * wrong attribute values to commonly misused video attributes.
  60620. *
  60621. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  60622. * as booleans. Existence of those attributes will mean truthy.
  60623. *
  60624. * For example, translates <video loop="false"> to <video>.
  60625. *
  60626. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  60627. * @param {Element} videoEl - Video element.
  60628. * @returns {Element} Video element with the correct properties updated.
  60629. */
  60630. function fixVideoAttributes (videoEl) {
  60631. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  60632. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  60633. if (videoEl.getAttribute('loop') === 'false') {
  60634. videoEl.removeAttribute('loop');
  60635. }
  60636. if (videoEl.getAttribute('preload') === 'false') {
  60637. videoEl.preload = 'none';
  60638. }
  60639. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  60640. // To support inline videos in iOS webviews.
  60641. videoEl.setAttribute('playsinline', '');
  60642. videoEl.setAttribute('webkit-playsinline', '');
  60643. return videoEl;
  60644. }
  60645. },{"../core/system":143,"../lib/three":180,"../utils/":206,"../utils/material":210}],195:[function(_dereq_,module,exports){
  60646. var registerSystem = _dereq_('../core/system').registerSystem;
  60647. var utils = _dereq_('../utils/');
  60648. var THREE = _dereq_('../lib/three');
  60649. var debug = utils.debug;
  60650. var warn = debug('components:renderer:warn');
  60651. /**
  60652. * Determines state of various renderer properties.
  60653. */
  60654. module.exports.System = registerSystem('renderer', {
  60655. schema: {
  60656. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60657. highRefreshRate: {default: utils.device.isOculusBrowser()},
  60658. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60659. maxCanvasWidth: {default: 1920},
  60660. maxCanvasHeight: {default: 1920},
  60661. physicallyCorrectLights: {default: false},
  60662. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  60663. sortObjects: {default: false},
  60664. colorManagement: {default: false},
  60665. gammaOutput: {default: false},
  60666. alpha: {default: true},
  60667. foveationLevel: {default: 0}
  60668. },
  60669. init: function () {
  60670. var data = this.data;
  60671. var sceneEl = this.el;
  60672. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  60673. var renderer = sceneEl.renderer;
  60674. renderer.sortObjects = data.sortObjects;
  60675. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  60676. if (data.colorManagement || data.gammaOutput) {
  60677. renderer.outputEncoding = THREE.sRGBEncoding;
  60678. if (data.gammaOutput) {
  60679. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  60680. }
  60681. }
  60682. if (sceneEl.hasAttribute('antialias')) {
  60683. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  60684. }
  60685. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  60686. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  60687. }
  60688. },
  60689. applyColorCorrection: function (colorOrTexture) {
  60690. if (!this.data.colorManagement || !colorOrTexture) {
  60691. return;
  60692. } else if (colorOrTexture.isColor) {
  60693. colorOrTexture.convertSRGBToLinear();
  60694. } else if (colorOrTexture.isTexture) {
  60695. colorOrTexture.encoding = THREE.sRGBEncoding;
  60696. }
  60697. }
  60698. });
  60699. },{"../core/system":143,"../lib/three":180,"../utils/":206}],196:[function(_dereq_,module,exports){
  60700. var registerSystem = _dereq_('../core/system').registerSystem;
  60701. var THREE = _dereq_('../lib/three');
  60702. var SHADOW_MAP_TYPE_MAP = {
  60703. basic: THREE.BasicShadowMap,
  60704. pcf: THREE.PCFShadowMap,
  60705. pcfsoft: THREE.PCFSoftShadowMap
  60706. };
  60707. /**
  60708. * Shadow system.
  60709. *
  60710. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  60711. * options on the WebGLRenderer for configuring shadow appearance.
  60712. */
  60713. module.exports.System = registerSystem('shadow', {
  60714. schema: {
  60715. enabled: {default: true},
  60716. autoUpdate: {default: true},
  60717. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  60718. },
  60719. init: function () {
  60720. var sceneEl = this.sceneEl;
  60721. var data = this.data;
  60722. this.shadowMapEnabled = false;
  60723. if (!sceneEl.renderer) { return; } // For tests.
  60724. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  60725. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  60726. this.setShadowMapEnabled(this.shadowMapEnabled);
  60727. },
  60728. update: function (prevData) {
  60729. if (prevData.enabled !== this.data.enabled) {
  60730. this.setShadowMapEnabled(this.data.enabled);
  60731. }
  60732. },
  60733. /**
  60734. * Enables/disables the renderer shadow map.
  60735. * @param {boolean} enabled
  60736. */
  60737. setShadowMapEnabled: function (enabled) {
  60738. var renderer = this.sceneEl.renderer;
  60739. this.shadowMapEnabled = this.data.enabled && enabled;
  60740. if (renderer) {
  60741. renderer.shadowMap.enabled = this.shadowMapEnabled;
  60742. }
  60743. }
  60744. });
  60745. },{"../core/system":143,"../lib/three":180}],197:[function(_dereq_,module,exports){
  60746. var registerSystem = _dereq_('../core/system').registerSystem;
  60747. var utils = _dereq_('../utils');
  60748. var isWebXRAvailable = utils.device.isWebXRAvailable;
  60749. /**
  60750. * Tracked controls system.
  60751. * Maintain list with available tracked controllers.
  60752. */
  60753. module.exports.System = registerSystem('tracked-controls-webvr', {
  60754. init: function () {
  60755. var self = this;
  60756. this.controllers = [];
  60757. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  60758. this.updateControllerList();
  60759. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60760. // Don't use WebVR if WebXR is available?
  60761. if (isWebXRAvailable) { return; }
  60762. if (!navigator.getVRDisplays) { return; }
  60763. this.sceneEl.addEventListener('enter-vr', function () {
  60764. navigator.getVRDisplays().then(function (displays) {
  60765. if (displays.length) { self.vrDisplay = displays[0]; }
  60766. });
  60767. });
  60768. },
  60769. tick: function () {
  60770. if (this.isChrome) {
  60771. // Retrieve new controller handlers with updated state (pose, buttons...)
  60772. this.updateControllerList();
  60773. } else {
  60774. this.throttledUpdateControllerList();
  60775. }
  60776. },
  60777. /**
  60778. * Update controller list.
  60779. */
  60780. updateControllerList: function () {
  60781. var controllers = this.controllers;
  60782. var gamepad;
  60783. var gamepads;
  60784. var i;
  60785. var prevCount;
  60786. gamepads = navigator.getGamepads && navigator.getGamepads();
  60787. if (!gamepads) { return; }
  60788. prevCount = controllers.length;
  60789. controllers.length = 0;
  60790. for (i = 0; i < gamepads.length; ++i) {
  60791. gamepad = gamepads[i];
  60792. if (gamepad && gamepad.pose) {
  60793. controllers.push(gamepad);
  60794. }
  60795. }
  60796. if (controllers.length !== prevCount) {
  60797. this.el.emit('controllersupdated', undefined, false);
  60798. }
  60799. }
  60800. });
  60801. },{"../core/system":143,"../utils":206}],198:[function(_dereq_,module,exports){
  60802. var registerSystem = _dereq_('../core/system').registerSystem;
  60803. var utils = _dereq_('../utils');
  60804. /**
  60805. * Tracked controls system.
  60806. * Maintain list with available tracked controllers.
  60807. */
  60808. module.exports.System = registerSystem('tracked-controls-webxr', {
  60809. init: function () {
  60810. this.controllers = [];
  60811. this.oldControllers = [];
  60812. this.oldControllersLength = 0;
  60813. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60814. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  60815. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  60816. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  60817. },
  60818. tick: function () {
  60819. this.throttledUpdateControllerList();
  60820. },
  60821. updateReferenceSpace: function () {
  60822. var self = this;
  60823. var xrSession = this.el.xrSession;
  60824. if (!xrSession) {
  60825. this.referenceSpace = undefined;
  60826. this.controllers = [];
  60827. if (this.oldControllersLength > 0) {
  60828. this.oldControllersLength = 0;
  60829. this.el.emit('controllersupdated', undefined, false);
  60830. }
  60831. return;
  60832. }
  60833. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  60834. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  60835. self.referenceSpace = referenceSpace;
  60836. }).catch(function (err) {
  60837. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  60838. refspace,
  60839. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  60840. throw err;
  60841. });
  60842. },
  60843. updateControllerList: function () {
  60844. var xrSession = this.el.xrSession;
  60845. var oldControllers = this.oldControllers;
  60846. var i;
  60847. if (!xrSession) {
  60848. if (this.oldControllersLength === 0) { return; }
  60849. // Broadcast that we now have zero controllers connected if there is
  60850. // no session
  60851. this.oldControllersLength = 0;
  60852. this.controllers = [];
  60853. this.el.emit('controllersupdated', undefined, false);
  60854. return;
  60855. }
  60856. if (!xrSession.inputSources) { return; }
  60857. this.controllers = xrSession.inputSources;
  60858. if (this.oldControllersLength === this.controllers.length) {
  60859. var equal = true;
  60860. for (i = 0; i < this.controllers.length; ++i) {
  60861. if (this.controllers[i] === oldControllers[i] &&
  60862. this.controllers[i].gamepad === oldControllers[i].gamepad) { continue; }
  60863. equal = false;
  60864. break;
  60865. }
  60866. if (equal) { return; }
  60867. }
  60868. // Store reference to current controllers
  60869. oldControllers.length = 0;
  60870. for (i = 0; i < this.controllers.length; i++) {
  60871. oldControllers.push(this.controllers[i]);
  60872. }
  60873. this.oldControllersLength = this.controllers.length;
  60874. this.el.emit('controllersupdated', undefined, false);
  60875. }
  60876. });
  60877. },{"../core/system":143,"../utils":206}],199:[function(_dereq_,module,exports){
  60878. var registerSystem = _dereq_('../core/system').registerSystem;
  60879. var utils = _dereq_('../utils/');
  60880. var warn = utils.debug('systems:webxr:warn');
  60881. /**
  60882. * WebXR session initialization and XR module support.
  60883. */
  60884. module.exports.System = registerSystem('webxr', {
  60885. schema: {
  60886. referenceSpaceType: {type: 'string', default: 'local-floor'},
  60887. requiredFeatures: {type: 'array', default: ['local-floor']},
  60888. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  60889. overlayElement: {type: 'selector'}
  60890. },
  60891. update: function () {
  60892. var data = this.data;
  60893. this.sessionConfiguration = {
  60894. requiredFeatures: data.requiredFeatures,
  60895. optionalFeatures: data.optionalFeatures
  60896. };
  60897. this.sessionReferenceSpaceType = data.referenceSpaceType;
  60898. if (data.overlayElement) {
  60899. this.warnIfFeatureNotRequested('dom-overlay');
  60900. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  60901. }
  60902. },
  60903. wasFeatureRequested: function (feature) {
  60904. // Features available by default for immersive sessions don't need to
  60905. // be requested explicitly.
  60906. if (feature === 'viewer' || feature === 'local') return true;
  60907. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  60908. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  60909. return true;
  60910. }
  60911. return false;
  60912. },
  60913. warnIfFeatureNotRequested: function (feature, optIntro) {
  60914. if (!this.wasFeatureRequested(feature)) {
  60915. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  60916. 'webxr system options in requiredFeatures/optionalFeatures.';
  60917. warn((optIntro ? optIntro + ' ' : '') + msg);
  60918. }
  60919. }
  60920. });
  60921. },{"../core/system":143,"../utils/":206}],200:[function(_dereq_,module,exports){
  60922. /**
  60923. * Faster version of Function.prototype.bind
  60924. * @param {Function} fn - Function to wrap.
  60925. * @param {Object} ctx - What to bind as context.
  60926. * @param {...*} arguments - Arguments to pass through.
  60927. */
  60928. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  60929. return (function (prependedArgs) {
  60930. return function bound () {
  60931. // Concat the bound function arguments with those passed to original bind
  60932. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  60933. return fn.apply(ctx, args);
  60934. };
  60935. })(Array.prototype.slice.call(arguments, 2));
  60936. };
  60937. },{}],201:[function(_dereq_,module,exports){
  60938. /* global THREE */
  60939. var debug = _dereq_('./debug');
  60940. var extend = _dereq_('object-assign');
  60941. var warn = debug('utils:coordinates:warn');
  60942. // Order of coordinates parsed by coordinates.parse.
  60943. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  60944. // Coordinate string regex. Handles negative, positive, and decimals.
  60945. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  60946. module.exports.regex = regex;
  60947. var OBJECT = 'object';
  60948. var whitespaceRegex = /\s+/g;
  60949. /**
  60950. * Parses coordinates from an "x y z" string.
  60951. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  60952. *
  60953. * @param {string} val - An "x y z" string.
  60954. * @param {string} defaults - fallback value.
  60955. * @returns {object} An object with keys [x, y, z].
  60956. */
  60957. function parse (value, defaultVec) {
  60958. var coordinate;
  60959. var defaultVal;
  60960. var key;
  60961. var i;
  60962. var vec;
  60963. var x;
  60964. var y;
  60965. var z;
  60966. var w;
  60967. if (value && value instanceof Object) {
  60968. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  60969. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  60970. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  60971. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  60972. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  60973. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  60974. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  60975. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  60976. return value;
  60977. }
  60978. if (value === null || value === undefined) {
  60979. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  60980. }
  60981. coordinate = value.trim().split(whitespaceRegex);
  60982. vec = {};
  60983. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  60984. key = COORDINATE_KEYS[i];
  60985. if (coordinate[i]) {
  60986. vec[key] = parseFloat(coordinate[i], 10);
  60987. } else {
  60988. defaultVal = defaultVec && defaultVec[key];
  60989. if (defaultVal === undefined) { continue; }
  60990. vec[key] = parseIfString(defaultVal);
  60991. }
  60992. }
  60993. return vec;
  60994. }
  60995. module.exports.parse = parse;
  60996. /**
  60997. * Stringify coordinates from an object with keys [x y z].
  60998. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  60999. *
  61000. * @param {object|string} data - An object with keys [x y z].
  61001. * @returns {string} An "x y z" string.
  61002. */
  61003. function stringify (data) {
  61004. var str;
  61005. if (typeof data !== OBJECT) { return data; }
  61006. str = data.x + ' ' + data.y;
  61007. if (data.z != null) { str += ' ' + data.z; }
  61008. if (data.w != null) { str += ' ' + data.w; }
  61009. return str;
  61010. }
  61011. module.exports.stringify = stringify;
  61012. /**
  61013. * @returns {bool}
  61014. */
  61015. function isCoordinates (value) {
  61016. return regex.test(value);
  61017. }
  61018. module.exports.isCoordinates = isCoordinates;
  61019. module.exports.isCoordinate = function (value) {
  61020. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  61021. return isCoordinates(value);
  61022. };
  61023. function parseIfString (val) {
  61024. if (val !== null && val !== undefined && val.constructor === String) {
  61025. return parseFloat(val, 10);
  61026. }
  61027. return val;
  61028. }
  61029. /**
  61030. * Convert {x, y, z} object to three.js Vector3.
  61031. */
  61032. module.exports.toVector3 = function (vec3) {
  61033. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  61034. };
  61035. },{"./debug":202,"object-assign":39}],202:[function(_dereq_,module,exports){
  61036. (function (process){
  61037. var debugLib = _dereq_('debug');
  61038. var extend = _dereq_('object-assign');
  61039. var settings = {
  61040. colors: {
  61041. debug: 'gray',
  61042. error: 'red',
  61043. info: 'gray',
  61044. warn: 'orange'
  61045. }
  61046. };
  61047. /**
  61048. * Monkeypatches `debug` so we can colorize error/warning messages.
  61049. *
  61050. * (See issue: https://github.com/visionmedia/debug/issues/137)
  61051. */
  61052. var debug = function (namespace) {
  61053. var d = debugLib(namespace);
  61054. d.color = getDebugNamespaceColor(namespace);
  61055. return d;
  61056. };
  61057. extend(debug, debugLib);
  61058. /**
  61059. * Returns the type of the namespace (e.g., `error`, `warn`).
  61060. *
  61061. * @param {String} namespace
  61062. * The debug logger's namespace (e.g., `components:geometry:warn`).
  61063. * @returns {String} The type of the namespace (e.g., `warn`).
  61064. * @api private
  61065. */
  61066. function getDebugNamespaceType (namespace) {
  61067. var chunks = namespace.split(':');
  61068. return chunks[chunks.length - 1]; // Return the last one
  61069. }
  61070. /**
  61071. * Returns the color of the namespace (e.g., `orange`).
  61072. *
  61073. * @param {String} namespace
  61074. * The debug logger's namespace (e.g., `components:geometry:warn`).
  61075. * @returns {String} The color of the namespace (e.g., `orange`).
  61076. * @api private
  61077. */
  61078. function getDebugNamespaceColor (namespace) {
  61079. var type = getDebugNamespaceType(namespace);
  61080. var color = settings.colors && settings.colors[type];
  61081. return color || null;
  61082. }
  61083. /**
  61084. * Returns `localStorage` if possible.
  61085. *
  61086. * This is necessary because Safari throws when a user disables
  61087. * cookies or `localStorage` and you attempt to access it.
  61088. *
  61089. * @returns {localStorage}
  61090. * @api private
  61091. */
  61092. function storage () {
  61093. try {
  61094. return window.localStorage;
  61095. } catch (e) {
  61096. }
  61097. }
  61098. /**
  61099. * To enable console logging, type this in the Console of your Dev Tools:
  61100. *
  61101. * localStorage.logs = 1
  61102. *
  61103. * To disable console logging:
  61104. *
  61105. * localStorage.logs = 0
  61106. *
  61107. */
  61108. var ls = storage();
  61109. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  61110. debug.enable('*');
  61111. } else {
  61112. debug.enable('*:error,*:info,*:warn');
  61113. }
  61114. if (process.browser) { window.logs = debug; }
  61115. module.exports = debug;
  61116. }).call(this,_dereq_('_process'))
  61117. },{"_process":49,"debug":8,"object-assign":39}],203:[function(_dereq_,module,exports){
  61118. (function (process){
  61119. var error = _dereq_('debug')('device:error');
  61120. var vrDisplay;
  61121. var supportsVRSession = false;
  61122. var supportsARSession = false;
  61123. /**
  61124. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  61125. * We fallback to WebVR API and will hotfix when implementation is complete.
  61126. */
  61127. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  61128. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  61129. window.addEventListener('vrdisplayactivate', function (evt) {
  61130. var canvasEl;
  61131. // WebXR takes priority if available.
  61132. if (isWebXRAvailable) { return; }
  61133. canvasEl = document.createElement('canvas');
  61134. vrDisplay = evt.display;
  61135. // We need to make sure the canvas has a WebGL context associated with it.
  61136. // Otherwise, the requestPresent could be denied.
  61137. canvasEl.getContext('webgl', {});
  61138. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  61139. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  61140. });
  61141. // Support both WebVR and WebXR APIs.
  61142. if (isWebXRAvailable) {
  61143. var updateEnterInterfaces = function () {
  61144. var sceneEl = document.querySelector('a-scene');
  61145. if (!sceneEl) {
  61146. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  61147. return;
  61148. }
  61149. if (sceneEl.hasLoaded) {
  61150. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  61151. } else {
  61152. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  61153. }
  61154. };
  61155. var errorHandler = function (err) {
  61156. error('WebXR session support error: ' + err.message);
  61157. };
  61158. if (navigator.xr.isSessionSupported) {
  61159. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  61160. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  61161. supportsVRSession = supported;
  61162. updateEnterInterfaces();
  61163. }).catch(errorHandler);
  61164. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  61165. supportsARSession = supported;
  61166. updateEnterInterfaces();
  61167. }).catch(function () {});
  61168. } else if (navigator.xr.supportsSession) {
  61169. // Fallback for implementations that haven't updated to the new spec yet,
  61170. // the old version used supportsSession which is rejected for missing
  61171. // support.
  61172. navigator.xr.supportsSession('immersive-vr').then(function () {
  61173. supportsVRSession = true;
  61174. updateEnterInterfaces();
  61175. }).catch(errorHandler);
  61176. navigator.xr.supportsSession('immersive-ar').then(function () {
  61177. supportsARSession = true;
  61178. updateEnterInterfaces();
  61179. }).catch(function () {});
  61180. } else {
  61181. error('WebXR has neither isSessionSupported or supportsSession?!');
  61182. }
  61183. } else {
  61184. if (navigator.getVRDisplays) {
  61185. navigator.getVRDisplays().then(function (displays) {
  61186. var sceneEl = document.querySelector('a-scene');
  61187. vrDisplay = displays.length && displays[0];
  61188. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  61189. });
  61190. }
  61191. }
  61192. function getVRDisplay () { return vrDisplay; }
  61193. module.exports.getVRDisplay = getVRDisplay;
  61194. /**
  61195. * Determine if a headset is connected by checking if a vrDisplay is available.
  61196. */
  61197. function checkHeadsetConnected () {
  61198. return supportsVRSession || supportsARSession || !!getVRDisplay();
  61199. }
  61200. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  61201. function checkARSupport () { return supportsARSession; }
  61202. module.exports.checkARSupport = checkARSupport;
  61203. /**
  61204. * Checks if browser is mobile and not stand-alone dedicated vr device.
  61205. * @return {Boolean} True if mobile browser detected.
  61206. */
  61207. var isMobile = (function () {
  61208. var _isMobile = false;
  61209. (function (a) {
  61210. // eslint-disable-next-line no-useless-escape
  61211. 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))) {
  61212. _isMobile = true;
  61213. }
  61214. if (isIOS() || isTablet() || isR7()) {
  61215. _isMobile = true;
  61216. }
  61217. if (isMobileVR()) {
  61218. _isMobile = false;
  61219. }
  61220. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  61221. return function () { return _isMobile; };
  61222. })();
  61223. module.exports.isMobile = isMobile;
  61224. /**
  61225. * Detect tablet devices.
  61226. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  61227. */
  61228. function isTablet (mockUserAgent) {
  61229. var userAgent = mockUserAgent || window.navigator.userAgent;
  61230. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  61231. }
  61232. module.exports.isTablet = isTablet;
  61233. function isIOS () {
  61234. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  61235. }
  61236. module.exports.isIOS = isIOS;
  61237. function isMobileDeviceRequestingDesktopSite () {
  61238. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  61239. }
  61240. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  61241. /**
  61242. * Detect Oculus Browser (standalone headset)
  61243. */
  61244. function isOculusBrowser () {
  61245. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  61246. }
  61247. module.exports.isOculusBrowser = isOculusBrowser;
  61248. /**
  61249. * Detect Firefox Reality (standalone headset)
  61250. */
  61251. function isFirefoxReality () {
  61252. return /(Mobile VR)/i.test(window.navigator.userAgent);
  61253. }
  61254. module.exports.isFirefoxReality = isFirefoxReality;
  61255. /**
  61256. * Detect browsers in Stand-Alone headsets
  61257. */
  61258. function isMobileVR () {
  61259. return isOculusBrowser() || isFirefoxReality();
  61260. }
  61261. module.exports.isMobileVR = isMobileVR;
  61262. function isR7 () {
  61263. return /R7 Build/.test(window.navigator.userAgent);
  61264. }
  61265. module.exports.isR7 = isR7;
  61266. /**
  61267. * Checks mobile device orientation.
  61268. * @return {Boolean} True if landscape orientation.
  61269. */
  61270. module.exports.isLandscape = function () {
  61271. var orientation = window.orientation;
  61272. if (isR7()) { orientation += 90; }
  61273. return orientation === 90 || orientation === -90;
  61274. };
  61275. /**
  61276. * Check if running in a browser or spoofed browser (bundler).
  61277. * We need to check a node api that isn't mocked on either side.
  61278. * `require` and `module.exports` are mocked in browser by bundlers.
  61279. * `window` is mocked in node.
  61280. * `process` is also mocked by browserify, but has custom properties.
  61281. */
  61282. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  61283. /**
  61284. * Check if running in node on the server.
  61285. */
  61286. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  61287. }).call(this,_dereq_('_process'))
  61288. },{"_process":49,"debug":8}],204:[function(_dereq_,module,exports){
  61289. /**
  61290. * Split a delimited component property string (e.g., `material.color`) to an object
  61291. * containing `component` name and `property` name. If there is no delimiter, just return the
  61292. * string back.
  61293. *
  61294. * Cache arrays from splitting strings via delimiter to save on memory.
  61295. *
  61296. * @param {string} str - e.g., `material.opacity`.
  61297. * @param {string} delimiter - e.g., `.`.
  61298. * @returns {array} e.g., `['material', 'opacity']`.
  61299. */
  61300. var propertyPathCache = {};
  61301. function getComponentPropertyPath (str, delimiter) {
  61302. delimiter = delimiter || '.';
  61303. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  61304. if (str.indexOf(delimiter) !== -1) {
  61305. propertyPathCache[delimiter][str] = str.split(delimiter);
  61306. } else {
  61307. propertyPathCache[delimiter][str] = str;
  61308. }
  61309. return propertyPathCache[delimiter][str];
  61310. }
  61311. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  61312. module.exports.propertyPathCache = propertyPathCache;
  61313. /**
  61314. * Get component property using encoded component name + component property name with a
  61315. * delimiter.
  61316. */
  61317. module.exports.getComponentProperty = function (el, name, delimiter) {
  61318. var splitName;
  61319. delimiter = delimiter || '.';
  61320. if (name.indexOf(delimiter) !== -1) {
  61321. splitName = getComponentPropertyPath(name, delimiter);
  61322. if (splitName.constructor === String) {
  61323. return el.getAttribute(splitName);
  61324. }
  61325. return el.getAttribute(splitName[0])[splitName[1]];
  61326. }
  61327. return el.getAttribute(name);
  61328. };
  61329. /**
  61330. * Set component property using encoded component name + component property name with a
  61331. * delimiter.
  61332. */
  61333. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  61334. var splitName;
  61335. delimiter = delimiter || '.';
  61336. if (name.indexOf(delimiter) !== -1) {
  61337. splitName = getComponentPropertyPath(name, delimiter);
  61338. if (splitName.constructor === String) {
  61339. el.setAttribute(splitName, value);
  61340. } else {
  61341. el.setAttribute(splitName[0], splitName[1], value);
  61342. }
  61343. return;
  61344. }
  61345. el.setAttribute(name, value);
  61346. };
  61347. },{}],205:[function(_dereq_,module,exports){
  61348. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  61349. var width = canvasEl.style.width;
  61350. var height = canvasEl.style.height;
  61351. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  61352. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  61353. // By changing the size 1 pixel and restoring the previous value
  61354. // we trigger a size recalculation cycle.
  61355. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  61356. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  61357. setTimeout(function () {
  61358. canvasEl.style.width = width;
  61359. canvasEl.style.height = height;
  61360. }, 200);
  61361. };
  61362. },{}],206:[function(_dereq_,module,exports){
  61363. /* global location */
  61364. /* Centralized place to reference utilities since utils is exposed to the user. */
  61365. var debug = _dereq_('./debug');
  61366. var deepAssign = _dereq_('deep-assign');
  61367. var device = _dereq_('./device');
  61368. var objectAssign = _dereq_('object-assign');
  61369. var objectPool = _dereq_('./object-pool');
  61370. var warn = debug('utils:warn');
  61371. module.exports.bind = _dereq_('./bind');
  61372. module.exports.coordinates = _dereq_('./coordinates');
  61373. module.exports.debug = debug;
  61374. module.exports.device = device;
  61375. module.exports.entity = _dereq_('./entity');
  61376. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  61377. module.exports.isIE11 = _dereq_('./is-ie11');
  61378. module.exports.material = _dereq_('./material');
  61379. module.exports.objectPool = objectPool;
  61380. module.exports.split = _dereq_('./split').split;
  61381. module.exports.styleParser = _dereq_('./styleParser');
  61382. module.exports.trackedControls = _dereq_('./tracked-controls');
  61383. module.exports.checkHeadsetConnected = function () {
  61384. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  61385. return device.checkHeadsetConnected(arguments);
  61386. };
  61387. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  61388. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  61389. };
  61390. module.exports.isIOS = function () {
  61391. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  61392. return device.isIOS(arguments);
  61393. };
  61394. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  61395. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  61396. };
  61397. module.exports.isMobile = function () {
  61398. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  61399. return device.isMobile(arguments);
  61400. };
  61401. /**
  61402. * Returns throttle function that gets called at most once every interval.
  61403. *
  61404. * @param {function} functionToThrottle
  61405. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61406. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61407. * @returns {function} Throttled function.
  61408. */
  61409. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  61410. var lastTime;
  61411. if (optionalContext) {
  61412. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61413. }
  61414. return function () {
  61415. var time = Date.now();
  61416. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  61417. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61418. lastTime = time;
  61419. functionToThrottle.apply(null, arguments);
  61420. }
  61421. };
  61422. };
  61423. /**
  61424. * Returns throttle function that gets called at most once every interval.
  61425. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  61426. *
  61427. * @param {function} functionToThrottle
  61428. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61429. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61430. * @returns {function} Throttled function.
  61431. */
  61432. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  61433. var lastTime;
  61434. if (optionalContext) {
  61435. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61436. }
  61437. return function (time, delta) {
  61438. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  61439. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61440. lastTime = time;
  61441. functionToThrottle(time, sinceLastTime);
  61442. }
  61443. };
  61444. };
  61445. /**
  61446. * Returns debounce function that gets called only once after a set of repeated calls.
  61447. *
  61448. * @param {function} functionToDebounce
  61449. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  61450. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  61451. * @returns {function} Debounced function.
  61452. */
  61453. module.exports.debounce = function (func, wait, immediate) {
  61454. var timeout;
  61455. return function () {
  61456. var context = this;
  61457. var args = arguments;
  61458. var later = function () {
  61459. timeout = null;
  61460. if (!immediate) func.apply(context, args);
  61461. };
  61462. var callNow = immediate && !timeout;
  61463. clearTimeout(timeout);
  61464. timeout = setTimeout(later, wait);
  61465. if (callNow) func.apply(context, args);
  61466. };
  61467. };
  61468. /**
  61469. * Mix the properties of source object(s) into a destination object.
  61470. *
  61471. * @param {object} dest - The object to which properties will be copied.
  61472. * @param {...object} source - The object(s) from which properties will be copied.
  61473. */
  61474. module.exports.extend = objectAssign;
  61475. module.exports.extendDeep = deepAssign;
  61476. module.exports.clone = function (obj) {
  61477. return JSON.parse(JSON.stringify(obj));
  61478. };
  61479. /**
  61480. * Checks if two values are equal.
  61481. * Includes objects and arrays and nested objects and arrays.
  61482. * Try to keep this function performant as it will be called often to see if a component
  61483. * should be updated.
  61484. *
  61485. * @param {object} a - First object.
  61486. * @param {object} b - Second object.
  61487. * @returns {boolean} Whether two objects are deeply equal.
  61488. */
  61489. var deepEqual = (function () {
  61490. var arrayPool = objectPool.createPool(function () { return []; });
  61491. return function (a, b) {
  61492. var key;
  61493. var keysA;
  61494. var keysB;
  61495. var i;
  61496. var valA;
  61497. var valB;
  61498. // If not objects or arrays, compare as values.
  61499. if (a === undefined || b === undefined || a === null || b === null ||
  61500. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  61501. (a.constructor === Array && b.constructor === Array))) {
  61502. return a === b;
  61503. }
  61504. // Different number of keys, not equal.
  61505. keysA = arrayPool.use();
  61506. keysB = arrayPool.use();
  61507. keysA.length = 0;
  61508. keysB.length = 0;
  61509. for (key in a) { keysA.push(key); }
  61510. for (key in b) { keysB.push(key); }
  61511. if (keysA.length !== keysB.length) {
  61512. arrayPool.recycle(keysA);
  61513. arrayPool.recycle(keysB);
  61514. return false;
  61515. }
  61516. // Return `false` at the first sign of inequality.
  61517. for (i = 0; i < keysA.length; ++i) {
  61518. valA = a[keysA[i]];
  61519. valB = b[keysA[i]];
  61520. // Check nested array and object.
  61521. if ((typeof valA === 'object' || typeof valB === 'object') ||
  61522. (Array.isArray(valA) && Array.isArray(valB))) {
  61523. if (valA === valB) { continue; }
  61524. if (!deepEqual(valA, valB)) {
  61525. arrayPool.recycle(keysA);
  61526. arrayPool.recycle(keysB);
  61527. return false;
  61528. }
  61529. } else if (valA !== valB) {
  61530. arrayPool.recycle(keysA);
  61531. arrayPool.recycle(keysB);
  61532. return false;
  61533. }
  61534. }
  61535. arrayPool.recycle(keysA);
  61536. arrayPool.recycle(keysB);
  61537. return true;
  61538. };
  61539. })();
  61540. module.exports.deepEqual = deepEqual;
  61541. /**
  61542. * Computes the difference between two objects.
  61543. *
  61544. * @param {object} a - First object to compare (e.g., oldData).
  61545. * @param {object} b - Second object to compare (e.g., newData).
  61546. * @returns {object}
  61547. * Difference object where set of keys note which values were not equal, and values are
  61548. * `b`'s values.
  61549. */
  61550. module.exports.diff = (function () {
  61551. var keys = [];
  61552. return function (a, b, targetObject) {
  61553. var aVal;
  61554. var bVal;
  61555. var bKey;
  61556. var diff;
  61557. var key;
  61558. var i;
  61559. var isComparingObjects;
  61560. diff = targetObject || {};
  61561. // Collect A keys.
  61562. keys.length = 0;
  61563. for (key in a) { keys.push(key); }
  61564. if (!b) { return diff; }
  61565. // Collect B keys.
  61566. for (bKey in b) {
  61567. if (keys.indexOf(bKey) === -1) {
  61568. keys.push(bKey);
  61569. }
  61570. }
  61571. for (i = 0; i < keys.length; i++) {
  61572. key = keys[i];
  61573. aVal = a[key];
  61574. bVal = b[key];
  61575. isComparingObjects = aVal && bVal &&
  61576. aVal.constructor === Object && bVal.constructor === Object;
  61577. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  61578. (!isComparingObjects && aVal !== bVal)) {
  61579. diff[key] = bVal;
  61580. }
  61581. }
  61582. return diff;
  61583. };
  61584. })();
  61585. /**
  61586. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  61587. * @param {Event} event Event object.
  61588. * @returns {Boolean} Whether the key event should be captured.
  61589. */
  61590. module.exports.shouldCaptureKeyEvent = function (event) {
  61591. if (event.metaKey) { return false; }
  61592. return document.activeElement === document.body;
  61593. };
  61594. /**
  61595. * Splits a string into an array based on a delimiter.
  61596. *
  61597. * @param {string=} [str=''] Source string
  61598. * @param {string=} [delimiter=' '] Delimiter to use
  61599. * @returns {array} Array of delimited strings
  61600. */
  61601. module.exports.splitString = function (str, delimiter) {
  61602. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  61603. // First collapse the whitespace (or whatever the delimiter is).
  61604. var regex = new RegExp(delimiter, 'g');
  61605. str = (str || '').replace(regex, delimiter);
  61606. // Then split.
  61607. return str.split(delimiter);
  61608. };
  61609. /**
  61610. * Extracts data from the element given an object that contains expected keys.
  61611. *
  61612. * @param {Element} Source element.
  61613. * @param {Object} [defaults={}] Object of default key-value pairs.
  61614. * @returns {Object}
  61615. */
  61616. module.exports.getElData = function (el, defaults) {
  61617. defaults = defaults || {};
  61618. var data = {};
  61619. Object.keys(defaults).forEach(copyAttribute);
  61620. function copyAttribute (key) {
  61621. if (el.hasAttribute(key)) {
  61622. data[key] = el.getAttribute(key);
  61623. }
  61624. }
  61625. return data;
  61626. };
  61627. /**
  61628. * Retrieves querystring value.
  61629. * @param {String} name Name of querystring key.
  61630. * @return {String} Value
  61631. */
  61632. module.exports.getUrlParameter = function (name) {
  61633. // eslint-disable-next-line no-useless-escape
  61634. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  61635. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  61636. var results = regex.exec(location.search);
  61637. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  61638. };
  61639. /**
  61640. * Detects whether context is within iframe.
  61641. */
  61642. module.exports.isIframed = function () {
  61643. return window.top !== window.self;
  61644. };
  61645. /**
  61646. * Finds all elements under the element that have the isScene
  61647. * property set to true
  61648. */
  61649. module.exports.findAllScenes = function (el) {
  61650. var matchingElements = [];
  61651. var allElements = el.getElementsByTagName('*');
  61652. for (var i = 0, n = allElements.length; i < n; i++) {
  61653. if (allElements[i].isScene) {
  61654. // Element exists with isScene set.
  61655. matchingElements.push(allElements[i]);
  61656. }
  61657. }
  61658. return matchingElements;
  61659. };
  61660. // Must be at bottom to avoid circular dependency.
  61661. module.exports.srcLoader = _dereq_('./src-loader');
  61662. },{"./bind":200,"./coordinates":201,"./debug":202,"./device":203,"./entity":204,"./forceCanvasResizeSafariMobile":205,"./is-ie11":208,"./material":210,"./object-pool":211,"./split":212,"./src-loader":213,"./styleParser":214,"./tracked-controls":215,"deep-assign":10,"object-assign":39}],207:[function(_dereq_,module,exports){
  61663. // Safari regression introduced in iOS 12 and remains in iOS 13.
  61664. // https://stackoverflow.com/questions/62717621/white-space-at-page-bottom-after-device-rotation-in-ios-safari
  61665. window.addEventListener('orientationchange', function () {
  61666. document.documentElement.style.height = `initial`;
  61667. setTimeout(function () {
  61668. document.documentElement.style.height = `100%`;
  61669. setTimeout(function () {
  61670. // this line prevents the content
  61671. // from hiding behind the address bar
  61672. window.scrollTo(0, 1);
  61673. }, 500);
  61674. }, 500);
  61675. });
  61676. },{}],208:[function(_dereq_,module,exports){
  61677. // https://stackoverflow.com/a/17907562
  61678. function getInternetExplorerVersion () {
  61679. var version = -1;
  61680. var userAgent = navigator.userAgent;
  61681. var re;
  61682. if (navigator.appName === 'Microsoft Internet Explorer') {
  61683. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  61684. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61685. } else if (navigator.appName === 'Netscape') {
  61686. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  61687. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61688. }
  61689. return version;
  61690. }
  61691. module.exports = getInternetExplorerVersion() === 11;
  61692. },{}],209:[function(_dereq_,module,exports){
  61693. /**
  61694. * Check if device is iOS and older than version 10.
  61695. */
  61696. module.exports = function isIOSOlderThan10 (userAgent) {
  61697. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  61698. };
  61699. },{}],210:[function(_dereq_,module,exports){
  61700. var THREE = _dereq_('../lib/three');
  61701. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  61702. var COLOR_MAPS = new Set([
  61703. 'emissiveMap',
  61704. 'envMap',
  61705. 'map',
  61706. 'specularMap'
  61707. ]);
  61708. /**
  61709. * Update `material` texture property (usually but not always `map`)
  61710. * from `data` property (usually but not always `src`)
  61711. *
  61712. * @param {object} shader - A-Frame shader instance.
  61713. * @param {object} data
  61714. */
  61715. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  61716. var el = shader.el;
  61717. var material = shader.material;
  61718. var rendererSystem = el.sceneEl.systems.renderer;
  61719. var src = data[dataName];
  61720. // Because a single material / shader may have multiple textures,
  61721. // we need to remember the source value for this data property
  61722. // to avoid redundant operations which can be expensive otherwise
  61723. // (e.g. video texture loads).
  61724. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  61725. if (!src) {
  61726. // Forget the prior material src.
  61727. delete shader.materialSrcs[materialName];
  61728. // Remove the texture.
  61729. setMap(null);
  61730. return;
  61731. }
  61732. // Don't process if material src hasn't changed.
  61733. if (src === shader.materialSrcs[materialName]) { return; }
  61734. // Remember the new src for this texture (there may be multiple).
  61735. shader.materialSrcs[materialName] = src;
  61736. // If the new material src is already a texture, just use it.
  61737. if (src instanceof THREE.Texture) { setMap(src); } else {
  61738. // Load texture for the new material src.
  61739. // (And check if we should still use it once available in callback.)
  61740. el.sceneEl.systems.material.loadTexture(src,
  61741. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  61742. checkSetMap);
  61743. }
  61744. function checkSetMap (texture) {
  61745. // If the source has been changed, don't use loaded texture.
  61746. if (shader.materialSrcs[materialName] !== src) { return; }
  61747. setMap(texture);
  61748. }
  61749. function setMap (texture) {
  61750. material[materialName] = texture;
  61751. if (texture && COLOR_MAPS.has(materialName)) {
  61752. rendererSystem.applyColorCorrection(texture);
  61753. }
  61754. material.needsUpdate = true;
  61755. handleTextureEvents(el, texture);
  61756. }
  61757. };
  61758. /**
  61759. * Update `material.map` given `data.src`. For standard and flat shaders.
  61760. *
  61761. * @param {object} shader - A-Frame shader instance.
  61762. * @param {object} data
  61763. */
  61764. module.exports.updateMap = function (shader, data) {
  61765. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  61766. };
  61767. /**
  61768. * Updates the material's maps which give the illusion of extra geometry.
  61769. *
  61770. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  61771. * @param {object} shader - A-Frame shader instance
  61772. * @param {object} data
  61773. */
  61774. module.exports.updateDistortionMap = function (longType, shader, data) {
  61775. var shortType = longType;
  61776. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  61777. var el = shader.el;
  61778. var material = shader.material;
  61779. var rendererSystem = el.sceneEl.systems.renderer;
  61780. var src = data[longType + 'Map'];
  61781. var info = {};
  61782. info.src = src;
  61783. // Pass through the repeat and offset to be handled by the material loader.
  61784. info.offset = data[longType + 'TextureOffset'];
  61785. info.repeat = data[longType + 'TextureRepeat'];
  61786. info.wrap = data[longType + 'TextureWrap'];
  61787. if (src) {
  61788. if (src === shader[longType + 'TextureSrc']) { return; }
  61789. // Texture added or changed.
  61790. shader[longType + 'TextureSrc'] = src;
  61791. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  61792. return;
  61793. }
  61794. // Texture removed.
  61795. if (!material.map) { return; }
  61796. setMap(null);
  61797. function setMap (texture) {
  61798. var slot = shortType + 'Map';
  61799. material[slot] = texture;
  61800. if (texture && COLOR_MAPS.has(slot)) {
  61801. rendererSystem.applyColorCorrection(texture);
  61802. }
  61803. material.needsUpdate = true;
  61804. handleTextureEvents(el, texture);
  61805. }
  61806. };
  61807. /**
  61808. * Emit event on entities on texture-related events.
  61809. *
  61810. * @param {Element} el - Entity.
  61811. * @param {object} texture - three.js Texture.
  61812. */
  61813. function handleTextureEvents (el, texture) {
  61814. if (!texture) { return; }
  61815. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  61816. // Video events.
  61817. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  61818. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  61819. // Check to see if we need to use iOS 10 HLS shader.
  61820. // Only override the shader if it is stock shader that we know doesn't correct.
  61821. if (!el.components || !el.components.material) { return; }
  61822. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  61823. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  61824. el.setAttribute('material', 'shader', 'ios10hls');
  61825. }
  61826. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  61827. });
  61828. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  61829. // Works for non-looping videos only.
  61830. el.emit('materialvideoended', {src: texture.image, texture: texture});
  61831. });
  61832. }
  61833. module.exports.handleTextureEvents = handleTextureEvents;
  61834. /**
  61835. * Given video element src and type, guess whether stream is HLS.
  61836. *
  61837. * @param {string} src - src from video element (generally URL to content).
  61838. * @param {string} type - type from video element (generally MIME type if present).
  61839. */
  61840. module.exports.isHLS = function (src, type) {
  61841. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  61842. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  61843. return false;
  61844. };
  61845. },{"../lib/three":180}],211:[function(_dereq_,module,exports){
  61846. /*
  61847. Adapted deePool by Kyle Simpson.
  61848. MIT License: http://getify.mit-license.org
  61849. */
  61850. var EMPTY_SLOT = Object.freeze(Object.create(null));
  61851. // Default object factory.
  61852. function defaultObjectFactory () { return {}; }
  61853. /**
  61854. * Create a new pool.
  61855. */
  61856. module.exports.createPool = function createPool (objectFactory) {
  61857. var objPool = [];
  61858. var nextFreeSlot = null; // Pool location to look for a free object to use.
  61859. objectFactory = objectFactory || defaultObjectFactory;
  61860. function use () {
  61861. var objToUse;
  61862. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  61863. grow(objPool.length || 5);
  61864. }
  61865. objToUse = objPool[nextFreeSlot];
  61866. objPool[nextFreeSlot++] = EMPTY_SLOT;
  61867. clearObject(objToUse);
  61868. return objToUse;
  61869. }
  61870. function recycle (obj) {
  61871. if (!(obj instanceof Object)) { return; }
  61872. if (nextFreeSlot === null || nextFreeSlot === -1) {
  61873. objPool[objPool.length] = obj;
  61874. return;
  61875. }
  61876. objPool[--nextFreeSlot] = obj;
  61877. }
  61878. function grow (count) {
  61879. var currentLength;
  61880. var i;
  61881. count = count === undefined ? objPool.length : count;
  61882. if (count > 0 && nextFreeSlot == null) {
  61883. nextFreeSlot = 0;
  61884. }
  61885. if (count > 0) {
  61886. currentLength = objPool.length;
  61887. objPool.length += Number(count);
  61888. for (i = currentLength; i < objPool.length; i++) {
  61889. // Add new obj to pool.
  61890. objPool[i] = objectFactory();
  61891. }
  61892. }
  61893. return objPool.length;
  61894. }
  61895. function size () {
  61896. return objPool.length;
  61897. }
  61898. return {
  61899. grow: grow,
  61900. pool: objPool,
  61901. recycle: recycle,
  61902. size: size,
  61903. use: use
  61904. };
  61905. };
  61906. function clearObject (obj) {
  61907. var key;
  61908. if (!obj || obj.constructor !== Object) { return; }
  61909. for (key in obj) { obj[key] = undefined; }
  61910. }
  61911. module.exports.clearObject = clearObject;
  61912. function removeUnusedKeys (obj, schema) {
  61913. var key;
  61914. if (!obj || obj.constructor !== Object) { return; }
  61915. for (key in obj) {
  61916. if (!(key in schema)) {
  61917. delete obj[key];
  61918. }
  61919. }
  61920. }
  61921. module.exports.removeUnusedKeys = removeUnusedKeys;
  61922. },{}],212:[function(_dereq_,module,exports){
  61923. /**
  61924. * String split with cached result.
  61925. */
  61926. module.exports.split = (function () {
  61927. var splitCache = {};
  61928. return function (str, delimiter) {
  61929. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  61930. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  61931. splitCache[delimiter][str] = str.split(delimiter);
  61932. return splitCache[delimiter][str];
  61933. };
  61934. })();
  61935. },{}],213:[function(_dereq_,module,exports){
  61936. /* global Image, XMLHttpRequest */
  61937. var debug = _dereq_('./debug');
  61938. var warn = debug('utils:src-loader:warn');
  61939. /**
  61940. * Validate a texture, either as a selector or as a URL.
  61941. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  61942. * callback.
  61943. *
  61944. * `src` will be passed into the callback
  61945. *
  61946. * @params {string|Element} src - URL or media element.
  61947. * @params {function} isImageCb - callback if texture is an image.
  61948. * @params {function} isVideoCb - callback if texture is a video.
  61949. */
  61950. function validateSrc (src, isImageCb, isVideoCb) {
  61951. checkIsImage(src, function isAnImageUrl (isImage) {
  61952. if (isImage) {
  61953. isImageCb(src);
  61954. return;
  61955. }
  61956. isVideoCb(src);
  61957. });
  61958. }
  61959. /**
  61960. * Validates six images as a cubemap, either as selector or comma-separated
  61961. * URLs.
  61962. *
  61963. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61964. must be wrapped by `url()`.
  61965. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61966. must be wrapped by `url()`.
  61967. */
  61968. function validateCubemapSrc (src, cb) {
  61969. var aCubemap;
  61970. var cubemapSrcRegex = '';
  61971. var i;
  61972. var urls;
  61973. var validatedUrls = [];
  61974. for (i = 0; i < 5; i++) {
  61975. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  61976. }
  61977. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  61978. urls = src.match(new RegExp(cubemapSrcRegex));
  61979. // `src` is a comma-separated list of URLs.
  61980. // In this case, re-use validateSrc for each side of the cube.
  61981. function isImageCb (url) {
  61982. validatedUrls.push(url);
  61983. if (validatedUrls.length === 6) {
  61984. cb(validatedUrls);
  61985. }
  61986. }
  61987. if (urls) {
  61988. for (i = 1; i < 7; i++) {
  61989. validateSrc(parseUrl(urls[i]), isImageCb);
  61990. }
  61991. return;
  61992. }
  61993. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  61994. aCubemap = validateAndGetQuerySelector(src);
  61995. if (!aCubemap) { return; }
  61996. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  61997. return cb(aCubemap.srcs);
  61998. }
  61999. // Else if aCubeMap is not a <a-cubemap>.
  62000. warn('Selector "%s" does not point to <a-cubemap>', src);
  62001. }
  62002. /**
  62003. * Parses src from `url(src)`.
  62004. * @param {string} src - String to parse.
  62005. * @return {string} The parsed src, if parseable.
  62006. */
  62007. function parseUrl (src) {
  62008. var parsedSrc = src.match(/\url\((.+)\)/);
  62009. if (!parsedSrc) { return; }
  62010. return parsedSrc[1];
  62011. }
  62012. /**
  62013. * Call back whether `src` is an image.
  62014. *
  62015. * @param {string|Element} src - URL or element that will be tested.
  62016. * @param {function} onResult - Callback with whether `src` is an image.
  62017. */
  62018. function checkIsImage (src, onResult) {
  62019. var request;
  62020. if (src.tagName) {
  62021. onResult(src.tagName === 'IMG');
  62022. return;
  62023. }
  62024. request = new XMLHttpRequest();
  62025. // Try to send HEAD request to check if image first.
  62026. request.open('HEAD', src);
  62027. request.addEventListener('load', function (event) {
  62028. var contentType;
  62029. if (request.status >= 200 && request.status < 300) {
  62030. contentType = request.getResponseHeader('Content-Type');
  62031. if (contentType == null) {
  62032. checkIsImageFallback(src, onResult);
  62033. } else {
  62034. if (contentType.startsWith('image')) {
  62035. onResult(true);
  62036. } else {
  62037. onResult(false);
  62038. }
  62039. }
  62040. } else {
  62041. checkIsImageFallback(src, onResult);
  62042. }
  62043. request.abort();
  62044. });
  62045. request.send();
  62046. }
  62047. function checkIsImageFallback (src, onResult) {
  62048. var tester = new Image();
  62049. tester.addEventListener('load', onLoad);
  62050. function onLoad () { onResult(true); }
  62051. tester.addEventListener('error', onError);
  62052. function onError () { onResult(false); }
  62053. tester.src = src;
  62054. }
  62055. /**
  62056. * Query and validate a query selector,
  62057. *
  62058. * @param {string} selector - DOM selector.
  62059. * @return {object|null|undefined} Selected DOM element if exists.
  62060. null if query yields no results.
  62061. undefined if `selector` is not a valid selector.
  62062. */
  62063. function validateAndGetQuerySelector (selector) {
  62064. try {
  62065. var el = document.querySelector(selector);
  62066. if (!el) {
  62067. warn('No element was found matching the selector: "%s"', selector);
  62068. }
  62069. return el;
  62070. } catch (e) { // Capture exception if it's not a valid selector.
  62071. warn('"%s" is not a valid selector', selector);
  62072. return undefined;
  62073. }
  62074. }
  62075. module.exports = {
  62076. parseUrl: parseUrl,
  62077. validateSrc: validateSrc,
  62078. validateCubemapSrc: validateCubemapSrc
  62079. };
  62080. },{"./debug":202}],214:[function(_dereq_,module,exports){
  62081. /**
  62082. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  62083. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  62084. * by Josh Johnston (MIT License).
  62085. */
  62086. var DASH_REGEX = /-([a-z])/g;
  62087. /**
  62088. * Deserialize style-like string into an object of properties.
  62089. *
  62090. * @param {string} value - HTML attribute value.
  62091. * @param {object} obj - Reused object for object pooling.
  62092. * @returns {object} Property data.
  62093. */
  62094. module.exports.parse = function (value, obj) {
  62095. var parsedData;
  62096. if (typeof value !== 'string') { return value; }
  62097. parsedData = styleParse(value, obj);
  62098. // The style parser returns an object { "" : "test"} when fed a string
  62099. if (parsedData['']) { return value; }
  62100. return transformKeysToCamelCase(parsedData);
  62101. };
  62102. /**
  62103. * Serialize an object of properties into a style-like string.
  62104. *
  62105. * @param {object} data - Property data.
  62106. * @returns {string}
  62107. */
  62108. module.exports.stringify = function (data) {
  62109. if (typeof data === 'string') { return data; }
  62110. return styleStringify(data);
  62111. };
  62112. /**
  62113. * Converts string from hyphen to camelCase.
  62114. *
  62115. * @param {string} str - String to camelCase.
  62116. * @return {string} CamelCased string.
  62117. */
  62118. function toCamelCase (str) {
  62119. return str.replace(DASH_REGEX, upperCase);
  62120. }
  62121. module.exports.toCamelCase = toCamelCase;
  62122. /**
  62123. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  62124. * `maxValue`).
  62125. *
  62126. * @param {object} obj - The object to camelCase keys.
  62127. * @return {object} The object with keys camelCased.
  62128. */
  62129. function transformKeysToCamelCase (obj) {
  62130. var camelKey;
  62131. var key;
  62132. for (key in obj) {
  62133. camelKey = toCamelCase(key);
  62134. if (key === camelKey) { continue; }
  62135. obj[camelKey] = obj[key];
  62136. delete obj[key];
  62137. }
  62138. return obj;
  62139. }
  62140. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  62141. /**
  62142. * Split a string into chunks matching `<key>: <value>`
  62143. */
  62144. var getKeyValueChunks = (function () {
  62145. var chunks = [];
  62146. var hasUnclosedUrl = /url\([^)]+$/;
  62147. return function getKeyValueChunks (raw) {
  62148. var chunk = '';
  62149. var nextSplit;
  62150. var offset = 0;
  62151. var sep = ';';
  62152. chunks.length = 0;
  62153. while (offset < raw.length) {
  62154. nextSplit = raw.indexOf(sep, offset);
  62155. if (nextSplit === -1) { nextSplit = raw.length; }
  62156. chunk += raw.substring(offset, nextSplit);
  62157. // data URIs can contain semicolons, so make sure we get the whole thing
  62158. if (hasUnclosedUrl.test(chunk)) {
  62159. chunk += ';';
  62160. offset = nextSplit + 1;
  62161. continue;
  62162. }
  62163. chunks.push(chunk.trim());
  62164. chunk = '';
  62165. offset = nextSplit + 1;
  62166. }
  62167. return chunks;
  62168. };
  62169. })();
  62170. /**
  62171. * Convert a style attribute string to an object.
  62172. *
  62173. * @param {object} str - Attribute string.
  62174. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  62175. */
  62176. function styleParse (str, obj) {
  62177. var chunks;
  62178. var i;
  62179. var item;
  62180. var pos;
  62181. var key;
  62182. var val;
  62183. obj = obj || {};
  62184. chunks = getKeyValueChunks(str);
  62185. for (i = 0; i < chunks.length; i++) {
  62186. item = chunks[i];
  62187. if (!item) { continue; }
  62188. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  62189. pos = item.indexOf(':');
  62190. key = item.substr(0, pos).trim();
  62191. val = item.substr(pos + 1).trim();
  62192. obj[key] = val;
  62193. }
  62194. return obj;
  62195. }
  62196. /**
  62197. * Convert an object into an attribute string
  62198. **/
  62199. function styleStringify (obj) {
  62200. var key;
  62201. var keyCount = 0;
  62202. var i = 0;
  62203. var str = '';
  62204. for (key in obj) { keyCount++; }
  62205. for (key in obj) {
  62206. str += (key + ': ' + obj[key]);
  62207. if (i < keyCount - 1) { str += '; '; }
  62208. i++;
  62209. }
  62210. return str;
  62211. }
  62212. function upperCase (str) { return str[1].toUpperCase(); }
  62213. },{}],215:[function(_dereq_,module,exports){
  62214. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  62215. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  62216. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  62217. /**
  62218. * Called on controller component `.play` handlers.
  62219. * Check if controller matches parameters and inject tracked-controls component.
  62220. * Handle event listeners.
  62221. * Generate controllerconnected or controllerdisconnected events.
  62222. *
  62223. * @param {object} component - Tracked controls component.
  62224. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  62225. * @param {object} queryObject - Map of values to match.
  62226. */
  62227. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  62228. var el = component.el;
  62229. var controller;
  62230. var hasWebXR = el.sceneEl.hasWebXR;
  62231. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  62232. var isPresent;
  62233. controller = isControllerPresent(component, idPrefix, queryObject);
  62234. isPresent = !!controller;
  62235. // If component was previously paused and now playing, re-add event listeners.
  62236. // Handle the event listeners here since this helper method is control of calling
  62237. // `.addEventListeners` and `.removeEventListeners`.
  62238. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  62239. component.addEventListeners();
  62240. }
  62241. // Nothing changed, no need to do anything.
  62242. if (isPresent === component.controllerPresent) { return isPresent; }
  62243. component.controllerPresent = isPresent;
  62244. // Update controller presence.
  62245. if (isPresent) {
  62246. component.addEventListeners();
  62247. component.injectTrackedControls(controller);
  62248. el.emit('controllerconnected', {name: component.name, component: component});
  62249. } else {
  62250. component.removeEventListeners();
  62251. el.emit('controllerdisconnected', {name: component.name, component: component});
  62252. }
  62253. };
  62254. /**
  62255. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  62256. *
  62257. * @param {object} component - Tracked controls component.
  62258. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  62259. * @param {object} queryObject - Map of values to match.
  62260. */
  62261. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  62262. var gamepads;
  62263. var sceneEl = component.el.sceneEl;
  62264. var trackedControlsSystem;
  62265. var filterControllerIndex = queryObject.index || 0;
  62266. if (!idPrefix) { return false; }
  62267. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  62268. if (!trackedControlsSystem) { return false; }
  62269. gamepads = trackedControlsSystem.controllers;
  62270. if (!gamepads.length) { return false; }
  62271. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  62272. filterControllerIndex);
  62273. }
  62274. /**
  62275. *
  62276. * @param {object} component - Tracked controls component.
  62277. */
  62278. function isControllerPresentWebXR (component, id, queryObject) {
  62279. var controllers;
  62280. var sceneEl = component.el.sceneEl;
  62281. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  62282. if (!trackedControlsSystem) { return false; }
  62283. controllers = trackedControlsSystem.controllers;
  62284. if (!controllers || !controllers.length) { return false; }
  62285. return findMatchingControllerWebXR(
  62286. controllers, id,
  62287. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles, queryObject.handTracking);
  62288. }
  62289. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  62290. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  62291. /**
  62292. * Walk through the given controllers to find any where the device ID equals
  62293. * filterIdExact, or startsWith filterIdPrefix.
  62294. * A controller where this considered true is considered a 'match'.
  62295. *
  62296. * For each matching controller:
  62297. * If filterHand is set, and the controller:
  62298. * is handed, we further verify that controller.hand equals filterHand.
  62299. * is unhanded (controller.hand is ''), we skip until we have found a
  62300. * number of matching controllers that equals filterControllerIndex
  62301. * If filterHand is not set, we skip until we have found the nth matching
  62302. * controller, where n equals filterControllerIndex
  62303. *
  62304. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  62305. * one or both of: [filterHand, filterControllerIndex]
  62306. *
  62307. * @param {object} controllers - Array of gamepads to search
  62308. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  62309. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  62310. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  62311. * @param {object} filterControllerIndex - Find the nth matching controller,
  62312. * where n equals filterControllerIndex. defaults to 0.
  62313. */
  62314. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  62315. filterControllerIndex) {
  62316. var controller;
  62317. var i;
  62318. var matchingControllerOccurence = 0;
  62319. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  62320. for (i = 0; i < controllers.length; i++) {
  62321. controller = controllers[i];
  62322. // Determine if the controller ID matches our criteria.
  62323. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  62324. continue;
  62325. }
  62326. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  62327. // If the hand filter and controller handedness are defined we compare them.
  62328. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  62329. // If we have detected an unhanded controller and the component was asking
  62330. // for a particular hand, we need to treat the controllers in the array as
  62331. // pairs of controllers. This effectively means that we need to skip
  62332. // NUM_HANDS matches for each controller number, instead of 1.
  62333. if (filterHand && !controller.hand) {
  62334. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  62335. } else {
  62336. return controller;
  62337. }
  62338. // We are looking for the nth occurence of a matching controller
  62339. // (n equals targetControllerMatch).
  62340. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  62341. ++matchingControllerOccurence;
  62342. }
  62343. return undefined;
  62344. }
  62345. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles, handTracking) {
  62346. var i;
  62347. var j;
  62348. var controller;
  62349. var controllerMatch = false;
  62350. var controllerHasHandedness;
  62351. var profiles;
  62352. for (i = 0; i < controllers.length; i++) {
  62353. controller = controllers[i];
  62354. profiles = controller.profiles;
  62355. if (handTracking) {
  62356. controllerMatch = controller.hand;
  62357. } else {
  62358. if (iterateProfiles) {
  62359. for (j = 0; j < profiles.length; j++) {
  62360. controllerMatch = profiles[j].startsWith(idPrefix);
  62361. if (controllerMatch) { break; }
  62362. }
  62363. } else {
  62364. controllerMatch = profiles.length > 0 && profiles[0].startsWith(idPrefix);
  62365. }
  62366. }
  62367. if (!controllerMatch) { continue; }
  62368. // Vive controllers are assigned handedness at runtime and it might not be always available.
  62369. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  62370. if (controllerHasHandedness) {
  62371. if (controller.handedness === handedness) { return controllers[i]; }
  62372. } else { // Fallback to index if controller has no handedness.
  62373. if ((i === index)) { return controllers[i]; }
  62374. }
  62375. }
  62376. return undefined;
  62377. }
  62378. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  62379. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  62380. /**
  62381. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  62382. *
  62383. * @param {object} component - Controller component in use.
  62384. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  62385. * @param {object} evt - Event to process.
  62386. */
  62387. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  62388. var axes;
  62389. var buttonType;
  62390. var changed;
  62391. var detail;
  62392. var j;
  62393. for (buttonType in axesMapping) {
  62394. axes = axesMapping[buttonType];
  62395. changed = false;
  62396. for (j = 0; j < axes.length; j++) {
  62397. if (evt.detail.changed[axes[j]]) { changed = true; }
  62398. }
  62399. if (!changed) { continue; }
  62400. // Axis has changed. Emit the specific moved event with axis values in detail.
  62401. detail = {};
  62402. for (j = 0; j < axes.length; j++) {
  62403. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  62404. }
  62405. component.el.emit(buttonType + 'moved', detail);
  62406. }
  62407. };
  62408. /**
  62409. * Handle a button event and reemits the events.
  62410. *
  62411. * @param {string} id - id of the button.
  62412. * @param {string} evtName - name of the reemitted event
  62413. * @param {object} component - reference to the component
  62414. * @param {string} hand - handedness of the controller: left or right.
  62415. */
  62416. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  62417. var mapping = hand ? component.mapping[hand] : component.mapping;
  62418. var buttonName = mapping.buttons[id];
  62419. component.el.emit(buttonName + evtName);
  62420. if (component.updateModel) {
  62421. component.updateModel(buttonName, evtName);
  62422. }
  62423. };
  62424. },{"../constants":124}],216:[function(_dereq_,module,exports){
  62425. /**
  62426. * @author richt / http://richt.me
  62427. * @author WestLangley / http://github.com/WestLangley
  62428. *
  62429. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  62430. */
  62431. THREE.DeviceOrientationControls = function ( object ) {
  62432. var scope = this;
  62433. this.object = object;
  62434. this.object.rotation.reorder( 'YXZ' );
  62435. this.enabled = true;
  62436. this.deviceOrientation = {};
  62437. this.screenOrientation = 0;
  62438. this.alphaOffset = 0; // radians
  62439. var onDeviceOrientationChangeEvent = function ( event ) {
  62440. scope.deviceOrientation = event;
  62441. };
  62442. var onScreenOrientationChangeEvent = function () {
  62443. scope.screenOrientation = window.orientation || 0;
  62444. };
  62445. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  62446. var setObjectQuaternion = function () {
  62447. var zee = new THREE.Vector3( 0, 0, 1 );
  62448. var euler = new THREE.Euler();
  62449. var q0 = new THREE.Quaternion();
  62450. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  62451. return function ( quaternion, alpha, beta, gamma, orient ) {
  62452. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  62453. quaternion.setFromEuler( euler ); // orient the device
  62454. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  62455. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  62456. };
  62457. }();
  62458. this.connect = function () {
  62459. onScreenOrientationChangeEvent();
  62460. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62461. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62462. scope.enabled = true;
  62463. };
  62464. this.disconnect = function () {
  62465. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62466. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62467. scope.enabled = false;
  62468. };
  62469. this.update = function () {
  62470. if ( scope.enabled === false ) return;
  62471. var device = scope.deviceOrientation;
  62472. if ( device ) {
  62473. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  62474. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  62475. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  62476. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  62477. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  62478. }
  62479. };
  62480. this.dispose = function () {
  62481. scope.disconnect();
  62482. };
  62483. this.connect();
  62484. };
  62485. },{}],217:[function(_dereq_,module,exports){
  62486. window.glStats = function () {
  62487. var _rS = null;
  62488. var _totalDrawArraysCalls = 0,
  62489. _totalDrawElementsCalls = 0,
  62490. _totalUseProgramCalls = 0,
  62491. _totalFaces = 0,
  62492. _totalVertices = 0,
  62493. _totalPoints = 0,
  62494. _totalBindTexures = 0;
  62495. function _h ( f, c ) {
  62496. return function () {
  62497. c.apply( this, arguments );
  62498. f.apply( this, arguments );
  62499. };
  62500. }
  62501. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  62502. _totalDrawArraysCalls++;
  62503. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  62504. else _totalVertices += arguments[ 2 ];
  62505. } );
  62506. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  62507. _totalDrawElementsCalls++;
  62508. _totalFaces += arguments[ 1 ] / 3;
  62509. _totalVertices += arguments[ 1 ];
  62510. } );
  62511. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  62512. _totalUseProgramCalls++;
  62513. } );
  62514. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  62515. _totalBindTexures++;
  62516. } );
  62517. var _values = {
  62518. allcalls: {
  62519. over: 3000,
  62520. caption: 'Calls (hook)'
  62521. },
  62522. drawelements: {
  62523. caption: 'drawElements (hook)'
  62524. },
  62525. drawarrays: {
  62526. caption: 'drawArrays (hook)'
  62527. }
  62528. };
  62529. var _groups = [ {
  62530. caption: 'WebGL',
  62531. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  62532. } ];
  62533. var _fractions = [ {
  62534. base: 'allcalls',
  62535. steps: [ 'drawelements', 'drawarrays' ]
  62536. } ];
  62537. function _update () {
  62538. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  62539. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  62540. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  62541. _rS( 'bindTexture' ).set( _totalBindTexures );
  62542. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  62543. _rS( 'glfaces' ).set( _totalFaces );
  62544. _rS( 'glvertices' ).set( _totalVertices );
  62545. _rS( 'glpoints' ).set( _totalPoints );
  62546. }
  62547. function _start () {
  62548. _totalDrawArraysCalls = 0;
  62549. _totalDrawElementsCalls = 0;
  62550. _totalUseProgramCalls = 0;
  62551. _totalFaces = 0;
  62552. _totalVertices = 0;
  62553. _totalPoints = 0;
  62554. _totalBindTexures = 0;
  62555. }
  62556. function _end () {}
  62557. function _attach ( r ) {
  62558. _rS = r;
  62559. }
  62560. return {
  62561. update: _update,
  62562. start: _start,
  62563. end: _end,
  62564. attach: _attach,
  62565. values: _values,
  62566. groups: _groups,
  62567. fractions: _fractions
  62568. };
  62569. };
  62570. window.threeStats = function ( renderer ) {
  62571. var _rS = null;
  62572. var _values = {
  62573. 'renderer.info.memory.geometries': {
  62574. caption: 'Geometries'
  62575. },
  62576. 'renderer.info.memory.textures': {
  62577. caption: 'Textures'
  62578. },
  62579. 'renderer.info.programs': {
  62580. caption: 'Programs'
  62581. },
  62582. 'renderer.info.render.calls': {
  62583. caption: 'Calls'
  62584. },
  62585. 'renderer.info.render.triangles': {
  62586. caption: 'Triangles',
  62587. over: 1000
  62588. },
  62589. 'renderer.info.render.points': {
  62590. caption: 'Points'
  62591. }
  62592. };
  62593. var _groups = [ {
  62594. caption: 'Three.js - Memory',
  62595. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  62596. }, {
  62597. caption: 'Three.js - Render',
  62598. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  62599. } ];
  62600. var _fractions = [];
  62601. function _update () {
  62602. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  62603. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  62604. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  62605. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  62606. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  62607. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  62608. }
  62609. function _start () {}
  62610. function _end () {}
  62611. function _attach ( r ) {
  62612. _rS = r;
  62613. }
  62614. return {
  62615. update: _update,
  62616. start: _start,
  62617. end: _end,
  62618. attach: _attach,
  62619. values: _values,
  62620. groups: _groups,
  62621. fractions: _fractions
  62622. };
  62623. };
  62624. /*
  62625. * From https://github.com/paulirish/memory-stats.js
  62626. */
  62627. window.BrowserStats = function () {
  62628. var _rS = null;
  62629. var _usedJSHeapSize = 0,
  62630. _totalJSHeapSize = 0;
  62631. if ( window.performance && !performance.memory ) {
  62632. performance.memory = {
  62633. usedJSHeapSize: 0,
  62634. totalJSHeapSize: 0
  62635. };
  62636. }
  62637. if ( performance.memory.totalJSHeapSize === 0 ) {
  62638. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  62639. }
  62640. var _values = {
  62641. memory: {
  62642. caption: 'Used Memory',
  62643. average: true,
  62644. avgMs: 1000,
  62645. over: 22
  62646. },
  62647. total: {
  62648. caption: 'Total Memory'
  62649. }
  62650. };
  62651. var _groups = [ {
  62652. caption: 'Browser',
  62653. values: [ 'memory', 'total' ]
  62654. } ];
  62655. var _fractions = [ {
  62656. base: 'total',
  62657. steps: [ 'memory' ]
  62658. } ];
  62659. var log1024 = Math.log( 1024 );
  62660. function _size ( v ) {
  62661. var precision = 100; //Math.pow(10, 2);
  62662. var i = Math.floor( Math.log( v ) / log1024 );
  62663. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  62664. }
  62665. function _update () {
  62666. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  62667. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  62668. _rS( 'memory' ).set( _usedJSHeapSize );
  62669. _rS( 'total' ).set( _totalJSHeapSize );
  62670. }
  62671. function _start () {
  62672. _usedJSHeapSize = 0;
  62673. }
  62674. function _end () {}
  62675. function _attach ( r ) {
  62676. _rS = r;
  62677. }
  62678. return {
  62679. update: _update,
  62680. start: _start,
  62681. end: _end,
  62682. attach: _attach,
  62683. values: _values,
  62684. groups: _groups,
  62685. fractions: _fractions
  62686. };
  62687. };
  62688. if (typeof module === 'object') {
  62689. module.exports = {
  62690. glStats: window.glStats,
  62691. threeStats: window.threeStats,
  62692. BrowserStats: window.BrowserStats
  62693. };
  62694. }
  62695. },{}],218:[function(_dereq_,module,exports){
  62696. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  62697. 'use strict';
  62698. ( function () {
  62699. if ( 'performance' in window == false ) {
  62700. window.performance = {};
  62701. }
  62702. var performance = window.performance;
  62703. if ( 'now' in performance == false ) {
  62704. var nowOffset = Date.now();
  62705. if ( performance.timing && performance.timing.navigationStart ) {
  62706. nowOffset = performance.timing.navigationStart;
  62707. }
  62708. performance.now = function now () {
  62709. return Date.now() - nowOffset;
  62710. };
  62711. }
  62712. if( !performance.mark ) {
  62713. performance.mark = function(){}
  62714. }
  62715. if( !performance.measure ) {
  62716. performance.measure = function(){}
  62717. }
  62718. } )();
  62719. window.rStats = function rStats ( settings ) {
  62720. function iterateKeys ( array, callback ) {
  62721. var keys = Object.keys( array );
  62722. for ( var j = 0, l = keys.length; j < l; j++ ) {
  62723. callback( keys[ j ] );
  62724. }
  62725. }
  62726. function importCSS ( url ) {
  62727. var element = document.createElement( 'link' );
  62728. element.href = url;
  62729. element.rel = 'stylesheet';
  62730. element.type = 'text/css';
  62731. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  62732. }
  62733. var _settings = settings || {};
  62734. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  62735. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  62736. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  62737. var _css = _settings.css || [ _cssFont, _cssRStats ];
  62738. _css.forEach(function (uri) {
  62739. importCSS( uri );
  62740. });
  62741. if ( !_settings.values ) _settings.values = {};
  62742. var _base, _div, _elHeight = 10, _elWidth = 200;
  62743. var _perfCounters = {};
  62744. function Graph ( _dom, _id, _defArg ) {
  62745. var _def = _defArg || {};
  62746. var _canvas = document.createElement( 'canvas' ),
  62747. _ctx = _canvas.getContext( '2d' ),
  62748. _max = 0,
  62749. _current = 0;
  62750. var c = _def.color ? _def.color : '#666666';
  62751. var _dotCanvas = document.createElement( 'canvas' ),
  62752. _dotCtx = _dotCanvas.getContext( '2d' );
  62753. _dotCanvas.width = 1;
  62754. _dotCanvas.height = 2 * _elHeight;
  62755. _dotCtx.fillStyle = '#444444';
  62756. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62757. _dotCtx.fillStyle = c;
  62758. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62759. _dotCtx.fillStyle = '#ffffff';
  62760. _dotCtx.globalAlpha = 0.5;
  62761. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  62762. _dotCtx.globalAlpha = 1;
  62763. var _alarmCanvas = document.createElement( 'canvas' ),
  62764. _alarmCtx = _alarmCanvas.getContext( '2d' );
  62765. _alarmCanvas.width = 1;
  62766. _alarmCanvas.height = 2 * _elHeight;
  62767. _alarmCtx.fillStyle = '#444444';
  62768. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62769. _alarmCtx.fillStyle = '#b70000';
  62770. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62771. _alarmCtx.globalAlpha = 0.5;
  62772. _alarmCtx.fillStyle = '#ffffff';
  62773. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  62774. _alarmCtx.globalAlpha = 1;
  62775. function _init () {
  62776. _canvas.width = _elWidth;
  62777. _canvas.height = _elHeight;
  62778. _canvas.style.width = _canvas.width + 'px';
  62779. _canvas.style.height = _canvas.height + 'px';
  62780. _canvas.className = 'rs-canvas';
  62781. _dom.appendChild( _canvas );
  62782. _ctx.fillStyle = '#444444';
  62783. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62784. }
  62785. function _draw ( v, alarm ) {
  62786. _current += ( v - _current ) * 0.1;
  62787. _max *= 0.99;
  62788. if ( _current > _max ) _max = _current;
  62789. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62790. if ( alarm ) {
  62791. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62792. } else {
  62793. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62794. }
  62795. }
  62796. _init();
  62797. return {
  62798. draw: _draw
  62799. };
  62800. }
  62801. function StackGraph ( _dom, _num ) {
  62802. var _canvas = document.createElement( 'canvas' ),
  62803. _ctx = _canvas.getContext( '2d' );
  62804. function _init () {
  62805. _canvas.width = _elWidth;
  62806. _canvas.height = _elHeight * _num;
  62807. _canvas.style.width = _canvas.width + 'px';
  62808. _canvas.style.height = _canvas.height + 'px';
  62809. _canvas.className = 'rs-canvas';
  62810. _dom.appendChild( _canvas );
  62811. _ctx.fillStyle = '#444444';
  62812. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62813. }
  62814. function _draw ( v ) {
  62815. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62816. var th = 0;
  62817. iterateKeys( v, function ( j ) {
  62818. var h = v[ j ] * _canvas.height;
  62819. _ctx.fillStyle = _colours[ j ];
  62820. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  62821. th += h;
  62822. } );
  62823. }
  62824. _init();
  62825. return {
  62826. draw: _draw
  62827. };
  62828. }
  62829. function PerfCounter ( id, group ) {
  62830. var _id = id,
  62831. _time,
  62832. _value = 0,
  62833. _total = 0,
  62834. _averageValue = 0,
  62835. _accumValue = 0,
  62836. _accumStart = performance.now(),
  62837. _accumSamples = 0,
  62838. _dom = document.createElement( 'div' ),
  62839. _spanId = document.createElement( 'span' ),
  62840. _spanValue = document.createElement( 'div' ),
  62841. _spanValueText = document.createTextNode( '' ),
  62842. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  62843. _graph = new Graph( _dom, _id, _def ),
  62844. _started = false;
  62845. _spanId.className = 'rs-counter-id';
  62846. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  62847. _spanValue.className = 'rs-counter-value';
  62848. _spanValue.appendChild( _spanValueText );
  62849. _dom.appendChild( _spanId );
  62850. _dom.appendChild( _spanValue );
  62851. if ( group ) group.div.appendChild( _dom );
  62852. else _div.appendChild( _dom );
  62853. _time = performance.now();
  62854. function _average ( v ) {
  62855. if ( _def && _def.average ) {
  62856. _accumValue += v;
  62857. _accumSamples++;
  62858. var t = performance.now();
  62859. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  62860. _averageValue = _accumValue / _accumSamples;
  62861. _accumValue = 0;
  62862. _accumStart = t;
  62863. _accumSamples = 0;
  62864. }
  62865. }
  62866. }
  62867. function _start () {
  62868. _time = performance.now();
  62869. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  62870. _started = true;
  62871. }
  62872. function _end () {
  62873. _value = performance.now() - _time;
  62874. if( _settings.userTimingAPI ) {
  62875. performance.mark( _id + '-end' );
  62876. if( _started ) {
  62877. performance.measure( _id, _id + '-start', _id + '-end' );
  62878. }
  62879. }
  62880. _average( _value );
  62881. }
  62882. function _tick () {
  62883. _end();
  62884. _start();
  62885. }
  62886. function _draw () {
  62887. var v = ( _def && _def.average ) ? _averageValue : _value;
  62888. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  62889. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  62890. _graph.draw( _value, a );
  62891. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  62892. }
  62893. function _frame () {
  62894. var t = performance.now();
  62895. var e = t - _time;
  62896. _total++;
  62897. if ( e > 1000 ) {
  62898. if ( _def && _def.interpolate === false ) {
  62899. _value = _total;
  62900. } else {
  62901. _value = _total * 1000 / e;
  62902. }
  62903. _total = 0;
  62904. _time = t;
  62905. _average( _value );
  62906. }
  62907. }
  62908. function _set ( v ) {
  62909. _value = v;
  62910. _average( _value );
  62911. }
  62912. return {
  62913. set: _set,
  62914. start: _start,
  62915. tick: _tick,
  62916. end: _end,
  62917. frame: _frame,
  62918. value: function () {
  62919. return _value;
  62920. },
  62921. draw: _draw
  62922. };
  62923. }
  62924. function sample () {
  62925. var _value = 0;
  62926. function _set ( v ) {
  62927. _value = v;
  62928. }
  62929. return {
  62930. set: _set,
  62931. value: function () {
  62932. return _value;
  62933. }
  62934. };
  62935. }
  62936. function _perf ( idArg ) {
  62937. var id = idArg.toLowerCase();
  62938. if ( id === undefined ) id = 'default';
  62939. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  62940. var group = null;
  62941. if ( _settings && _settings.groups ) {
  62942. iterateKeys( _settings.groups, function ( j ) {
  62943. var g = _settings.groups[ parseInt( j, 10 ) ];
  62944. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  62945. group = g;
  62946. }
  62947. } );
  62948. }
  62949. var p = new PerfCounter( id, group );
  62950. _perfCounters[ id ] = p;
  62951. return p;
  62952. }
  62953. function _init () {
  62954. if ( _settings.plugins ) {
  62955. if ( !_settings.values ) _settings.values = {};
  62956. if ( !_settings.groups ) _settings.groups = [];
  62957. if ( !_settings.fractions ) _settings.fractions = [];
  62958. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  62959. _settings.plugins[ j ].attach( _perf );
  62960. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  62961. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  62962. } );
  62963. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  62964. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  62965. }
  62966. } else {
  62967. _settings.plugins = {};
  62968. }
  62969. _base = document.createElement( 'div' );
  62970. _base.className = 'rs-base';
  62971. _div = document.createElement( 'div' );
  62972. _div.className = 'rs-container';
  62973. _div.style.height = 'auto';
  62974. _base.appendChild( _div );
  62975. document.body.appendChild( _base );
  62976. if ( !_settings ) return;
  62977. if ( _settings.groups ) {
  62978. iterateKeys( _settings.groups, function ( j ) {
  62979. var g = _settings.groups[ parseInt( j, 10 ) ];
  62980. var div = document.createElement( 'div' );
  62981. div.className = 'rs-group';
  62982. g.div = div;
  62983. var h1 = document.createElement( 'h1' );
  62984. h1.textContent = g.caption;
  62985. h1.addEventListener( 'click', function ( e ) {
  62986. this.classList.toggle( 'hidden' );
  62987. e.preventDefault();
  62988. }.bind( div ) );
  62989. _div.appendChild( h1 );
  62990. _div.appendChild( div );
  62991. } );
  62992. }
  62993. if ( _settings.fractions ) {
  62994. iterateKeys( _settings.fractions, function ( j ) {
  62995. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62996. var div = document.createElement( 'div' );
  62997. div.className = 'rs-fraction';
  62998. var legend = document.createElement( 'div' );
  62999. legend.className = 'rs-legend';
  63000. var h = 0;
  63001. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  63002. var p = document.createElement( 'p' );
  63003. p.textContent = _settings.fractions[ j ].steps[ k ];
  63004. p.style.color = _colours[ h ];
  63005. legend.appendChild( p );
  63006. h++;
  63007. } );
  63008. div.appendChild( legend );
  63009. div.style.height = h * _elHeight + 'px';
  63010. f.div = div;
  63011. var graph = new StackGraph( div, h );
  63012. f.graph = graph;
  63013. _div.appendChild( div );
  63014. } );
  63015. }
  63016. }
  63017. function _update () {
  63018. iterateKeys( _settings.plugins, function ( j ) {
  63019. _settings.plugins[ j ].update();
  63020. } );
  63021. iterateKeys( _perfCounters, function ( j ) {
  63022. _perfCounters[ j ].draw();
  63023. } );
  63024. if ( _settings && _settings.fractions ) {
  63025. iterateKeys( _settings.fractions, function ( j ) {
  63026. var f = _settings.fractions[ parseInt( j, 10 ) ];
  63027. var v = [];
  63028. var base = _perfCounters[ f.base.toLowerCase() ];
  63029. if ( base ) {
  63030. base = base.value();
  63031. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  63032. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  63033. var val = _perfCounters[ s ];
  63034. if ( val ) {
  63035. v.push( val.value() / base );
  63036. }
  63037. } );
  63038. }
  63039. f.graph.draw( v );
  63040. } );
  63041. }
  63042. /*if( _height != _div.clientHeight ) {
  63043. _height = _div.clientHeight;
  63044. _base.style.height = _height + 2 * _elHeight + 'px';
  63045. console.log( _base.clientHeight );
  63046. }*/
  63047. }
  63048. _init();
  63049. return function ( id ) {
  63050. if ( id ) return _perf( id );
  63051. return {
  63052. element: _base,
  63053. update: _update
  63054. };
  63055. };
  63056. }
  63057. if (typeof module === 'object') {
  63058. module.exports = window.rStats;
  63059. }
  63060. },{}],219:[function(_dereq_,module,exports){
  63061. // https://stackoverflow.com/a/36213464
  63062. if (!String.prototype.startsWith) {
  63063. String.prototype.startsWith = function(searchString, position){
  63064. position = position || 0;
  63065. return this.substr(position, searchString.length) === searchString;
  63066. };
  63067. }
  63068. },{}],220:[function(_dereq_,module,exports){
  63069. /*
  63070. * Copyright 2015 Google Inc. All Rights Reserved.
  63071. * Licensed under the Apache License, Version 2.0 (the "License");
  63072. * you may not use this file except in compliance with the License.
  63073. * You may obtain a copy of the License at
  63074. *
  63075. * http://www.apache.org/licenses/LICENSE-2.0
  63076. *
  63077. * Unless required by applicable law or agreed to in writing, software
  63078. * distributed under the License is distributed on an "AS IS" BASIS,
  63079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63080. * See the License for the specific language governing permissions and
  63081. * limitations under the License.
  63082. */
  63083. var Util = {};
  63084. Util.base64 = function(mimeType, base64) {
  63085. return 'data:' + mimeType + ';base64,' + base64;
  63086. };
  63087. Util.isMobile = function() {
  63088. var check = false;
  63089. (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);
  63090. return check;
  63091. };
  63092. Util.isIOS = function() {
  63093. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  63094. };
  63095. Util.isIFrame = function() {
  63096. try {
  63097. return window.self !== window.top;
  63098. } catch (e) {
  63099. return true;
  63100. }
  63101. };
  63102. Util.appendQueryParameter = function(url, key, value) {
  63103. // Determine delimiter based on if the URL already GET parameters in it.
  63104. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  63105. url += delimiter + key + '=' + value;
  63106. return url;
  63107. };
  63108. // From http://goo.gl/4WX3tg
  63109. Util.getQueryParameter = function(name) {
  63110. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  63111. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  63112. results = regex.exec(location.search);
  63113. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  63114. };
  63115. Util.isLandscapeMode = function() {
  63116. return (window.orientation == 90 || window.orientation == -90);
  63117. };
  63118. module.exports = Util;
  63119. },{}],221:[function(_dereq_,module,exports){
  63120. /*
  63121. * Copyright 2015 Google Inc. All Rights Reserved.
  63122. * Licensed under the Apache License, Version 2.0 (the "License");
  63123. * you may not use this file except in compliance with the License.
  63124. * You may obtain a copy of the License at
  63125. *
  63126. * http://www.apache.org/licenses/LICENSE-2.0
  63127. *
  63128. * Unless required by applicable law or agreed to in writing, software
  63129. * distributed under the License is distributed on an "AS IS" BASIS,
  63130. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63131. * See the License for the specific language governing permissions and
  63132. * limitations under the License.
  63133. */
  63134. var Util = _dereq_('./util.js');
  63135. /**
  63136. * Android and iOS compatible wakelock implementation.
  63137. *
  63138. * Refactored thanks to dkovalev@.
  63139. */
  63140. function AndroidWakeLock() {
  63141. var video = document.createElement('video');
  63142. video.addEventListener('ended', function() {
  63143. video.play();
  63144. });
  63145. this.request = function() {
  63146. if (video.paused) {
  63147. // Base64 version of videos_src/no-sleep-60s.webm.
  63148. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  63149. video.play();
  63150. }
  63151. };
  63152. this.release = function() {
  63153. video.pause();
  63154. video.src = '';
  63155. };
  63156. }
  63157. function iOSWakeLock() {
  63158. var timer = null;
  63159. this.request = function() {
  63160. if (!timer) {
  63161. timer = setInterval(function() {
  63162. window.location.href = '/';
  63163. setTimeout(window.stop, 0);
  63164. }, 15000);
  63165. }
  63166. }
  63167. this.release = function() {
  63168. if (timer) {
  63169. clearInterval(timer);
  63170. timer = null;
  63171. }
  63172. }
  63173. }
  63174. function getWakeLock() {
  63175. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  63176. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  63177. return iOSWakeLock;
  63178. } else {
  63179. return AndroidWakeLock;
  63180. }
  63181. }
  63182. module.exports = getWakeLock();
  63183. },{"./util.js":220}]},{},[178])(178)
  63184. });
  63185. //# sourceMappingURL=aframe-master.js.map