aframe-master.js 2.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241
  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(require,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(require,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(require,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(require,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(require,module,exports){
  189. var Buffer = require('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(require,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 = require('base64-js')
  211. var ieee754 = require('ieee754')
  212. var isArray = require('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 : {},require("buffer").Buffer)
  1737. },{"base64-js":3,"buffer":6,"ieee754":29,"isarray":35}],7:[function(require,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(require,module,exports){
  1787. /**
  1788. * This is the web browser implementation of `debug()`.
  1789. *
  1790. * Expose `debug()` as the module.
  1791. */
  1792. exports = module.exports = require('./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(require,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(require,module,exports){
  2077. 'use strict';
  2078. var isObj = require('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(require,module,exports){
  2131. 'use strict';
  2132. var keys = require('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(require,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(require,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(require,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(require,module,exports){
  2373. 'use strict';
  2374. var GetIntrinsic = require('./GetIntrinsic');
  2375. var $Object = GetIntrinsic('%Object%');
  2376. var $TypeError = GetIntrinsic('%TypeError%');
  2377. var $String = GetIntrinsic('%String%');
  2378. var assertRecord = require('./helpers/assertRecord');
  2379. var $isNaN = require('./helpers/isNaN');
  2380. var $isFinite = require('./helpers/isFinite');
  2381. var sign = require('./helpers/sign');
  2382. var mod = require('./helpers/mod');
  2383. var IsCallable = require('is-callable');
  2384. var toPrimitive = require('es-to-primitive/es5');
  2385. var has = require('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(require,module,exports){
  2578. 'use strict';
  2579. var GetIntrinsic = require('../GetIntrinsic');
  2580. var $TypeError = GetIntrinsic('%TypeError%');
  2581. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  2582. var has = require('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(require,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(require,module,exports){
  2624. module.exports = Number.isNaN || function isNaN(a) {
  2625. return a !== a;
  2626. };
  2627. },{}],19:[function(require,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(require,module,exports){
  2633. module.exports = function sign(number) {
  2634. return number >= 0 ? 1 : -1;
  2635. };
  2636. },{}],21:[function(require,module,exports){
  2637. 'use strict';
  2638. var toStr = Object.prototype.toString;
  2639. var isPrimitive = require('./helpers/isPrimitive');
  2640. var isCallable = require('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(require,module,exports){
  2677. module.exports = function isPrimitive(value) {
  2678. return value === null || (typeof value !== 'function' && typeof value !== 'object');
  2679. };
  2680. },{}],23:[function(require,module,exports){
  2681. /*eslint new-cap:0*/
  2682. var dtype = require('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(require,module,exports){
  2731. 'use strict';
  2732. var isCallable = require('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(require,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(require,module,exports){
  2830. 'use strict';
  2831. var implementation = require('./implementation');
  2832. module.exports = Function.prototype.bind || implementation;
  2833. },{"./implementation":25}],27:[function(require,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(require,module,exports){
  2848. 'use strict';
  2849. var bind = require('function-bind');
  2850. module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
  2851. },{"function-bind":26}],29:[function(require,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(require,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(require,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(require,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(require,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(require,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(require,module,exports){
  3027. var toString = {}.toString;
  3028. module.exports = Array.isArray || function (arr) {
  3029. return toString.call(arr) == '[object Array]';
  3030. };
  3031. },{}],36:[function(require,module,exports){
  3032. var wordWrap = require('word-wrapper')
  3033. var xtend = require('xtend')
  3034. var number = require('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":70,"xtend":73}],37:[function(require,module,exports){
  3286. (function (Buffer){
  3287. var xhr = require('xhr')
  3288. var noop = function(){}
  3289. var parseASCII = require('parse-bmfont-ascii')
  3290. var parseXML = require('parse-bmfont-xml')
  3291. var readBinary = require('parse-bmfont-binary')
  3292. var isBinaryFormat = require('./lib/is-binary')
  3293. var xtend = require('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,require("buffer").Buffer)
  3371. },{"./lib/is-binary":38,"buffer":6,"parse-bmfont-ascii":43,"parse-bmfont-binary":44,"parse-bmfont-xml":45,"xhr":71,"xtend":73}],38:[function(require,module,exports){
  3372. (function (Buffer){
  3373. var equal = require('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,require("buffer").Buffer)
  3381. },{"buffer":6,"buffer-equal":5}],39:[function(require,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(require,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 = require('./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(require,module,exports){
  3575. 'use strict';
  3576. var slice = Array.prototype.slice;
  3577. var isArgs = require('./isArguments');
  3578. var origKeys = Object.keys;
  3579. var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./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(require,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(require,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(require,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(require,module,exports){
  3853. var parseAttributes = require('./parse-attribs')
  3854. var parseFromString = require('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":72}],46:[function(require,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(require,module,exports){
  3956. var trim = require('string.prototype.trim')
  3957. , forEach = require('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(require,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(require,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(require,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,require("timers").setImmediate)
  4350. },{"timers":68}],51:[function(require,module,exports){
  4351. var dtype = require('dtype')
  4352. var anArray = require('an-array')
  4353. var isBuffer = require('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(require,module,exports){
  4387. 'use strict';
  4388. var bind = require('function-bind');
  4389. var ES = require('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(require,module,exports){
  4400. 'use strict';
  4401. var bind = require('function-bind');
  4402. var define = require('define-properties');
  4403. var implementation = require('./implementation');
  4404. var getPolyfill = require('./polyfill');
  4405. var shim = require('./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(require,module,exports){
  4414. 'use strict';
  4415. var implementation = require('./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(require,module,exports){
  4424. 'use strict';
  4425. var define = require('define-properties');
  4426. var getPolyfill = require('./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(require,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(require,module,exports){
  5586. /**
  5587. * @license
  5588. * Copyright 2010-2021 Three.js Authors
  5589. * SPDX-License-Identifier: MIT
  5590. */
  5591. (function (global, factory) {
  5592. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5593. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5594. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  5595. }(this, (function (exports) { 'use strict';
  5596. const REVISION = '133';
  5597. const MOUSE = {
  5598. LEFT: 0,
  5599. MIDDLE: 1,
  5600. RIGHT: 2,
  5601. ROTATE: 0,
  5602. DOLLY: 1,
  5603. PAN: 2
  5604. };
  5605. const TOUCH = {
  5606. ROTATE: 0,
  5607. PAN: 1,
  5608. DOLLY_PAN: 2,
  5609. DOLLY_ROTATE: 3
  5610. };
  5611. const CullFaceNone = 0;
  5612. const CullFaceBack = 1;
  5613. const CullFaceFront = 2;
  5614. const CullFaceFrontBack = 3;
  5615. const BasicShadowMap = 0;
  5616. const PCFShadowMap = 1;
  5617. const PCFSoftShadowMap = 2;
  5618. const VSMShadowMap = 3;
  5619. const FrontSide = 0;
  5620. const BackSide = 1;
  5621. const DoubleSide = 2;
  5622. const FlatShading = 1;
  5623. const SmoothShading = 2;
  5624. const NoBlending = 0;
  5625. const NormalBlending = 1;
  5626. const AdditiveBlending = 2;
  5627. const SubtractiveBlending = 3;
  5628. const MultiplyBlending = 4;
  5629. const CustomBlending = 5;
  5630. const AddEquation = 100;
  5631. const SubtractEquation = 101;
  5632. const ReverseSubtractEquation = 102;
  5633. const MinEquation = 103;
  5634. const MaxEquation = 104;
  5635. const ZeroFactor = 200;
  5636. const OneFactor = 201;
  5637. const SrcColorFactor = 202;
  5638. const OneMinusSrcColorFactor = 203;
  5639. const SrcAlphaFactor = 204;
  5640. const OneMinusSrcAlphaFactor = 205;
  5641. const DstAlphaFactor = 206;
  5642. const OneMinusDstAlphaFactor = 207;
  5643. const DstColorFactor = 208;
  5644. const OneMinusDstColorFactor = 209;
  5645. const SrcAlphaSaturateFactor = 210;
  5646. const NeverDepth = 0;
  5647. const AlwaysDepth = 1;
  5648. const LessDepth = 2;
  5649. const LessEqualDepth = 3;
  5650. const EqualDepth = 4;
  5651. const GreaterEqualDepth = 5;
  5652. const GreaterDepth = 6;
  5653. const NotEqualDepth = 7;
  5654. const MultiplyOperation = 0;
  5655. const MixOperation = 1;
  5656. const AddOperation = 2;
  5657. const NoToneMapping = 0;
  5658. const LinearToneMapping = 1;
  5659. const ReinhardToneMapping = 2;
  5660. const CineonToneMapping = 3;
  5661. const ACESFilmicToneMapping = 4;
  5662. const CustomToneMapping = 5;
  5663. const UVMapping = 300;
  5664. const CubeReflectionMapping = 301;
  5665. const CubeRefractionMapping = 302;
  5666. const EquirectangularReflectionMapping = 303;
  5667. const EquirectangularRefractionMapping = 304;
  5668. const CubeUVReflectionMapping = 306;
  5669. const CubeUVRefractionMapping = 307;
  5670. const RepeatWrapping = 1000;
  5671. const ClampToEdgeWrapping = 1001;
  5672. const MirroredRepeatWrapping = 1002;
  5673. const NearestFilter = 1003;
  5674. const NearestMipmapNearestFilter = 1004;
  5675. const NearestMipMapNearestFilter = 1004;
  5676. const NearestMipmapLinearFilter = 1005;
  5677. const NearestMipMapLinearFilter = 1005;
  5678. const LinearFilter = 1006;
  5679. const LinearMipmapNearestFilter = 1007;
  5680. const LinearMipMapNearestFilter = 1007;
  5681. const LinearMipmapLinearFilter = 1008;
  5682. const LinearMipMapLinearFilter = 1008;
  5683. const UnsignedByteType = 1009;
  5684. const ByteType = 1010;
  5685. const ShortType = 1011;
  5686. const UnsignedShortType = 1012;
  5687. const IntType = 1013;
  5688. const UnsignedIntType = 1014;
  5689. const FloatType = 1015;
  5690. const HalfFloatType = 1016;
  5691. const UnsignedShort4444Type = 1017;
  5692. const UnsignedShort5551Type = 1018;
  5693. const UnsignedShort565Type = 1019;
  5694. const UnsignedInt248Type = 1020;
  5695. const AlphaFormat = 1021;
  5696. const RGBFormat = 1022;
  5697. const RGBAFormat = 1023;
  5698. const LuminanceFormat = 1024;
  5699. const LuminanceAlphaFormat = 1025;
  5700. const RGBEFormat = RGBAFormat;
  5701. const DepthFormat = 1026;
  5702. const DepthStencilFormat = 1027;
  5703. const RedFormat = 1028;
  5704. const RedIntegerFormat = 1029;
  5705. const RGFormat = 1030;
  5706. const RGIntegerFormat = 1031;
  5707. const RGBIntegerFormat = 1032;
  5708. const RGBAIntegerFormat = 1033;
  5709. const RGB_S3TC_DXT1_Format = 33776;
  5710. const RGBA_S3TC_DXT1_Format = 33777;
  5711. const RGBA_S3TC_DXT3_Format = 33778;
  5712. const RGBA_S3TC_DXT5_Format = 33779;
  5713. const RGB_PVRTC_4BPPV1_Format = 35840;
  5714. const RGB_PVRTC_2BPPV1_Format = 35841;
  5715. const RGBA_PVRTC_4BPPV1_Format = 35842;
  5716. const RGBA_PVRTC_2BPPV1_Format = 35843;
  5717. const RGB_ETC1_Format = 36196;
  5718. const RGB_ETC2_Format = 37492;
  5719. const RGBA_ETC2_EAC_Format = 37496;
  5720. const RGBA_ASTC_4x4_Format = 37808;
  5721. const RGBA_ASTC_5x4_Format = 37809;
  5722. const RGBA_ASTC_5x5_Format = 37810;
  5723. const RGBA_ASTC_6x5_Format = 37811;
  5724. const RGBA_ASTC_6x6_Format = 37812;
  5725. const RGBA_ASTC_8x5_Format = 37813;
  5726. const RGBA_ASTC_8x6_Format = 37814;
  5727. const RGBA_ASTC_8x8_Format = 37815;
  5728. const RGBA_ASTC_10x5_Format = 37816;
  5729. const RGBA_ASTC_10x6_Format = 37817;
  5730. const RGBA_ASTC_10x8_Format = 37818;
  5731. const RGBA_ASTC_10x10_Format = 37819;
  5732. const RGBA_ASTC_12x10_Format = 37820;
  5733. const RGBA_ASTC_12x12_Format = 37821;
  5734. const RGBA_BPTC_Format = 36492;
  5735. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  5736. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  5737. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  5738. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  5739. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  5740. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  5741. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  5742. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  5743. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  5744. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  5745. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  5746. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  5747. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  5748. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  5749. const LoopOnce = 2200;
  5750. const LoopRepeat = 2201;
  5751. const LoopPingPong = 2202;
  5752. const InterpolateDiscrete = 2300;
  5753. const InterpolateLinear = 2301;
  5754. const InterpolateSmooth = 2302;
  5755. const ZeroCurvatureEnding = 2400;
  5756. const ZeroSlopeEnding = 2401;
  5757. const WrapAroundEnding = 2402;
  5758. const NormalAnimationBlendMode = 2500;
  5759. const AdditiveAnimationBlendMode = 2501;
  5760. const TrianglesDrawMode = 0;
  5761. const TriangleStripDrawMode = 1;
  5762. const TriangleFanDrawMode = 2;
  5763. const LinearEncoding = 3000;
  5764. const sRGBEncoding = 3001;
  5765. const GammaEncoding = 3007;
  5766. const RGBEEncoding = 3002;
  5767. const LogLuvEncoding = 3003;
  5768. const RGBM7Encoding = 3004;
  5769. const RGBM16Encoding = 3005;
  5770. const RGBDEncoding = 3006;
  5771. const BasicDepthPacking = 3200;
  5772. const RGBADepthPacking = 3201;
  5773. const TangentSpaceNormalMap = 0;
  5774. const ObjectSpaceNormalMap = 1;
  5775. const ZeroStencilOp = 0;
  5776. const KeepStencilOp = 7680;
  5777. const ReplaceStencilOp = 7681;
  5778. const IncrementStencilOp = 7682;
  5779. const DecrementStencilOp = 7683;
  5780. const IncrementWrapStencilOp = 34055;
  5781. const DecrementWrapStencilOp = 34056;
  5782. const InvertStencilOp = 5386;
  5783. const NeverStencilFunc = 512;
  5784. const LessStencilFunc = 513;
  5785. const EqualStencilFunc = 514;
  5786. const LessEqualStencilFunc = 515;
  5787. const GreaterStencilFunc = 516;
  5788. const NotEqualStencilFunc = 517;
  5789. const GreaterEqualStencilFunc = 518;
  5790. const AlwaysStencilFunc = 519;
  5791. const StaticDrawUsage = 35044;
  5792. const DynamicDrawUsage = 35048;
  5793. const StreamDrawUsage = 35040;
  5794. const StaticReadUsage = 35045;
  5795. const DynamicReadUsage = 35049;
  5796. const StreamReadUsage = 35041;
  5797. const StaticCopyUsage = 35046;
  5798. const DynamicCopyUsage = 35050;
  5799. const StreamCopyUsage = 35042;
  5800. const GLSL1 = '100';
  5801. const GLSL3 = '300 es';
  5802. /**
  5803. * https://github.com/mrdoob/eventdispatcher.js/
  5804. */
  5805. class EventDispatcher {
  5806. addEventListener(type, listener) {
  5807. if (this._listeners === undefined) this._listeners = {};
  5808. const listeners = this._listeners;
  5809. if (listeners[type] === undefined) {
  5810. listeners[type] = [];
  5811. }
  5812. if (listeners[type].indexOf(listener) === -1) {
  5813. listeners[type].push(listener);
  5814. }
  5815. }
  5816. hasEventListener(type, listener) {
  5817. if (this._listeners === undefined) return false;
  5818. const listeners = this._listeners;
  5819. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  5820. }
  5821. removeEventListener(type, listener) {
  5822. if (this._listeners === undefined) return;
  5823. const listeners = this._listeners;
  5824. const listenerArray = listeners[type];
  5825. if (listenerArray !== undefined) {
  5826. const index = listenerArray.indexOf(listener);
  5827. if (index !== -1) {
  5828. listenerArray.splice(index, 1);
  5829. }
  5830. }
  5831. }
  5832. dispatchEvent(event) {
  5833. if (this._listeners === undefined) return;
  5834. const listeners = this._listeners;
  5835. const listenerArray = listeners[event.type];
  5836. if (listenerArray !== undefined) {
  5837. event.target = this; // Make a copy, in case listeners are removed while iterating.
  5838. const array = listenerArray.slice(0);
  5839. for (let i = 0, l = array.length; i < l; i++) {
  5840. array[i].call(this, event);
  5841. }
  5842. event.target = null;
  5843. }
  5844. }
  5845. }
  5846. let _seed = 1234567;
  5847. const DEG2RAD = Math.PI / 180;
  5848. const RAD2DEG = 180 / Math.PI; //
  5849. const _lut = [];
  5850. for (let i = 0; i < 256; i++) {
  5851. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  5852. }
  5853. const hasRandomUUID = typeof crypto !== 'undefined' && 'randomUUID' in crypto;
  5854. function generateUUID() {
  5855. if (hasRandomUUID) {
  5856. return crypto.randomUUID().toUpperCase();
  5857. } // TODO Remove this code when crypto.randomUUID() is available everywhere
  5858. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  5859. const d0 = Math.random() * 0xffffffff | 0;
  5860. const d1 = Math.random() * 0xffffffff | 0;
  5861. const d2 = Math.random() * 0xffffffff | 0;
  5862. const d3 = Math.random() * 0xffffffff | 0;
  5863. const 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.
  5864. return uuid.toUpperCase();
  5865. }
  5866. function clamp(value, min, max) {
  5867. return Math.max(min, Math.min(max, value));
  5868. } // compute euclidian modulo of m % n
  5869. // https://en.wikipedia.org/wiki/Modulo_operation
  5870. function euclideanModulo(n, m) {
  5871. return (n % m + m) % m;
  5872. } // Linear mapping from range <a1, a2> to range <b1, b2>
  5873. function mapLinear(x, a1, a2, b1, b2) {
  5874. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  5875. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  5876. function inverseLerp(x, y, value) {
  5877. if (x !== y) {
  5878. return (value - x) / (y - x);
  5879. } else {
  5880. return 0;
  5881. }
  5882. } // https://en.wikipedia.org/wiki/Linear_interpolation
  5883. function lerp(x, y, t) {
  5884. return (1 - t) * x + t * y;
  5885. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  5886. function damp(x, y, lambda, dt) {
  5887. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  5888. } // https://www.desmos.com/calculator/vcsjnyz7x4
  5889. function pingpong(x, length = 1) {
  5890. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  5891. } // http://en.wikipedia.org/wiki/Smoothstep
  5892. function smoothstep(x, min, max) {
  5893. if (x <= min) return 0;
  5894. if (x >= max) return 1;
  5895. x = (x - min) / (max - min);
  5896. return x * x * (3 - 2 * x);
  5897. }
  5898. function smootherstep(x, min, max) {
  5899. if (x <= min) return 0;
  5900. if (x >= max) return 1;
  5901. x = (x - min) / (max - min);
  5902. return x * x * x * (x * (x * 6 - 15) + 10);
  5903. } // Random integer from <low, high> interval
  5904. function randInt(low, high) {
  5905. return low + Math.floor(Math.random() * (high - low + 1));
  5906. } // Random float from <low, high> interval
  5907. function randFloat(low, high) {
  5908. return low + Math.random() * (high - low);
  5909. } // Random float from <-range/2, range/2> interval
  5910. function randFloatSpread(range) {
  5911. return range * (0.5 - Math.random());
  5912. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  5913. function seededRandom(s) {
  5914. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  5915. _seed = _seed * 16807 % 2147483647;
  5916. return (_seed - 1) / 2147483646;
  5917. }
  5918. function degToRad(degrees) {
  5919. return degrees * DEG2RAD;
  5920. }
  5921. function radToDeg(radians) {
  5922. return radians * RAD2DEG;
  5923. }
  5924. function isPowerOfTwo(value) {
  5925. return (value & value - 1) === 0 && value !== 0;
  5926. }
  5927. function ceilPowerOfTwo(value) {
  5928. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  5929. }
  5930. function floorPowerOfTwo(value) {
  5931. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  5932. }
  5933. function setQuaternionFromProperEuler(q, a, b, c, order) {
  5934. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  5935. // rotations are applied to the axes in the order specified by 'order'
  5936. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  5937. // angles are in radians
  5938. const cos = Math.cos;
  5939. const sin = Math.sin;
  5940. const c2 = cos(b / 2);
  5941. const s2 = sin(b / 2);
  5942. const c13 = cos((a + c) / 2);
  5943. const s13 = sin((a + c) / 2);
  5944. const c1_3 = cos((a - c) / 2);
  5945. const s1_3 = sin((a - c) / 2);
  5946. const c3_1 = cos((c - a) / 2);
  5947. const s3_1 = sin((c - a) / 2);
  5948. switch (order) {
  5949. case 'XYX':
  5950. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  5951. break;
  5952. case 'YZY':
  5953. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  5954. break;
  5955. case 'ZXZ':
  5956. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  5957. break;
  5958. case 'XZX':
  5959. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  5960. break;
  5961. case 'YXY':
  5962. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  5963. break;
  5964. case 'ZYZ':
  5965. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  5966. break;
  5967. default:
  5968. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  5969. }
  5970. }
  5971. var MathUtils = /*#__PURE__*/Object.freeze({
  5972. __proto__: null,
  5973. DEG2RAD: DEG2RAD,
  5974. RAD2DEG: RAD2DEG,
  5975. generateUUID: generateUUID,
  5976. clamp: clamp,
  5977. euclideanModulo: euclideanModulo,
  5978. mapLinear: mapLinear,
  5979. inverseLerp: inverseLerp,
  5980. lerp: lerp,
  5981. damp: damp,
  5982. pingpong: pingpong,
  5983. smoothstep: smoothstep,
  5984. smootherstep: smootherstep,
  5985. randInt: randInt,
  5986. randFloat: randFloat,
  5987. randFloatSpread: randFloatSpread,
  5988. seededRandom: seededRandom,
  5989. degToRad: degToRad,
  5990. radToDeg: radToDeg,
  5991. isPowerOfTwo: isPowerOfTwo,
  5992. ceilPowerOfTwo: ceilPowerOfTwo,
  5993. floorPowerOfTwo: floorPowerOfTwo,
  5994. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  5995. });
  5996. class Vector2 {
  5997. constructor(x = 0, y = 0) {
  5998. this.x = x;
  5999. this.y = y;
  6000. }
  6001. get width() {
  6002. return this.x;
  6003. }
  6004. set width(value) {
  6005. this.x = value;
  6006. }
  6007. get height() {
  6008. return this.y;
  6009. }
  6010. set height(value) {
  6011. this.y = value;
  6012. }
  6013. set(x, y) {
  6014. this.x = x;
  6015. this.y = y;
  6016. return this;
  6017. }
  6018. setScalar(scalar) {
  6019. this.x = scalar;
  6020. this.y = scalar;
  6021. return this;
  6022. }
  6023. setX(x) {
  6024. this.x = x;
  6025. return this;
  6026. }
  6027. setY(y) {
  6028. this.y = y;
  6029. return this;
  6030. }
  6031. setComponent(index, value) {
  6032. switch (index) {
  6033. case 0:
  6034. this.x = value;
  6035. break;
  6036. case 1:
  6037. this.y = value;
  6038. break;
  6039. default:
  6040. throw new Error('index is out of range: ' + index);
  6041. }
  6042. return this;
  6043. }
  6044. getComponent(index) {
  6045. switch (index) {
  6046. case 0:
  6047. return this.x;
  6048. case 1:
  6049. return this.y;
  6050. default:
  6051. throw new Error('index is out of range: ' + index);
  6052. }
  6053. }
  6054. clone() {
  6055. return new this.constructor(this.x, this.y);
  6056. }
  6057. copy(v) {
  6058. this.x = v.x;
  6059. this.y = v.y;
  6060. return this;
  6061. }
  6062. add(v, w) {
  6063. if (w !== undefined) {
  6064. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6065. return this.addVectors(v, w);
  6066. }
  6067. this.x += v.x;
  6068. this.y += v.y;
  6069. return this;
  6070. }
  6071. addScalar(s) {
  6072. this.x += s;
  6073. this.y += s;
  6074. return this;
  6075. }
  6076. addVectors(a, b) {
  6077. this.x = a.x + b.x;
  6078. this.y = a.y + b.y;
  6079. return this;
  6080. }
  6081. addScaledVector(v, s) {
  6082. this.x += v.x * s;
  6083. this.y += v.y * s;
  6084. return this;
  6085. }
  6086. sub(v, w) {
  6087. if (w !== undefined) {
  6088. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6089. return this.subVectors(v, w);
  6090. }
  6091. this.x -= v.x;
  6092. this.y -= v.y;
  6093. return this;
  6094. }
  6095. subScalar(s) {
  6096. this.x -= s;
  6097. this.y -= s;
  6098. return this;
  6099. }
  6100. subVectors(a, b) {
  6101. this.x = a.x - b.x;
  6102. this.y = a.y - b.y;
  6103. return this;
  6104. }
  6105. multiply(v) {
  6106. this.x *= v.x;
  6107. this.y *= v.y;
  6108. return this;
  6109. }
  6110. multiplyScalar(scalar) {
  6111. this.x *= scalar;
  6112. this.y *= scalar;
  6113. return this;
  6114. }
  6115. divide(v) {
  6116. this.x /= v.x;
  6117. this.y /= v.y;
  6118. return this;
  6119. }
  6120. divideScalar(scalar) {
  6121. return this.multiplyScalar(1 / scalar);
  6122. }
  6123. applyMatrix3(m) {
  6124. const x = this.x,
  6125. y = this.y;
  6126. const e = m.elements;
  6127. this.x = e[0] * x + e[3] * y + e[6];
  6128. this.y = e[1] * x + e[4] * y + e[7];
  6129. return this;
  6130. }
  6131. min(v) {
  6132. this.x = Math.min(this.x, v.x);
  6133. this.y = Math.min(this.y, v.y);
  6134. return this;
  6135. }
  6136. max(v) {
  6137. this.x = Math.max(this.x, v.x);
  6138. this.y = Math.max(this.y, v.y);
  6139. return this;
  6140. }
  6141. clamp(min, max) {
  6142. // assumes min < max, componentwise
  6143. this.x = Math.max(min.x, Math.min(max.x, this.x));
  6144. this.y = Math.max(min.y, Math.min(max.y, this.y));
  6145. return this;
  6146. }
  6147. clampScalar(minVal, maxVal) {
  6148. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  6149. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  6150. return this;
  6151. }
  6152. clampLength(min, max) {
  6153. const length = this.length();
  6154. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  6155. }
  6156. floor() {
  6157. this.x = Math.floor(this.x);
  6158. this.y = Math.floor(this.y);
  6159. return this;
  6160. }
  6161. ceil() {
  6162. this.x = Math.ceil(this.x);
  6163. this.y = Math.ceil(this.y);
  6164. return this;
  6165. }
  6166. round() {
  6167. this.x = Math.round(this.x);
  6168. this.y = Math.round(this.y);
  6169. return this;
  6170. }
  6171. roundToZero() {
  6172. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  6173. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  6174. return this;
  6175. }
  6176. negate() {
  6177. this.x = -this.x;
  6178. this.y = -this.y;
  6179. return this;
  6180. }
  6181. dot(v) {
  6182. return this.x * v.x + this.y * v.y;
  6183. }
  6184. cross(v) {
  6185. return this.x * v.y - this.y * v.x;
  6186. }
  6187. lengthSq() {
  6188. return this.x * this.x + this.y * this.y;
  6189. }
  6190. length() {
  6191. return Math.sqrt(this.x * this.x + this.y * this.y);
  6192. }
  6193. manhattanLength() {
  6194. return Math.abs(this.x) + Math.abs(this.y);
  6195. }
  6196. normalize() {
  6197. return this.divideScalar(this.length() || 1);
  6198. }
  6199. angle() {
  6200. // computes the angle in radians with respect to the positive x-axis
  6201. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  6202. return angle;
  6203. }
  6204. distanceTo(v) {
  6205. return Math.sqrt(this.distanceToSquared(v));
  6206. }
  6207. distanceToSquared(v) {
  6208. const dx = this.x - v.x,
  6209. dy = this.y - v.y;
  6210. return dx * dx + dy * dy;
  6211. }
  6212. manhattanDistanceTo(v) {
  6213. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  6214. }
  6215. setLength(length) {
  6216. return this.normalize().multiplyScalar(length);
  6217. }
  6218. lerp(v, alpha) {
  6219. this.x += (v.x - this.x) * alpha;
  6220. this.y += (v.y - this.y) * alpha;
  6221. return this;
  6222. }
  6223. lerpVectors(v1, v2, alpha) {
  6224. this.x = v1.x + (v2.x - v1.x) * alpha;
  6225. this.y = v1.y + (v2.y - v1.y) * alpha;
  6226. return this;
  6227. }
  6228. equals(v) {
  6229. return v.x === this.x && v.y === this.y;
  6230. }
  6231. fromArray(array, offset = 0) {
  6232. this.x = array[offset];
  6233. this.y = array[offset + 1];
  6234. return this;
  6235. }
  6236. toArray(array = [], offset = 0) {
  6237. array[offset] = this.x;
  6238. array[offset + 1] = this.y;
  6239. return array;
  6240. }
  6241. fromBufferAttribute(attribute, index, offset) {
  6242. if (offset !== undefined) {
  6243. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  6244. }
  6245. this.x = attribute.getX(index);
  6246. this.y = attribute.getY(index);
  6247. return this;
  6248. }
  6249. rotateAround(center, angle) {
  6250. const c = Math.cos(angle),
  6251. s = Math.sin(angle);
  6252. const x = this.x - center.x;
  6253. const y = this.y - center.y;
  6254. this.x = x * c - y * s + center.x;
  6255. this.y = x * s + y * c + center.y;
  6256. return this;
  6257. }
  6258. random() {
  6259. this.x = Math.random();
  6260. this.y = Math.random();
  6261. return this;
  6262. }
  6263. *[Symbol.iterator]() {
  6264. yield this.x;
  6265. yield this.y;
  6266. }
  6267. }
  6268. Vector2.prototype.isVector2 = true;
  6269. class Matrix3 {
  6270. constructor() {
  6271. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  6272. if (arguments.length > 0) {
  6273. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  6274. }
  6275. }
  6276. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  6277. const te = this.elements;
  6278. te[0] = n11;
  6279. te[1] = n21;
  6280. te[2] = n31;
  6281. te[3] = n12;
  6282. te[4] = n22;
  6283. te[5] = n32;
  6284. te[6] = n13;
  6285. te[7] = n23;
  6286. te[8] = n33;
  6287. return this;
  6288. }
  6289. identity() {
  6290. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  6291. return this;
  6292. }
  6293. copy(m) {
  6294. const te = this.elements;
  6295. const me = m.elements;
  6296. te[0] = me[0];
  6297. te[1] = me[1];
  6298. te[2] = me[2];
  6299. te[3] = me[3];
  6300. te[4] = me[4];
  6301. te[5] = me[5];
  6302. te[6] = me[6];
  6303. te[7] = me[7];
  6304. te[8] = me[8];
  6305. return this;
  6306. }
  6307. extractBasis(xAxis, yAxis, zAxis) {
  6308. xAxis.setFromMatrix3Column(this, 0);
  6309. yAxis.setFromMatrix3Column(this, 1);
  6310. zAxis.setFromMatrix3Column(this, 2);
  6311. return this;
  6312. }
  6313. setFromMatrix4(m) {
  6314. const me = m.elements;
  6315. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  6316. return this;
  6317. }
  6318. multiply(m) {
  6319. return this.multiplyMatrices(this, m);
  6320. }
  6321. premultiply(m) {
  6322. return this.multiplyMatrices(m, this);
  6323. }
  6324. multiplyMatrices(a, b) {
  6325. const ae = a.elements;
  6326. const be = b.elements;
  6327. const te = this.elements;
  6328. const a11 = ae[0],
  6329. a12 = ae[3],
  6330. a13 = ae[6];
  6331. const a21 = ae[1],
  6332. a22 = ae[4],
  6333. a23 = ae[7];
  6334. const a31 = ae[2],
  6335. a32 = ae[5],
  6336. a33 = ae[8];
  6337. const b11 = be[0],
  6338. b12 = be[3],
  6339. b13 = be[6];
  6340. const b21 = be[1],
  6341. b22 = be[4],
  6342. b23 = be[7];
  6343. const b31 = be[2],
  6344. b32 = be[5],
  6345. b33 = be[8];
  6346. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  6347. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  6348. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  6349. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  6350. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  6351. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  6352. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  6353. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  6354. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  6355. return this;
  6356. }
  6357. multiplyScalar(s) {
  6358. const te = this.elements;
  6359. te[0] *= s;
  6360. te[3] *= s;
  6361. te[6] *= s;
  6362. te[1] *= s;
  6363. te[4] *= s;
  6364. te[7] *= s;
  6365. te[2] *= s;
  6366. te[5] *= s;
  6367. te[8] *= s;
  6368. return this;
  6369. }
  6370. determinant() {
  6371. const te = this.elements;
  6372. const a = te[0],
  6373. b = te[1],
  6374. c = te[2],
  6375. d = te[3],
  6376. e = te[4],
  6377. f = te[5],
  6378. g = te[6],
  6379. h = te[7],
  6380. i = te[8];
  6381. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6382. }
  6383. invert() {
  6384. const te = this.elements,
  6385. n11 = te[0],
  6386. n21 = te[1],
  6387. n31 = te[2],
  6388. n12 = te[3],
  6389. n22 = te[4],
  6390. n32 = te[5],
  6391. n13 = te[6],
  6392. n23 = te[7],
  6393. n33 = te[8],
  6394. t11 = n33 * n22 - n32 * n23,
  6395. t12 = n32 * n13 - n33 * n12,
  6396. t13 = n23 * n12 - n22 * n13,
  6397. det = n11 * t11 + n21 * t12 + n31 * t13;
  6398. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  6399. const detInv = 1 / det;
  6400. te[0] = t11 * detInv;
  6401. te[1] = (n31 * n23 - n33 * n21) * detInv;
  6402. te[2] = (n32 * n21 - n31 * n22) * detInv;
  6403. te[3] = t12 * detInv;
  6404. te[4] = (n33 * n11 - n31 * n13) * detInv;
  6405. te[5] = (n31 * n12 - n32 * n11) * detInv;
  6406. te[6] = t13 * detInv;
  6407. te[7] = (n21 * n13 - n23 * n11) * detInv;
  6408. te[8] = (n22 * n11 - n21 * n12) * detInv;
  6409. return this;
  6410. }
  6411. transpose() {
  6412. let tmp;
  6413. const m = this.elements;
  6414. tmp = m[1];
  6415. m[1] = m[3];
  6416. m[3] = tmp;
  6417. tmp = m[2];
  6418. m[2] = m[6];
  6419. m[6] = tmp;
  6420. tmp = m[5];
  6421. m[5] = m[7];
  6422. m[7] = tmp;
  6423. return this;
  6424. }
  6425. getNormalMatrix(matrix4) {
  6426. return this.setFromMatrix4(matrix4).invert().transpose();
  6427. }
  6428. transposeIntoArray(r) {
  6429. const m = this.elements;
  6430. r[0] = m[0];
  6431. r[1] = m[3];
  6432. r[2] = m[6];
  6433. r[3] = m[1];
  6434. r[4] = m[4];
  6435. r[5] = m[7];
  6436. r[6] = m[2];
  6437. r[7] = m[5];
  6438. r[8] = m[8];
  6439. return this;
  6440. }
  6441. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  6442. const c = Math.cos(rotation);
  6443. const s = Math.sin(rotation);
  6444. 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);
  6445. return this;
  6446. }
  6447. scale(sx, sy) {
  6448. const te = this.elements;
  6449. te[0] *= sx;
  6450. te[3] *= sx;
  6451. te[6] *= sx;
  6452. te[1] *= sy;
  6453. te[4] *= sy;
  6454. te[7] *= sy;
  6455. return this;
  6456. }
  6457. rotate(theta) {
  6458. const c = Math.cos(theta);
  6459. const s = Math.sin(theta);
  6460. const te = this.elements;
  6461. const a11 = te[0],
  6462. a12 = te[3],
  6463. a13 = te[6];
  6464. const a21 = te[1],
  6465. a22 = te[4],
  6466. a23 = te[7];
  6467. te[0] = c * a11 + s * a21;
  6468. te[3] = c * a12 + s * a22;
  6469. te[6] = c * a13 + s * a23;
  6470. te[1] = -s * a11 + c * a21;
  6471. te[4] = -s * a12 + c * a22;
  6472. te[7] = -s * a13 + c * a23;
  6473. return this;
  6474. }
  6475. translate(tx, ty) {
  6476. const te = this.elements;
  6477. te[0] += tx * te[2];
  6478. te[3] += tx * te[5];
  6479. te[6] += tx * te[8];
  6480. te[1] += ty * te[2];
  6481. te[4] += ty * te[5];
  6482. te[7] += ty * te[8];
  6483. return this;
  6484. }
  6485. equals(matrix) {
  6486. const te = this.elements;
  6487. const me = matrix.elements;
  6488. for (let i = 0; i < 9; i++) {
  6489. if (te[i] !== me[i]) return false;
  6490. }
  6491. return true;
  6492. }
  6493. fromArray(array, offset = 0) {
  6494. for (let i = 0; i < 9; i++) {
  6495. this.elements[i] = array[i + offset];
  6496. }
  6497. return this;
  6498. }
  6499. toArray(array = [], offset = 0) {
  6500. const te = this.elements;
  6501. array[offset] = te[0];
  6502. array[offset + 1] = te[1];
  6503. array[offset + 2] = te[2];
  6504. array[offset + 3] = te[3];
  6505. array[offset + 4] = te[4];
  6506. array[offset + 5] = te[5];
  6507. array[offset + 6] = te[6];
  6508. array[offset + 7] = te[7];
  6509. array[offset + 8] = te[8];
  6510. return array;
  6511. }
  6512. clone() {
  6513. return new this.constructor().fromArray(this.elements);
  6514. }
  6515. }
  6516. Matrix3.prototype.isMatrix3 = true;
  6517. function arrayMax(array) {
  6518. if (array.length === 0) return -Infinity;
  6519. let max = array[0];
  6520. for (let i = 1, l = array.length; i < l; ++i) {
  6521. if (array[i] > max) max = array[i];
  6522. }
  6523. return max;
  6524. }
  6525. const TYPED_ARRAYS = {
  6526. Int8Array: Int8Array,
  6527. Uint8Array: Uint8Array,
  6528. Uint8ClampedArray: Uint8ClampedArray,
  6529. Int16Array: Int16Array,
  6530. Uint16Array: Uint16Array,
  6531. Int32Array: Int32Array,
  6532. Uint32Array: Uint32Array,
  6533. Float32Array: Float32Array,
  6534. Float64Array: Float64Array
  6535. };
  6536. function getTypedArray(type, buffer) {
  6537. return new TYPED_ARRAYS[type](buffer);
  6538. }
  6539. function createElementNS(name) {
  6540. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  6541. }
  6542. let _canvas;
  6543. class ImageUtils {
  6544. static getDataURL(image) {
  6545. if (/^data:/i.test(image.src)) {
  6546. return image.src;
  6547. }
  6548. if (typeof HTMLCanvasElement == 'undefined') {
  6549. return image.src;
  6550. }
  6551. let canvas;
  6552. if (image instanceof HTMLCanvasElement) {
  6553. canvas = image;
  6554. } else {
  6555. if (_canvas === undefined) _canvas = createElementNS('canvas');
  6556. _canvas.width = image.width;
  6557. _canvas.height = image.height;
  6558. const context = _canvas.getContext('2d');
  6559. if (image instanceof ImageData) {
  6560. context.putImageData(image, 0, 0);
  6561. } else {
  6562. context.drawImage(image, 0, 0, image.width, image.height);
  6563. }
  6564. canvas = _canvas;
  6565. }
  6566. if (canvas.width > 2048 || canvas.height > 2048) {
  6567. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  6568. return canvas.toDataURL('image/jpeg', 0.6);
  6569. } else {
  6570. return canvas.toDataURL('image/png');
  6571. }
  6572. }
  6573. }
  6574. let textureId = 0;
  6575. class Texture extends EventDispatcher {
  6576. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  6577. super();
  6578. Object.defineProperty(this, 'id', {
  6579. value: textureId++
  6580. });
  6581. this.uuid = generateUUID();
  6582. this.name = '';
  6583. this.image = image;
  6584. this.mipmaps = [];
  6585. this.mapping = mapping;
  6586. this.wrapS = wrapS;
  6587. this.wrapT = wrapT;
  6588. this.magFilter = magFilter;
  6589. this.minFilter = minFilter;
  6590. this.anisotropy = anisotropy;
  6591. this.format = format;
  6592. this.internalFormat = null;
  6593. this.type = type;
  6594. this.offset = new Vector2(0, 0);
  6595. this.repeat = new Vector2(1, 1);
  6596. this.center = new Vector2(0, 0);
  6597. this.rotation = 0;
  6598. this.matrixAutoUpdate = true;
  6599. this.matrix = new Matrix3();
  6600. this.generateMipmaps = true;
  6601. this.premultiplyAlpha = false;
  6602. this.flipY = true;
  6603. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6604. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6605. //
  6606. // Also changing the encoding after already used by a Material will not automatically make the Material
  6607. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6608. this.encoding = encoding;
  6609. this.version = 0;
  6610. this.onUpdate = null;
  6611. this.isRenderTargetTexture = false;
  6612. }
  6613. updateMatrix() {
  6614. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  6615. }
  6616. clone() {
  6617. return new this.constructor().copy(this);
  6618. }
  6619. copy(source) {
  6620. this.name = source.name;
  6621. this.image = source.image;
  6622. this.mipmaps = source.mipmaps.slice(0);
  6623. this.mapping = source.mapping;
  6624. this.wrapS = source.wrapS;
  6625. this.wrapT = source.wrapT;
  6626. this.magFilter = source.magFilter;
  6627. this.minFilter = source.minFilter;
  6628. this.anisotropy = source.anisotropy;
  6629. this.format = source.format;
  6630. this.internalFormat = source.internalFormat;
  6631. this.type = source.type;
  6632. this.offset.copy(source.offset);
  6633. this.repeat.copy(source.repeat);
  6634. this.center.copy(source.center);
  6635. this.rotation = source.rotation;
  6636. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6637. this.matrix.copy(source.matrix);
  6638. this.generateMipmaps = source.generateMipmaps;
  6639. this.premultiplyAlpha = source.premultiplyAlpha;
  6640. this.flipY = source.flipY;
  6641. this.unpackAlignment = source.unpackAlignment;
  6642. this.encoding = source.encoding;
  6643. return this;
  6644. }
  6645. toJSON(meta) {
  6646. const isRootObject = meta === undefined || typeof meta === 'string';
  6647. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  6648. return meta.textures[this.uuid];
  6649. }
  6650. const output = {
  6651. metadata: {
  6652. version: 4.5,
  6653. type: 'Texture',
  6654. generator: 'Texture.toJSON'
  6655. },
  6656. uuid: this.uuid,
  6657. name: this.name,
  6658. mapping: this.mapping,
  6659. repeat: [this.repeat.x, this.repeat.y],
  6660. offset: [this.offset.x, this.offset.y],
  6661. center: [this.center.x, this.center.y],
  6662. rotation: this.rotation,
  6663. wrap: [this.wrapS, this.wrapT],
  6664. format: this.format,
  6665. type: this.type,
  6666. encoding: this.encoding,
  6667. minFilter: this.minFilter,
  6668. magFilter: this.magFilter,
  6669. anisotropy: this.anisotropy,
  6670. flipY: this.flipY,
  6671. premultiplyAlpha: this.premultiplyAlpha,
  6672. unpackAlignment: this.unpackAlignment
  6673. };
  6674. if (this.image !== undefined) {
  6675. // TODO: Move to THREE.Image
  6676. const image = this.image;
  6677. if (image.uuid === undefined) {
  6678. image.uuid = generateUUID(); // UGH
  6679. }
  6680. if (!isRootObject && meta.images[image.uuid] === undefined) {
  6681. let url;
  6682. if (Array.isArray(image)) {
  6683. // process array of images e.g. CubeTexture
  6684. url = [];
  6685. for (let i = 0, l = image.length; i < l; i++) {
  6686. // check cube texture with data textures
  6687. if (image[i].isDataTexture) {
  6688. url.push(serializeImage(image[i].image));
  6689. } else {
  6690. url.push(serializeImage(image[i]));
  6691. }
  6692. }
  6693. } else {
  6694. // process single image
  6695. url = serializeImage(image);
  6696. }
  6697. meta.images[image.uuid] = {
  6698. uuid: image.uuid,
  6699. url: url
  6700. };
  6701. }
  6702. output.image = image.uuid;
  6703. }
  6704. if (!isRootObject) {
  6705. meta.textures[this.uuid] = output;
  6706. }
  6707. return output;
  6708. }
  6709. dispose() {
  6710. this.dispatchEvent({
  6711. type: 'dispose'
  6712. });
  6713. }
  6714. transformUv(uv) {
  6715. if (this.mapping !== UVMapping) return uv;
  6716. uv.applyMatrix3(this.matrix);
  6717. if (uv.x < 0 || uv.x > 1) {
  6718. switch (this.wrapS) {
  6719. case RepeatWrapping:
  6720. uv.x = uv.x - Math.floor(uv.x);
  6721. break;
  6722. case ClampToEdgeWrapping:
  6723. uv.x = uv.x < 0 ? 0 : 1;
  6724. break;
  6725. case MirroredRepeatWrapping:
  6726. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  6727. uv.x = Math.ceil(uv.x) - uv.x;
  6728. } else {
  6729. uv.x = uv.x - Math.floor(uv.x);
  6730. }
  6731. break;
  6732. }
  6733. }
  6734. if (uv.y < 0 || uv.y > 1) {
  6735. switch (this.wrapT) {
  6736. case RepeatWrapping:
  6737. uv.y = uv.y - Math.floor(uv.y);
  6738. break;
  6739. case ClampToEdgeWrapping:
  6740. uv.y = uv.y < 0 ? 0 : 1;
  6741. break;
  6742. case MirroredRepeatWrapping:
  6743. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  6744. uv.y = Math.ceil(uv.y) - uv.y;
  6745. } else {
  6746. uv.y = uv.y - Math.floor(uv.y);
  6747. }
  6748. break;
  6749. }
  6750. }
  6751. if (this.flipY) {
  6752. uv.y = 1 - uv.y;
  6753. }
  6754. return uv;
  6755. }
  6756. set needsUpdate(value) {
  6757. if (value === true) this.version++;
  6758. }
  6759. }
  6760. Texture.DEFAULT_IMAGE = undefined;
  6761. Texture.DEFAULT_MAPPING = UVMapping;
  6762. Texture.prototype.isTexture = true;
  6763. function serializeImage(image) {
  6764. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  6765. // default images
  6766. return ImageUtils.getDataURL(image);
  6767. } else {
  6768. if (image.data) {
  6769. // images of DataTexture
  6770. return {
  6771. data: Array.prototype.slice.call(image.data),
  6772. width: image.width,
  6773. height: image.height,
  6774. type: image.data.constructor.name
  6775. };
  6776. } else {
  6777. console.warn('THREE.Texture: Unable to serialize Texture.');
  6778. return {};
  6779. }
  6780. }
  6781. }
  6782. class Vector4 {
  6783. constructor(x = 0, y = 0, z = 0, w = 1) {
  6784. this.x = x;
  6785. this.y = y;
  6786. this.z = z;
  6787. this.w = w;
  6788. }
  6789. get width() {
  6790. return this.z;
  6791. }
  6792. set width(value) {
  6793. this.z = value;
  6794. }
  6795. get height() {
  6796. return this.w;
  6797. }
  6798. set height(value) {
  6799. this.w = value;
  6800. }
  6801. set(x, y, z, w) {
  6802. this.x = x;
  6803. this.y = y;
  6804. this.z = z;
  6805. this.w = w;
  6806. return this;
  6807. }
  6808. setScalar(scalar) {
  6809. this.x = scalar;
  6810. this.y = scalar;
  6811. this.z = scalar;
  6812. this.w = scalar;
  6813. return this;
  6814. }
  6815. setX(x) {
  6816. this.x = x;
  6817. return this;
  6818. }
  6819. setY(y) {
  6820. this.y = y;
  6821. return this;
  6822. }
  6823. setZ(z) {
  6824. this.z = z;
  6825. return this;
  6826. }
  6827. setW(w) {
  6828. this.w = w;
  6829. return this;
  6830. }
  6831. setComponent(index, value) {
  6832. switch (index) {
  6833. case 0:
  6834. this.x = value;
  6835. break;
  6836. case 1:
  6837. this.y = value;
  6838. break;
  6839. case 2:
  6840. this.z = value;
  6841. break;
  6842. case 3:
  6843. this.w = value;
  6844. break;
  6845. default:
  6846. throw new Error('index is out of range: ' + index);
  6847. }
  6848. return this;
  6849. }
  6850. getComponent(index) {
  6851. switch (index) {
  6852. case 0:
  6853. return this.x;
  6854. case 1:
  6855. return this.y;
  6856. case 2:
  6857. return this.z;
  6858. case 3:
  6859. return this.w;
  6860. default:
  6861. throw new Error('index is out of range: ' + index);
  6862. }
  6863. }
  6864. clone() {
  6865. return new this.constructor(this.x, this.y, this.z, this.w);
  6866. }
  6867. copy(v) {
  6868. this.x = v.x;
  6869. this.y = v.y;
  6870. this.z = v.z;
  6871. this.w = v.w !== undefined ? v.w : 1;
  6872. return this;
  6873. }
  6874. add(v, w) {
  6875. if (w !== undefined) {
  6876. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6877. return this.addVectors(v, w);
  6878. }
  6879. this.x += v.x;
  6880. this.y += v.y;
  6881. this.z += v.z;
  6882. this.w += v.w;
  6883. return this;
  6884. }
  6885. addScalar(s) {
  6886. this.x += s;
  6887. this.y += s;
  6888. this.z += s;
  6889. this.w += s;
  6890. return this;
  6891. }
  6892. addVectors(a, b) {
  6893. this.x = a.x + b.x;
  6894. this.y = a.y + b.y;
  6895. this.z = a.z + b.z;
  6896. this.w = a.w + b.w;
  6897. return this;
  6898. }
  6899. addScaledVector(v, s) {
  6900. this.x += v.x * s;
  6901. this.y += v.y * s;
  6902. this.z += v.z * s;
  6903. this.w += v.w * s;
  6904. return this;
  6905. }
  6906. sub(v, w) {
  6907. if (w !== undefined) {
  6908. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6909. return this.subVectors(v, w);
  6910. }
  6911. this.x -= v.x;
  6912. this.y -= v.y;
  6913. this.z -= v.z;
  6914. this.w -= v.w;
  6915. return this;
  6916. }
  6917. subScalar(s) {
  6918. this.x -= s;
  6919. this.y -= s;
  6920. this.z -= s;
  6921. this.w -= s;
  6922. return this;
  6923. }
  6924. subVectors(a, b) {
  6925. this.x = a.x - b.x;
  6926. this.y = a.y - b.y;
  6927. this.z = a.z - b.z;
  6928. this.w = a.w - b.w;
  6929. return this;
  6930. }
  6931. multiply(v) {
  6932. this.x *= v.x;
  6933. this.y *= v.y;
  6934. this.z *= v.z;
  6935. this.w *= v.w;
  6936. return this;
  6937. }
  6938. multiplyScalar(scalar) {
  6939. this.x *= scalar;
  6940. this.y *= scalar;
  6941. this.z *= scalar;
  6942. this.w *= scalar;
  6943. return this;
  6944. }
  6945. applyMatrix4(m) {
  6946. const x = this.x,
  6947. y = this.y,
  6948. z = this.z,
  6949. w = this.w;
  6950. const e = m.elements;
  6951. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  6952. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  6953. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  6954. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  6955. return this;
  6956. }
  6957. divideScalar(scalar) {
  6958. return this.multiplyScalar(1 / scalar);
  6959. }
  6960. setAxisAngleFromQuaternion(q) {
  6961. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6962. // q is assumed to be normalized
  6963. this.w = 2 * Math.acos(q.w);
  6964. const s = Math.sqrt(1 - q.w * q.w);
  6965. if (s < 0.0001) {
  6966. this.x = 1;
  6967. this.y = 0;
  6968. this.z = 0;
  6969. } else {
  6970. this.x = q.x / s;
  6971. this.y = q.y / s;
  6972. this.z = q.z / s;
  6973. }
  6974. return this;
  6975. }
  6976. setAxisAngleFromRotationMatrix(m) {
  6977. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6978. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6979. let angle, x, y, z; // variables for result
  6980. const epsilon = 0.01,
  6981. // margin to allow for rounding errors
  6982. epsilon2 = 0.1,
  6983. // margin to distinguish between 0 and 180 degrees
  6984. te = m.elements,
  6985. m11 = te[0],
  6986. m12 = te[4],
  6987. m13 = te[8],
  6988. m21 = te[1],
  6989. m22 = te[5],
  6990. m23 = te[9],
  6991. m31 = te[2],
  6992. m32 = te[6],
  6993. m33 = te[10];
  6994. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  6995. // singularity found
  6996. // first check for identity matrix which must have +1 for all terms
  6997. // in leading diagonal and zero in other terms
  6998. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  6999. // this singularity is identity matrix so angle = 0
  7000. this.set(1, 0, 0, 0);
  7001. return this; // zero angle, arbitrary axis
  7002. } // otherwise this singularity is angle = 180
  7003. angle = Math.PI;
  7004. const xx = (m11 + 1) / 2;
  7005. const yy = (m22 + 1) / 2;
  7006. const zz = (m33 + 1) / 2;
  7007. const xy = (m12 + m21) / 4;
  7008. const xz = (m13 + m31) / 4;
  7009. const yz = (m23 + m32) / 4;
  7010. if (xx > yy && xx > zz) {
  7011. // m11 is the largest diagonal term
  7012. if (xx < epsilon) {
  7013. x = 0;
  7014. y = 0.707106781;
  7015. z = 0.707106781;
  7016. } else {
  7017. x = Math.sqrt(xx);
  7018. y = xy / x;
  7019. z = xz / x;
  7020. }
  7021. } else if (yy > zz) {
  7022. // m22 is the largest diagonal term
  7023. if (yy < epsilon) {
  7024. x = 0.707106781;
  7025. y = 0;
  7026. z = 0.707106781;
  7027. } else {
  7028. y = Math.sqrt(yy);
  7029. x = xy / y;
  7030. z = yz / y;
  7031. }
  7032. } else {
  7033. // m33 is the largest diagonal term so base result on this
  7034. if (zz < epsilon) {
  7035. x = 0.707106781;
  7036. y = 0.707106781;
  7037. z = 0;
  7038. } else {
  7039. z = Math.sqrt(zz);
  7040. x = xz / z;
  7041. y = yz / z;
  7042. }
  7043. }
  7044. this.set(x, y, z, angle);
  7045. return this; // return 180 deg rotation
  7046. } // as we have reached here there are no singularities so we can handle normally
  7047. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  7048. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7049. // caught by singularity test above, but I've left it in just in case
  7050. this.x = (m32 - m23) / s;
  7051. this.y = (m13 - m31) / s;
  7052. this.z = (m21 - m12) / s;
  7053. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  7054. return this;
  7055. }
  7056. min(v) {
  7057. this.x = Math.min(this.x, v.x);
  7058. this.y = Math.min(this.y, v.y);
  7059. this.z = Math.min(this.z, v.z);
  7060. this.w = Math.min(this.w, v.w);
  7061. return this;
  7062. }
  7063. max(v) {
  7064. this.x = Math.max(this.x, v.x);
  7065. this.y = Math.max(this.y, v.y);
  7066. this.z = Math.max(this.z, v.z);
  7067. this.w = Math.max(this.w, v.w);
  7068. return this;
  7069. }
  7070. clamp(min, max) {
  7071. // assumes min < max, componentwise
  7072. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7073. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7074. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7075. this.w = Math.max(min.w, Math.min(max.w, this.w));
  7076. return this;
  7077. }
  7078. clampScalar(minVal, maxVal) {
  7079. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  7080. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  7081. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  7082. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  7083. return this;
  7084. }
  7085. clampLength(min, max) {
  7086. const length = this.length();
  7087. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  7088. }
  7089. floor() {
  7090. this.x = Math.floor(this.x);
  7091. this.y = Math.floor(this.y);
  7092. this.z = Math.floor(this.z);
  7093. this.w = Math.floor(this.w);
  7094. return this;
  7095. }
  7096. ceil() {
  7097. this.x = Math.ceil(this.x);
  7098. this.y = Math.ceil(this.y);
  7099. this.z = Math.ceil(this.z);
  7100. this.w = Math.ceil(this.w);
  7101. return this;
  7102. }
  7103. round() {
  7104. this.x = Math.round(this.x);
  7105. this.y = Math.round(this.y);
  7106. this.z = Math.round(this.z);
  7107. this.w = Math.round(this.w);
  7108. return this;
  7109. }
  7110. roundToZero() {
  7111. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  7112. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  7113. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  7114. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  7115. return this;
  7116. }
  7117. negate() {
  7118. this.x = -this.x;
  7119. this.y = -this.y;
  7120. this.z = -this.z;
  7121. this.w = -this.w;
  7122. return this;
  7123. }
  7124. dot(v) {
  7125. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7126. }
  7127. lengthSq() {
  7128. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7129. }
  7130. length() {
  7131. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  7132. }
  7133. manhattanLength() {
  7134. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  7135. }
  7136. normalize() {
  7137. return this.divideScalar(this.length() || 1);
  7138. }
  7139. setLength(length) {
  7140. return this.normalize().multiplyScalar(length);
  7141. }
  7142. lerp(v, alpha) {
  7143. this.x += (v.x - this.x) * alpha;
  7144. this.y += (v.y - this.y) * alpha;
  7145. this.z += (v.z - this.z) * alpha;
  7146. this.w += (v.w - this.w) * alpha;
  7147. return this;
  7148. }
  7149. lerpVectors(v1, v2, alpha) {
  7150. this.x = v1.x + (v2.x - v1.x) * alpha;
  7151. this.y = v1.y + (v2.y - v1.y) * alpha;
  7152. this.z = v1.z + (v2.z - v1.z) * alpha;
  7153. this.w = v1.w + (v2.w - v1.w) * alpha;
  7154. return this;
  7155. }
  7156. equals(v) {
  7157. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  7158. }
  7159. fromArray(array, offset = 0) {
  7160. this.x = array[offset];
  7161. this.y = array[offset + 1];
  7162. this.z = array[offset + 2];
  7163. this.w = array[offset + 3];
  7164. return this;
  7165. }
  7166. toArray(array = [], offset = 0) {
  7167. array[offset] = this.x;
  7168. array[offset + 1] = this.y;
  7169. array[offset + 2] = this.z;
  7170. array[offset + 3] = this.w;
  7171. return array;
  7172. }
  7173. fromBufferAttribute(attribute, index, offset) {
  7174. if (offset !== undefined) {
  7175. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  7176. }
  7177. this.x = attribute.getX(index);
  7178. this.y = attribute.getY(index);
  7179. this.z = attribute.getZ(index);
  7180. this.w = attribute.getW(index);
  7181. return this;
  7182. }
  7183. random() {
  7184. this.x = Math.random();
  7185. this.y = Math.random();
  7186. this.z = Math.random();
  7187. this.w = Math.random();
  7188. return this;
  7189. }
  7190. *[Symbol.iterator]() {
  7191. yield this.x;
  7192. yield this.y;
  7193. yield this.z;
  7194. yield this.w;
  7195. }
  7196. }
  7197. Vector4.prototype.isVector4 = true;
  7198. /*
  7199. In options, we can specify:
  7200. * Texture parameters for an auto-generated target texture
  7201. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7202. */
  7203. class WebGLRenderTarget extends EventDispatcher {
  7204. constructor(width, height, options = {}) {
  7205. super();
  7206. this.width = width;
  7207. this.height = height;
  7208. this.depth = 1;
  7209. this.scissor = new Vector4(0, 0, width, height);
  7210. this.scissorTest = false;
  7211. this.viewport = new Vector4(0, 0, width, height);
  7212. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7213. this.texture.isRenderTargetTexture = true;
  7214. this.texture.image = {
  7215. width: width,
  7216. height: height,
  7217. depth: 1
  7218. };
  7219. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7220. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  7221. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7222. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7223. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  7224. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7225. }
  7226. setTexture(texture) {
  7227. texture.image = {
  7228. width: this.width,
  7229. height: this.height,
  7230. depth: this.depth
  7231. };
  7232. this.texture = texture;
  7233. }
  7234. setSize(width, height, depth = 1) {
  7235. if (this.width !== width || this.height !== height || this.depth !== depth) {
  7236. this.width = width;
  7237. this.height = height;
  7238. this.depth = depth;
  7239. this.texture.image.width = width;
  7240. this.texture.image.height = height;
  7241. this.texture.image.depth = depth;
  7242. this.dispose();
  7243. }
  7244. this.viewport.set(0, 0, width, height);
  7245. this.scissor.set(0, 0, width, height);
  7246. }
  7247. clone() {
  7248. return new this.constructor().copy(this);
  7249. }
  7250. copy(source) {
  7251. this.width = source.width;
  7252. this.height = source.height;
  7253. this.depth = source.depth;
  7254. this.viewport.copy(source.viewport);
  7255. this.texture = source.texture.clone();
  7256. this.texture.image = { ...this.texture.image
  7257. }; // See #20328.
  7258. this.depthBuffer = source.depthBuffer;
  7259. this.stencilBuffer = source.stencilBuffer;
  7260. this.depthTexture = source.depthTexture;
  7261. return this;
  7262. }
  7263. dispose() {
  7264. this.dispatchEvent({
  7265. type: 'dispose'
  7266. });
  7267. }
  7268. }
  7269. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  7270. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  7271. constructor(width, height, count) {
  7272. super(width, height);
  7273. const texture = this.texture;
  7274. this.texture = [];
  7275. for (let i = 0; i < count; i++) {
  7276. this.texture[i] = texture.clone();
  7277. }
  7278. }
  7279. setSize(width, height, depth = 1) {
  7280. if (this.width !== width || this.height !== height || this.depth !== depth) {
  7281. this.width = width;
  7282. this.height = height;
  7283. this.depth = depth;
  7284. for (let i = 0, il = this.texture.length; i < il; i++) {
  7285. this.texture[i].image.width = width;
  7286. this.texture[i].image.height = height;
  7287. this.texture[i].image.depth = depth;
  7288. }
  7289. this.dispose();
  7290. }
  7291. this.viewport.set(0, 0, width, height);
  7292. this.scissor.set(0, 0, width, height);
  7293. return this;
  7294. }
  7295. copy(source) {
  7296. this.dispose();
  7297. this.width = source.width;
  7298. this.height = source.height;
  7299. this.depth = source.depth;
  7300. this.viewport.set(0, 0, this.width, this.height);
  7301. this.scissor.set(0, 0, this.width, this.height);
  7302. this.depthBuffer = source.depthBuffer;
  7303. this.stencilBuffer = source.stencilBuffer;
  7304. this.depthTexture = source.depthTexture;
  7305. this.texture.length = 0;
  7306. for (let i = 0, il = source.texture.length; i < il; i++) {
  7307. this.texture[i] = source.texture[i].clone();
  7308. }
  7309. return this;
  7310. }
  7311. }
  7312. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  7313. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  7314. constructor(width, height, options) {
  7315. super(width, height, options);
  7316. this.samples = 4;
  7317. }
  7318. copy(source) {
  7319. super.copy.call(this, source);
  7320. this.samples = source.samples;
  7321. return this;
  7322. }
  7323. }
  7324. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  7325. class Quaternion {
  7326. constructor(x = 0, y = 0, z = 0, w = 1) {
  7327. this._x = x;
  7328. this._y = y;
  7329. this._z = z;
  7330. this._w = w;
  7331. }
  7332. static slerp(qa, qb, qm, t) {
  7333. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  7334. return qm.slerpQuaternions(qa, qb, t);
  7335. }
  7336. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  7337. // fuzz-free, array-based Quaternion SLERP operation
  7338. let x0 = src0[srcOffset0 + 0],
  7339. y0 = src0[srcOffset0 + 1],
  7340. z0 = src0[srcOffset0 + 2],
  7341. w0 = src0[srcOffset0 + 3];
  7342. const x1 = src1[srcOffset1 + 0],
  7343. y1 = src1[srcOffset1 + 1],
  7344. z1 = src1[srcOffset1 + 2],
  7345. w1 = src1[srcOffset1 + 3];
  7346. if (t === 0) {
  7347. dst[dstOffset + 0] = x0;
  7348. dst[dstOffset + 1] = y0;
  7349. dst[dstOffset + 2] = z0;
  7350. dst[dstOffset + 3] = w0;
  7351. return;
  7352. }
  7353. if (t === 1) {
  7354. dst[dstOffset + 0] = x1;
  7355. dst[dstOffset + 1] = y1;
  7356. dst[dstOffset + 2] = z1;
  7357. dst[dstOffset + 3] = w1;
  7358. return;
  7359. }
  7360. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  7361. let s = 1 - t;
  7362. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  7363. dir = cos >= 0 ? 1 : -1,
  7364. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  7365. if (sqrSin > Number.EPSILON) {
  7366. const sin = Math.sqrt(sqrSin),
  7367. len = Math.atan2(sin, cos * dir);
  7368. s = Math.sin(s * len) / sin;
  7369. t = Math.sin(t * len) / sin;
  7370. }
  7371. const tDir = t * dir;
  7372. x0 = x0 * s + x1 * tDir;
  7373. y0 = y0 * s + y1 * tDir;
  7374. z0 = z0 * s + z1 * tDir;
  7375. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  7376. if (s === 1 - t) {
  7377. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  7378. x0 *= f;
  7379. y0 *= f;
  7380. z0 *= f;
  7381. w0 *= f;
  7382. }
  7383. }
  7384. dst[dstOffset] = x0;
  7385. dst[dstOffset + 1] = y0;
  7386. dst[dstOffset + 2] = z0;
  7387. dst[dstOffset + 3] = w0;
  7388. }
  7389. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  7390. const x0 = src0[srcOffset0];
  7391. const y0 = src0[srcOffset0 + 1];
  7392. const z0 = src0[srcOffset0 + 2];
  7393. const w0 = src0[srcOffset0 + 3];
  7394. const x1 = src1[srcOffset1];
  7395. const y1 = src1[srcOffset1 + 1];
  7396. const z1 = src1[srcOffset1 + 2];
  7397. const w1 = src1[srcOffset1 + 3];
  7398. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  7399. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  7400. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  7401. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  7402. return dst;
  7403. }
  7404. get x() {
  7405. return this._x;
  7406. }
  7407. set x(value) {
  7408. this._x = value;
  7409. this._onChangeCallback();
  7410. }
  7411. get y() {
  7412. return this._y;
  7413. }
  7414. set y(value) {
  7415. this._y = value;
  7416. this._onChangeCallback();
  7417. }
  7418. get z() {
  7419. return this._z;
  7420. }
  7421. set z(value) {
  7422. this._z = value;
  7423. this._onChangeCallback();
  7424. }
  7425. get w() {
  7426. return this._w;
  7427. }
  7428. set w(value) {
  7429. this._w = value;
  7430. this._onChangeCallback();
  7431. }
  7432. set(x, y, z, w) {
  7433. this._x = x;
  7434. this._y = y;
  7435. this._z = z;
  7436. this._w = w;
  7437. this._onChangeCallback();
  7438. return this;
  7439. }
  7440. clone() {
  7441. return new this.constructor(this._x, this._y, this._z, this._w);
  7442. }
  7443. copy(quaternion) {
  7444. this._x = quaternion.x;
  7445. this._y = quaternion.y;
  7446. this._z = quaternion.z;
  7447. this._w = quaternion.w;
  7448. this._onChangeCallback();
  7449. return this;
  7450. }
  7451. setFromEuler(euler, update) {
  7452. if (!(euler && euler.isEuler)) {
  7453. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  7454. }
  7455. const x = euler._x,
  7456. y = euler._y,
  7457. z = euler._z,
  7458. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  7459. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  7460. // content/SpinCalc.m
  7461. const cos = Math.cos;
  7462. const sin = Math.sin;
  7463. const c1 = cos(x / 2);
  7464. const c2 = cos(y / 2);
  7465. const c3 = cos(z / 2);
  7466. const s1 = sin(x / 2);
  7467. const s2 = sin(y / 2);
  7468. const s3 = sin(z / 2);
  7469. switch (order) {
  7470. case 'XYZ':
  7471. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7472. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7473. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7474. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7475. break;
  7476. case 'YXZ':
  7477. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7478. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7479. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7480. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7481. break;
  7482. case 'ZXY':
  7483. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7484. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7485. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7486. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7487. break;
  7488. case 'ZYX':
  7489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7490. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7491. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7493. break;
  7494. case 'YZX':
  7495. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7496. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7497. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7498. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7499. break;
  7500. case 'XZY':
  7501. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7502. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7503. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7504. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7505. break;
  7506. default:
  7507. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  7508. }
  7509. if (update !== false) this._onChangeCallback();
  7510. return this;
  7511. }
  7512. setFromAxisAngle(axis, angle) {
  7513. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  7514. // assumes axis is normalized
  7515. const halfAngle = angle / 2,
  7516. s = Math.sin(halfAngle);
  7517. this._x = axis.x * s;
  7518. this._y = axis.y * s;
  7519. this._z = axis.z * s;
  7520. this._w = Math.cos(halfAngle);
  7521. this._onChangeCallback();
  7522. return this;
  7523. }
  7524. setFromRotationMatrix(m) {
  7525. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  7526. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7527. const te = m.elements,
  7528. m11 = te[0],
  7529. m12 = te[4],
  7530. m13 = te[8],
  7531. m21 = te[1],
  7532. m22 = te[5],
  7533. m23 = te[9],
  7534. m31 = te[2],
  7535. m32 = te[6],
  7536. m33 = te[10],
  7537. trace = m11 + m22 + m33;
  7538. if (trace > 0) {
  7539. const s = 0.5 / Math.sqrt(trace + 1.0);
  7540. this._w = 0.25 / s;
  7541. this._x = (m32 - m23) * s;
  7542. this._y = (m13 - m31) * s;
  7543. this._z = (m21 - m12) * s;
  7544. } else if (m11 > m22 && m11 > m33) {
  7545. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7546. this._w = (m32 - m23) / s;
  7547. this._x = 0.25 * s;
  7548. this._y = (m12 + m21) / s;
  7549. this._z = (m13 + m31) / s;
  7550. } else if (m22 > m33) {
  7551. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7552. this._w = (m13 - m31) / s;
  7553. this._x = (m12 + m21) / s;
  7554. this._y = 0.25 * s;
  7555. this._z = (m23 + m32) / s;
  7556. } else {
  7557. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7558. this._w = (m21 - m12) / s;
  7559. this._x = (m13 + m31) / s;
  7560. this._y = (m23 + m32) / s;
  7561. this._z = 0.25 * s;
  7562. }
  7563. this._onChangeCallback();
  7564. return this;
  7565. }
  7566. setFromUnitVectors(vFrom, vTo) {
  7567. // assumes direction vectors vFrom and vTo are normalized
  7568. let r = vFrom.dot(vTo) + 1;
  7569. if (r < Number.EPSILON) {
  7570. // vFrom and vTo point in opposite directions
  7571. r = 0;
  7572. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  7573. this._x = -vFrom.y;
  7574. this._y = vFrom.x;
  7575. this._z = 0;
  7576. this._w = r;
  7577. } else {
  7578. this._x = 0;
  7579. this._y = -vFrom.z;
  7580. this._z = vFrom.y;
  7581. this._w = r;
  7582. }
  7583. } else {
  7584. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  7585. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  7586. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  7587. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  7588. this._w = r;
  7589. }
  7590. return this.normalize();
  7591. }
  7592. angleTo(q) {
  7593. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  7594. }
  7595. rotateTowards(q, step) {
  7596. const angle = this.angleTo(q);
  7597. if (angle === 0) return this;
  7598. const t = Math.min(1, step / angle);
  7599. this.slerp(q, t);
  7600. return this;
  7601. }
  7602. identity() {
  7603. return this.set(0, 0, 0, 1);
  7604. }
  7605. invert() {
  7606. // quaternion is assumed to have unit length
  7607. return this.conjugate();
  7608. }
  7609. conjugate() {
  7610. this._x *= -1;
  7611. this._y *= -1;
  7612. this._z *= -1;
  7613. this._onChangeCallback();
  7614. return this;
  7615. }
  7616. dot(v) {
  7617. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  7618. }
  7619. lengthSq() {
  7620. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  7621. }
  7622. length() {
  7623. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  7624. }
  7625. normalize() {
  7626. let l = this.length();
  7627. if (l === 0) {
  7628. this._x = 0;
  7629. this._y = 0;
  7630. this._z = 0;
  7631. this._w = 1;
  7632. } else {
  7633. l = 1 / l;
  7634. this._x = this._x * l;
  7635. this._y = this._y * l;
  7636. this._z = this._z * l;
  7637. this._w = this._w * l;
  7638. }
  7639. this._onChangeCallback();
  7640. return this;
  7641. }
  7642. multiply(q, p) {
  7643. if (p !== undefined) {
  7644. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  7645. return this.multiplyQuaternions(q, p);
  7646. }
  7647. return this.multiplyQuaternions(this, q);
  7648. }
  7649. premultiply(q) {
  7650. return this.multiplyQuaternions(q, this);
  7651. }
  7652. multiplyQuaternions(a, b) {
  7653. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  7654. const qax = a._x,
  7655. qay = a._y,
  7656. qaz = a._z,
  7657. qaw = a._w;
  7658. const qbx = b._x,
  7659. qby = b._y,
  7660. qbz = b._z,
  7661. qbw = b._w;
  7662. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  7663. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  7664. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  7665. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  7666. this._onChangeCallback();
  7667. return this;
  7668. }
  7669. slerp(qb, t) {
  7670. if (t === 0) return this;
  7671. if (t === 1) return this.copy(qb);
  7672. const x = this._x,
  7673. y = this._y,
  7674. z = this._z,
  7675. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  7676. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  7677. if (cosHalfTheta < 0) {
  7678. this._w = -qb._w;
  7679. this._x = -qb._x;
  7680. this._y = -qb._y;
  7681. this._z = -qb._z;
  7682. cosHalfTheta = -cosHalfTheta;
  7683. } else {
  7684. this.copy(qb);
  7685. }
  7686. if (cosHalfTheta >= 1.0) {
  7687. this._w = w;
  7688. this._x = x;
  7689. this._y = y;
  7690. this._z = z;
  7691. return this;
  7692. }
  7693. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  7694. if (sqrSinHalfTheta <= Number.EPSILON) {
  7695. const s = 1 - t;
  7696. this._w = s * w + t * this._w;
  7697. this._x = s * x + t * this._x;
  7698. this._y = s * y + t * this._y;
  7699. this._z = s * z + t * this._z;
  7700. this.normalize();
  7701. this._onChangeCallback();
  7702. return this;
  7703. }
  7704. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  7705. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  7706. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  7707. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  7708. this._w = w * ratioA + this._w * ratioB;
  7709. this._x = x * ratioA + this._x * ratioB;
  7710. this._y = y * ratioA + this._y * ratioB;
  7711. this._z = z * ratioA + this._z * ratioB;
  7712. this._onChangeCallback();
  7713. return this;
  7714. }
  7715. slerpQuaternions(qa, qb, t) {
  7716. this.copy(qa).slerp(qb, t);
  7717. }
  7718. random() {
  7719. // Derived from http://planning.cs.uiuc.edu/node198.html
  7720. // Note, this source uses w, x, y, z ordering,
  7721. // so we swap the order below.
  7722. const u1 = Math.random();
  7723. const sqrt1u1 = Math.sqrt(1 - u1);
  7724. const sqrtu1 = Math.sqrt(u1);
  7725. const u2 = 2 * Math.PI * Math.random();
  7726. const u3 = 2 * Math.PI * Math.random();
  7727. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  7728. }
  7729. equals(quaternion) {
  7730. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  7731. }
  7732. fromArray(array, offset = 0) {
  7733. this._x = array[offset];
  7734. this._y = array[offset + 1];
  7735. this._z = array[offset + 2];
  7736. this._w = array[offset + 3];
  7737. this._onChangeCallback();
  7738. return this;
  7739. }
  7740. toArray(array = [], offset = 0) {
  7741. array[offset] = this._x;
  7742. array[offset + 1] = this._y;
  7743. array[offset + 2] = this._z;
  7744. array[offset + 3] = this._w;
  7745. return array;
  7746. }
  7747. fromBufferAttribute(attribute, index) {
  7748. this._x = attribute.getX(index);
  7749. this._y = attribute.getY(index);
  7750. this._z = attribute.getZ(index);
  7751. this._w = attribute.getW(index);
  7752. return this;
  7753. }
  7754. _onChange(callback) {
  7755. this._onChangeCallback = callback;
  7756. return this;
  7757. }
  7758. _onChangeCallback() {}
  7759. }
  7760. Quaternion.prototype.isQuaternion = true;
  7761. class Vector3 {
  7762. constructor(x = 0, y = 0, z = 0) {
  7763. this.x = x;
  7764. this.y = y;
  7765. this.z = z;
  7766. }
  7767. set(x, y, z) {
  7768. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  7769. this.x = x;
  7770. this.y = y;
  7771. this.z = z;
  7772. return this;
  7773. }
  7774. setScalar(scalar) {
  7775. this.x = scalar;
  7776. this.y = scalar;
  7777. this.z = scalar;
  7778. return this;
  7779. }
  7780. setX(x) {
  7781. this.x = x;
  7782. return this;
  7783. }
  7784. setY(y) {
  7785. this.y = y;
  7786. return this;
  7787. }
  7788. setZ(z) {
  7789. this.z = z;
  7790. return this;
  7791. }
  7792. setComponent(index, value) {
  7793. switch (index) {
  7794. case 0:
  7795. this.x = value;
  7796. break;
  7797. case 1:
  7798. this.y = value;
  7799. break;
  7800. case 2:
  7801. this.z = value;
  7802. break;
  7803. default:
  7804. throw new Error('index is out of range: ' + index);
  7805. }
  7806. return this;
  7807. }
  7808. getComponent(index) {
  7809. switch (index) {
  7810. case 0:
  7811. return this.x;
  7812. case 1:
  7813. return this.y;
  7814. case 2:
  7815. return this.z;
  7816. default:
  7817. throw new Error('index is out of range: ' + index);
  7818. }
  7819. }
  7820. clone() {
  7821. return new this.constructor(this.x, this.y, this.z);
  7822. }
  7823. copy(v) {
  7824. this.x = v.x;
  7825. this.y = v.y;
  7826. this.z = v.z;
  7827. return this;
  7828. }
  7829. add(v, w) {
  7830. if (w !== undefined) {
  7831. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  7832. return this.addVectors(v, w);
  7833. }
  7834. this.x += v.x;
  7835. this.y += v.y;
  7836. this.z += v.z;
  7837. return this;
  7838. }
  7839. addScalar(s) {
  7840. this.x += s;
  7841. this.y += s;
  7842. this.z += s;
  7843. return this;
  7844. }
  7845. addVectors(a, b) {
  7846. this.x = a.x + b.x;
  7847. this.y = a.y + b.y;
  7848. this.z = a.z + b.z;
  7849. return this;
  7850. }
  7851. addScaledVector(v, s) {
  7852. this.x += v.x * s;
  7853. this.y += v.y * s;
  7854. this.z += v.z * s;
  7855. return this;
  7856. }
  7857. sub(v, w) {
  7858. if (w !== undefined) {
  7859. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  7860. return this.subVectors(v, w);
  7861. }
  7862. this.x -= v.x;
  7863. this.y -= v.y;
  7864. this.z -= v.z;
  7865. return this;
  7866. }
  7867. subScalar(s) {
  7868. this.x -= s;
  7869. this.y -= s;
  7870. this.z -= s;
  7871. return this;
  7872. }
  7873. subVectors(a, b) {
  7874. this.x = a.x - b.x;
  7875. this.y = a.y - b.y;
  7876. this.z = a.z - b.z;
  7877. return this;
  7878. }
  7879. multiply(v, w) {
  7880. if (w !== undefined) {
  7881. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  7882. return this.multiplyVectors(v, w);
  7883. }
  7884. this.x *= v.x;
  7885. this.y *= v.y;
  7886. this.z *= v.z;
  7887. return this;
  7888. }
  7889. multiplyScalar(scalar) {
  7890. this.x *= scalar;
  7891. this.y *= scalar;
  7892. this.z *= scalar;
  7893. return this;
  7894. }
  7895. multiplyVectors(a, b) {
  7896. this.x = a.x * b.x;
  7897. this.y = a.y * b.y;
  7898. this.z = a.z * b.z;
  7899. return this;
  7900. }
  7901. applyEuler(euler) {
  7902. if (!(euler && euler.isEuler)) {
  7903. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  7904. }
  7905. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  7906. }
  7907. applyAxisAngle(axis, angle) {
  7908. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  7909. }
  7910. applyMatrix3(m) {
  7911. const x = this.x,
  7912. y = this.y,
  7913. z = this.z;
  7914. const e = m.elements;
  7915. this.x = e[0] * x + e[3] * y + e[6] * z;
  7916. this.y = e[1] * x + e[4] * y + e[7] * z;
  7917. this.z = e[2] * x + e[5] * y + e[8] * z;
  7918. return this;
  7919. }
  7920. applyNormalMatrix(m) {
  7921. return this.applyMatrix3(m).normalize();
  7922. }
  7923. applyMatrix4(m) {
  7924. const x = this.x,
  7925. y = this.y,
  7926. z = this.z;
  7927. const e = m.elements;
  7928. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  7929. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  7930. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  7931. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  7932. return this;
  7933. }
  7934. applyQuaternion(q) {
  7935. const x = this.x,
  7936. y = this.y,
  7937. z = this.z;
  7938. const qx = q.x,
  7939. qy = q.y,
  7940. qz = q.z,
  7941. qw = q.w; // calculate quat * vector
  7942. const ix = qw * x + qy * z - qz * y;
  7943. const iy = qw * y + qz * x - qx * z;
  7944. const iz = qw * z + qx * y - qy * x;
  7945. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  7946. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  7947. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  7948. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  7949. return this;
  7950. }
  7951. project(camera) {
  7952. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  7953. }
  7954. unproject(camera) {
  7955. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  7956. }
  7957. transformDirection(m) {
  7958. // input: THREE.Matrix4 affine matrix
  7959. // vector interpreted as a direction
  7960. const x = this.x,
  7961. y = this.y,
  7962. z = this.z;
  7963. const e = m.elements;
  7964. this.x = e[0] * x + e[4] * y + e[8] * z;
  7965. this.y = e[1] * x + e[5] * y + e[9] * z;
  7966. this.z = e[2] * x + e[6] * y + e[10] * z;
  7967. return this.normalize();
  7968. }
  7969. divide(v) {
  7970. this.x /= v.x;
  7971. this.y /= v.y;
  7972. this.z /= v.z;
  7973. return this;
  7974. }
  7975. divideScalar(scalar) {
  7976. return this.multiplyScalar(1 / scalar);
  7977. }
  7978. min(v) {
  7979. this.x = Math.min(this.x, v.x);
  7980. this.y = Math.min(this.y, v.y);
  7981. this.z = Math.min(this.z, v.z);
  7982. return this;
  7983. }
  7984. max(v) {
  7985. this.x = Math.max(this.x, v.x);
  7986. this.y = Math.max(this.y, v.y);
  7987. this.z = Math.max(this.z, v.z);
  7988. return this;
  7989. }
  7990. clamp(min, max) {
  7991. // assumes min < max, componentwise
  7992. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7993. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7994. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7995. return this;
  7996. }
  7997. clampScalar(minVal, maxVal) {
  7998. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  7999. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  8000. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  8001. return this;
  8002. }
  8003. clampLength(min, max) {
  8004. const length = this.length();
  8005. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  8006. }
  8007. floor() {
  8008. this.x = Math.floor(this.x);
  8009. this.y = Math.floor(this.y);
  8010. this.z = Math.floor(this.z);
  8011. return this;
  8012. }
  8013. ceil() {
  8014. this.x = Math.ceil(this.x);
  8015. this.y = Math.ceil(this.y);
  8016. this.z = Math.ceil(this.z);
  8017. return this;
  8018. }
  8019. round() {
  8020. this.x = Math.round(this.x);
  8021. this.y = Math.round(this.y);
  8022. this.z = Math.round(this.z);
  8023. return this;
  8024. }
  8025. roundToZero() {
  8026. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  8027. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  8028. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  8029. return this;
  8030. }
  8031. negate() {
  8032. this.x = -this.x;
  8033. this.y = -this.y;
  8034. this.z = -this.z;
  8035. return this;
  8036. }
  8037. dot(v) {
  8038. return this.x * v.x + this.y * v.y + this.z * v.z;
  8039. } // TODO lengthSquared?
  8040. lengthSq() {
  8041. return this.x * this.x + this.y * this.y + this.z * this.z;
  8042. }
  8043. length() {
  8044. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  8045. }
  8046. manhattanLength() {
  8047. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  8048. }
  8049. normalize() {
  8050. return this.divideScalar(this.length() || 1);
  8051. }
  8052. setLength(length) {
  8053. return this.normalize().multiplyScalar(length);
  8054. }
  8055. lerp(v, alpha) {
  8056. this.x += (v.x - this.x) * alpha;
  8057. this.y += (v.y - this.y) * alpha;
  8058. this.z += (v.z - this.z) * alpha;
  8059. return this;
  8060. }
  8061. lerpVectors(v1, v2, alpha) {
  8062. this.x = v1.x + (v2.x - v1.x) * alpha;
  8063. this.y = v1.y + (v2.y - v1.y) * alpha;
  8064. this.z = v1.z + (v2.z - v1.z) * alpha;
  8065. return this;
  8066. }
  8067. cross(v, w) {
  8068. if (w !== undefined) {
  8069. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  8070. return this.crossVectors(v, w);
  8071. }
  8072. return this.crossVectors(this, v);
  8073. }
  8074. crossVectors(a, b) {
  8075. const ax = a.x,
  8076. ay = a.y,
  8077. az = a.z;
  8078. const bx = b.x,
  8079. by = b.y,
  8080. bz = b.z;
  8081. this.x = ay * bz - az * by;
  8082. this.y = az * bx - ax * bz;
  8083. this.z = ax * by - ay * bx;
  8084. return this;
  8085. }
  8086. projectOnVector(v) {
  8087. const denominator = v.lengthSq();
  8088. if (denominator === 0) return this.set(0, 0, 0);
  8089. const scalar = v.dot(this) / denominator;
  8090. return this.copy(v).multiplyScalar(scalar);
  8091. }
  8092. projectOnPlane(planeNormal) {
  8093. _vector$c.copy(this).projectOnVector(planeNormal);
  8094. return this.sub(_vector$c);
  8095. }
  8096. reflect(normal) {
  8097. // reflect incident vector off plane orthogonal to normal
  8098. // normal is assumed to have unit length
  8099. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  8100. }
  8101. angleTo(v) {
  8102. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  8103. if (denominator === 0) return Math.PI / 2;
  8104. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  8105. return Math.acos(clamp(theta, -1, 1));
  8106. }
  8107. distanceTo(v) {
  8108. return Math.sqrt(this.distanceToSquared(v));
  8109. }
  8110. distanceToSquared(v) {
  8111. const dx = this.x - v.x,
  8112. dy = this.y - v.y,
  8113. dz = this.z - v.z;
  8114. return dx * dx + dy * dy + dz * dz;
  8115. }
  8116. manhattanDistanceTo(v) {
  8117. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  8118. }
  8119. setFromSpherical(s) {
  8120. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  8121. }
  8122. setFromSphericalCoords(radius, phi, theta) {
  8123. const sinPhiRadius = Math.sin(phi) * radius;
  8124. this.x = sinPhiRadius * Math.sin(theta);
  8125. this.y = Math.cos(phi) * radius;
  8126. this.z = sinPhiRadius * Math.cos(theta);
  8127. return this;
  8128. }
  8129. setFromCylindrical(c) {
  8130. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  8131. }
  8132. setFromCylindricalCoords(radius, theta, y) {
  8133. this.x = radius * Math.sin(theta);
  8134. this.y = y;
  8135. this.z = radius * Math.cos(theta);
  8136. return this;
  8137. }
  8138. setFromMatrixPosition(m) {
  8139. const e = m.elements;
  8140. this.x = e[12];
  8141. this.y = e[13];
  8142. this.z = e[14];
  8143. return this;
  8144. }
  8145. setFromMatrixScale(m) {
  8146. const sx = this.setFromMatrixColumn(m, 0).length();
  8147. const sy = this.setFromMatrixColumn(m, 1).length();
  8148. const sz = this.setFromMatrixColumn(m, 2).length();
  8149. this.x = sx;
  8150. this.y = sy;
  8151. this.z = sz;
  8152. return this;
  8153. }
  8154. setFromMatrixColumn(m, index) {
  8155. return this.fromArray(m.elements, index * 4);
  8156. }
  8157. setFromMatrix3Column(m, index) {
  8158. return this.fromArray(m.elements, index * 3);
  8159. }
  8160. equals(v) {
  8161. return v.x === this.x && v.y === this.y && v.z === this.z;
  8162. }
  8163. fromArray(array, offset = 0) {
  8164. this.x = array[offset];
  8165. this.y = array[offset + 1];
  8166. this.z = array[offset + 2];
  8167. return this;
  8168. }
  8169. toArray(array = [], offset = 0) {
  8170. array[offset] = this.x;
  8171. array[offset + 1] = this.y;
  8172. array[offset + 2] = this.z;
  8173. return array;
  8174. }
  8175. fromBufferAttribute(attribute, index, offset) {
  8176. if (offset !== undefined) {
  8177. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  8178. }
  8179. this.x = attribute.getX(index);
  8180. this.y = attribute.getY(index);
  8181. this.z = attribute.getZ(index);
  8182. return this;
  8183. }
  8184. random() {
  8185. this.x = Math.random();
  8186. this.y = Math.random();
  8187. this.z = Math.random();
  8188. return this;
  8189. }
  8190. randomDirection() {
  8191. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  8192. const u = (Math.random() - 0.5) * 2;
  8193. const t = Math.random() * Math.PI * 2;
  8194. const f = Math.sqrt(1 - u ** 2);
  8195. this.x = f * Math.cos(t);
  8196. this.y = f * Math.sin(t);
  8197. this.z = u;
  8198. return this;
  8199. }
  8200. *[Symbol.iterator]() {
  8201. yield this.x;
  8202. yield this.y;
  8203. yield this.z;
  8204. }
  8205. }
  8206. Vector3.prototype.isVector3 = true;
  8207. const _vector$c = /*@__PURE__*/new Vector3();
  8208. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  8209. class Box3 {
  8210. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  8211. this.min = min;
  8212. this.max = max;
  8213. }
  8214. set(min, max) {
  8215. this.min.copy(min);
  8216. this.max.copy(max);
  8217. return this;
  8218. }
  8219. setFromArray(array) {
  8220. let minX = +Infinity;
  8221. let minY = +Infinity;
  8222. let minZ = +Infinity;
  8223. let maxX = -Infinity;
  8224. let maxY = -Infinity;
  8225. let maxZ = -Infinity;
  8226. for (let i = 0, l = array.length; i < l; i += 3) {
  8227. const x = array[i];
  8228. const y = array[i + 1];
  8229. const z = array[i + 2];
  8230. if (x < minX) minX = x;
  8231. if (y < minY) minY = y;
  8232. if (z < minZ) minZ = z;
  8233. if (x > maxX) maxX = x;
  8234. if (y > maxY) maxY = y;
  8235. if (z > maxZ) maxZ = z;
  8236. }
  8237. this.min.set(minX, minY, minZ);
  8238. this.max.set(maxX, maxY, maxZ);
  8239. return this;
  8240. }
  8241. setFromBufferAttribute(attribute) {
  8242. let minX = +Infinity;
  8243. let minY = +Infinity;
  8244. let minZ = +Infinity;
  8245. let maxX = -Infinity;
  8246. let maxY = -Infinity;
  8247. let maxZ = -Infinity;
  8248. for (let i = 0, l = attribute.count; i < l; i++) {
  8249. const x = attribute.getX(i);
  8250. const y = attribute.getY(i);
  8251. const z = attribute.getZ(i);
  8252. if (x < minX) minX = x;
  8253. if (y < minY) minY = y;
  8254. if (z < minZ) minZ = z;
  8255. if (x > maxX) maxX = x;
  8256. if (y > maxY) maxY = y;
  8257. if (z > maxZ) maxZ = z;
  8258. }
  8259. this.min.set(minX, minY, minZ);
  8260. this.max.set(maxX, maxY, maxZ);
  8261. return this;
  8262. }
  8263. setFromPoints(points) {
  8264. this.makeEmpty();
  8265. for (let i = 0, il = points.length; i < il; i++) {
  8266. this.expandByPoint(points[i]);
  8267. }
  8268. return this;
  8269. }
  8270. setFromCenterAndSize(center, size) {
  8271. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  8272. this.min.copy(center).sub(halfSize);
  8273. this.max.copy(center).add(halfSize);
  8274. return this;
  8275. }
  8276. setFromObject(object) {
  8277. this.makeEmpty();
  8278. return this.expandByObject(object);
  8279. }
  8280. clone() {
  8281. return new this.constructor().copy(this);
  8282. }
  8283. copy(box) {
  8284. this.min.copy(box.min);
  8285. this.max.copy(box.max);
  8286. return this;
  8287. }
  8288. makeEmpty() {
  8289. this.min.x = this.min.y = this.min.z = +Infinity;
  8290. this.max.x = this.max.y = this.max.z = -Infinity;
  8291. return this;
  8292. }
  8293. isEmpty() {
  8294. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8295. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  8296. }
  8297. getCenter(target) {
  8298. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  8299. }
  8300. getSize(target) {
  8301. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  8302. }
  8303. expandByPoint(point) {
  8304. this.min.min(point);
  8305. this.max.max(point);
  8306. return this;
  8307. }
  8308. expandByVector(vector) {
  8309. this.min.sub(vector);
  8310. this.max.add(vector);
  8311. return this;
  8312. }
  8313. expandByScalar(scalar) {
  8314. this.min.addScalar(-scalar);
  8315. this.max.addScalar(scalar);
  8316. return this;
  8317. }
  8318. expandByObject(object) {
  8319. // Computes the world-axis-aligned bounding box of an object (including its children),
  8320. // accounting for both the object's, and children's, world transforms
  8321. object.updateWorldMatrix(false, false);
  8322. const geometry = object.geometry;
  8323. if (geometry !== undefined) {
  8324. if (geometry.boundingBox === null) {
  8325. geometry.computeBoundingBox();
  8326. }
  8327. _box$3.copy(geometry.boundingBox);
  8328. _box$3.applyMatrix4(object.matrixWorld);
  8329. this.union(_box$3);
  8330. }
  8331. const children = object.children;
  8332. for (let i = 0, l = children.length; i < l; i++) {
  8333. this.expandByObject(children[i]);
  8334. }
  8335. return this;
  8336. }
  8337. containsPoint(point) {
  8338. 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;
  8339. }
  8340. containsBox(box) {
  8341. 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;
  8342. }
  8343. getParameter(point, target) {
  8344. // This can potentially have a divide by zero if the box
  8345. // has a size dimension of 0.
  8346. 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));
  8347. }
  8348. intersectsBox(box) {
  8349. // using 6 splitting planes to rule out intersections.
  8350. 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;
  8351. }
  8352. intersectsSphere(sphere) {
  8353. // Find the point on the AABB closest to the sphere center.
  8354. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  8355. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  8356. }
  8357. intersectsPlane(plane) {
  8358. // We compute the minimum and maximum dot product values. If those values
  8359. // are on the same side (back or front) of the plane, then there is no intersection.
  8360. let min, max;
  8361. if (plane.normal.x > 0) {
  8362. min = plane.normal.x * this.min.x;
  8363. max = plane.normal.x * this.max.x;
  8364. } else {
  8365. min = plane.normal.x * this.max.x;
  8366. max = plane.normal.x * this.min.x;
  8367. }
  8368. if (plane.normal.y > 0) {
  8369. min += plane.normal.y * this.min.y;
  8370. max += plane.normal.y * this.max.y;
  8371. } else {
  8372. min += plane.normal.y * this.max.y;
  8373. max += plane.normal.y * this.min.y;
  8374. }
  8375. if (plane.normal.z > 0) {
  8376. min += plane.normal.z * this.min.z;
  8377. max += plane.normal.z * this.max.z;
  8378. } else {
  8379. min += plane.normal.z * this.max.z;
  8380. max += plane.normal.z * this.min.z;
  8381. }
  8382. return min <= -plane.constant && max >= -plane.constant;
  8383. }
  8384. intersectsTriangle(triangle) {
  8385. if (this.isEmpty()) {
  8386. return false;
  8387. } // compute box center and extents
  8388. this.getCenter(_center);
  8389. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  8390. _v0$2.subVectors(triangle.a, _center);
  8391. _v1$7.subVectors(triangle.b, _center);
  8392. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  8393. _f0.subVectors(_v1$7, _v0$2);
  8394. _f1.subVectors(_v2$3, _v1$7);
  8395. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  8396. // 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
  8397. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  8398. let 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];
  8399. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  8400. return false;
  8401. } // test 3 face normals from the aabb
  8402. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  8403. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  8404. return false;
  8405. } // finally testing the face normal of the triangle
  8406. // use already existing triangle edge vectors here
  8407. _triangleNormal.crossVectors(_f0, _f1);
  8408. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  8409. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  8410. }
  8411. clampPoint(point, target) {
  8412. return target.copy(point).clamp(this.min, this.max);
  8413. }
  8414. distanceToPoint(point) {
  8415. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  8416. return clampedPoint.sub(point).length();
  8417. }
  8418. getBoundingSphere(target) {
  8419. this.getCenter(target.center);
  8420. target.radius = this.getSize(_vector$b).length() * 0.5;
  8421. return target;
  8422. }
  8423. intersect(box) {
  8424. this.min.max(box.min);
  8425. 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.
  8426. if (this.isEmpty()) this.makeEmpty();
  8427. return this;
  8428. }
  8429. union(box) {
  8430. this.min.min(box.min);
  8431. this.max.max(box.max);
  8432. return this;
  8433. }
  8434. applyMatrix4(matrix) {
  8435. // transform of empty box is an empty box.
  8436. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8437. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  8438. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  8439. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  8440. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  8441. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  8442. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  8443. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  8444. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  8445. this.setFromPoints(_points);
  8446. return this;
  8447. }
  8448. translate(offset) {
  8449. this.min.add(offset);
  8450. this.max.add(offset);
  8451. return this;
  8452. }
  8453. equals(box) {
  8454. return box.min.equals(this.min) && box.max.equals(this.max);
  8455. }
  8456. }
  8457. Box3.prototype.isBox3 = true;
  8458. const _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()];
  8459. const _vector$b = /*@__PURE__*/new Vector3();
  8460. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  8461. const _v0$2 = /*@__PURE__*/new Vector3();
  8462. const _v1$7 = /*@__PURE__*/new Vector3();
  8463. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  8464. const _f0 = /*@__PURE__*/new Vector3();
  8465. const _f1 = /*@__PURE__*/new Vector3();
  8466. const _f2 = /*@__PURE__*/new Vector3();
  8467. const _center = /*@__PURE__*/new Vector3();
  8468. const _extents = /*@__PURE__*/new Vector3();
  8469. const _triangleNormal = /*@__PURE__*/new Vector3();
  8470. const _testAxis = /*@__PURE__*/new Vector3();
  8471. function satForAxes(axes, v0, v1, v2, extents) {
  8472. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  8473. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  8474. const 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
  8475. const p0 = v0.dot(_testAxis);
  8476. const p1 = v1.dot(_testAxis);
  8477. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  8478. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  8479. // points of the projected triangle are outside the projected half-length of the aabb
  8480. // the axis is seperating and we can exit
  8481. return false;
  8482. }
  8483. }
  8484. return true;
  8485. }
  8486. const _box$2 = /*@__PURE__*/new Box3();
  8487. const _v1$6 = /*@__PURE__*/new Vector3();
  8488. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  8489. const _toPoint = /*@__PURE__*/new Vector3();
  8490. class Sphere {
  8491. constructor(center = new Vector3(), radius = -1) {
  8492. this.center = center;
  8493. this.radius = radius;
  8494. }
  8495. set(center, radius) {
  8496. this.center.copy(center);
  8497. this.radius = radius;
  8498. return this;
  8499. }
  8500. setFromPoints(points, optionalCenter) {
  8501. const center = this.center;
  8502. if (optionalCenter !== undefined) {
  8503. center.copy(optionalCenter);
  8504. } else {
  8505. _box$2.setFromPoints(points).getCenter(center);
  8506. }
  8507. let maxRadiusSq = 0;
  8508. for (let i = 0, il = points.length; i < il; i++) {
  8509. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  8510. }
  8511. this.radius = Math.sqrt(maxRadiusSq);
  8512. return this;
  8513. }
  8514. copy(sphere) {
  8515. this.center.copy(sphere.center);
  8516. this.radius = sphere.radius;
  8517. return this;
  8518. }
  8519. isEmpty() {
  8520. return this.radius < 0;
  8521. }
  8522. makeEmpty() {
  8523. this.center.set(0, 0, 0);
  8524. this.radius = -1;
  8525. return this;
  8526. }
  8527. containsPoint(point) {
  8528. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  8529. }
  8530. distanceToPoint(point) {
  8531. return point.distanceTo(this.center) - this.radius;
  8532. }
  8533. intersectsSphere(sphere) {
  8534. const radiusSum = this.radius + sphere.radius;
  8535. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  8536. }
  8537. intersectsBox(box) {
  8538. return box.intersectsSphere(this);
  8539. }
  8540. intersectsPlane(plane) {
  8541. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  8542. }
  8543. clampPoint(point, target) {
  8544. const deltaLengthSq = this.center.distanceToSquared(point);
  8545. target.copy(point);
  8546. if (deltaLengthSq > this.radius * this.radius) {
  8547. target.sub(this.center).normalize();
  8548. target.multiplyScalar(this.radius).add(this.center);
  8549. }
  8550. return target;
  8551. }
  8552. getBoundingBox(target) {
  8553. if (this.isEmpty()) {
  8554. // Empty sphere produces empty bounding box
  8555. target.makeEmpty();
  8556. return target;
  8557. }
  8558. target.set(this.center, this.center);
  8559. target.expandByScalar(this.radius);
  8560. return target;
  8561. }
  8562. applyMatrix4(matrix) {
  8563. this.center.applyMatrix4(matrix);
  8564. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8565. return this;
  8566. }
  8567. translate(offset) {
  8568. this.center.add(offset);
  8569. return this;
  8570. }
  8571. expandByPoint(point) {
  8572. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  8573. _toPoint.subVectors(point, this.center);
  8574. const lengthSq = _toPoint.lengthSq();
  8575. if (lengthSq > this.radius * this.radius) {
  8576. const length = Math.sqrt(lengthSq);
  8577. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  8578. // and the other half to position. This gives a tighter enclosure, instead of if
  8579. // the whole missing distance were just added to radius.
  8580. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  8581. this.radius += missingRadiusHalf;
  8582. }
  8583. return this;
  8584. }
  8585. union(sphere) {
  8586. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  8587. // To enclose another sphere into this sphere, we only need to enclose two points:
  8588. // 1) Enclose the farthest point on the other sphere into this sphere.
  8589. // 2) Enclose the opposite point of the farthest point into this sphere.
  8590. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  8591. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  8592. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  8593. return this;
  8594. }
  8595. equals(sphere) {
  8596. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  8597. }
  8598. clone() {
  8599. return new this.constructor().copy(this);
  8600. }
  8601. }
  8602. const _vector$a = /*@__PURE__*/new Vector3();
  8603. const _segCenter = /*@__PURE__*/new Vector3();
  8604. const _segDir = /*@__PURE__*/new Vector3();
  8605. const _diff = /*@__PURE__*/new Vector3();
  8606. const _edge1 = /*@__PURE__*/new Vector3();
  8607. const _edge2 = /*@__PURE__*/new Vector3();
  8608. const _normal$1 = /*@__PURE__*/new Vector3();
  8609. class Ray {
  8610. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  8611. this.origin = origin;
  8612. this.direction = direction;
  8613. }
  8614. set(origin, direction) {
  8615. this.origin.copy(origin);
  8616. this.direction.copy(direction);
  8617. return this;
  8618. }
  8619. copy(ray) {
  8620. this.origin.copy(ray.origin);
  8621. this.direction.copy(ray.direction);
  8622. return this;
  8623. }
  8624. at(t, target) {
  8625. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  8626. }
  8627. lookAt(v) {
  8628. this.direction.copy(v).sub(this.origin).normalize();
  8629. return this;
  8630. }
  8631. recast(t) {
  8632. this.origin.copy(this.at(t, _vector$a));
  8633. return this;
  8634. }
  8635. closestPointToPoint(point, target) {
  8636. target.subVectors(point, this.origin);
  8637. const directionDistance = target.dot(this.direction);
  8638. if (directionDistance < 0) {
  8639. return target.copy(this.origin);
  8640. }
  8641. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  8642. }
  8643. distanceToPoint(point) {
  8644. return Math.sqrt(this.distanceSqToPoint(point));
  8645. }
  8646. distanceSqToPoint(point) {
  8647. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  8648. if (directionDistance < 0) {
  8649. return this.origin.distanceToSquared(point);
  8650. }
  8651. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  8652. return _vector$a.distanceToSquared(point);
  8653. }
  8654. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  8655. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8656. // It returns the min distance between the ray and the segment
  8657. // defined by v0 and v1
  8658. // It can also set two optional targets :
  8659. // - The closest point on the ray
  8660. // - The closest point on the segment
  8661. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  8662. _segDir.copy(v1).sub(v0).normalize();
  8663. _diff.copy(this.origin).sub(_segCenter);
  8664. const segExtent = v0.distanceTo(v1) * 0.5;
  8665. const a01 = -this.direction.dot(_segDir);
  8666. const b0 = _diff.dot(this.direction);
  8667. const b1 = -_diff.dot(_segDir);
  8668. const c = _diff.lengthSq();
  8669. const det = Math.abs(1 - a01 * a01);
  8670. let s0, s1, sqrDist, extDet;
  8671. if (det > 0) {
  8672. // The ray and segment are not parallel.
  8673. s0 = a01 * b1 - b0;
  8674. s1 = a01 * b0 - b1;
  8675. extDet = segExtent * det;
  8676. if (s0 >= 0) {
  8677. if (s1 >= -extDet) {
  8678. if (s1 <= extDet) {
  8679. // region 0
  8680. // Minimum at interior points of ray and segment.
  8681. const invDet = 1 / det;
  8682. s0 *= invDet;
  8683. s1 *= invDet;
  8684. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  8685. } else {
  8686. // region 1
  8687. s1 = segExtent;
  8688. s0 = Math.max(0, -(a01 * s1 + b0));
  8689. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8690. }
  8691. } else {
  8692. // region 5
  8693. s1 = -segExtent;
  8694. s0 = Math.max(0, -(a01 * s1 + b0));
  8695. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8696. }
  8697. } else {
  8698. if (s1 <= -extDet) {
  8699. // region 4
  8700. s0 = Math.max(0, -(-a01 * segExtent + b0));
  8701. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  8702. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8703. } else if (s1 <= extDet) {
  8704. // region 3
  8705. s0 = 0;
  8706. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  8707. sqrDist = s1 * (s1 + 2 * b1) + c;
  8708. } else {
  8709. // region 2
  8710. s0 = Math.max(0, -(a01 * segExtent + b0));
  8711. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  8712. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8713. }
  8714. }
  8715. } else {
  8716. // Ray and segment are parallel.
  8717. s1 = a01 > 0 ? -segExtent : segExtent;
  8718. s0 = Math.max(0, -(a01 * s1 + b0));
  8719. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  8720. }
  8721. if (optionalPointOnRay) {
  8722. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  8723. }
  8724. if (optionalPointOnSegment) {
  8725. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  8726. }
  8727. return sqrDist;
  8728. }
  8729. intersectSphere(sphere, target) {
  8730. _vector$a.subVectors(sphere.center, this.origin);
  8731. const tca = _vector$a.dot(this.direction);
  8732. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  8733. const radius2 = sphere.radius * sphere.radius;
  8734. if (d2 > radius2) return null;
  8735. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  8736. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  8737. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  8738. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  8739. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8740. // in order to always return an intersect point that is in front of the ray.
  8741. 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
  8742. return this.at(t0, target);
  8743. }
  8744. intersectsSphere(sphere) {
  8745. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  8746. }
  8747. distanceToPlane(plane) {
  8748. const denominator = plane.normal.dot(this.direction);
  8749. if (denominator === 0) {
  8750. // line is coplanar, return origin
  8751. if (plane.distanceToPoint(this.origin) === 0) {
  8752. return 0;
  8753. } // Null is preferable to undefined since undefined means.... it is undefined
  8754. return null;
  8755. }
  8756. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  8757. return t >= 0 ? t : null;
  8758. }
  8759. intersectPlane(plane, target) {
  8760. const t = this.distanceToPlane(plane);
  8761. if (t === null) {
  8762. return null;
  8763. }
  8764. return this.at(t, target);
  8765. }
  8766. intersectsPlane(plane) {
  8767. // check if the ray lies on the plane first
  8768. const distToPoint = plane.distanceToPoint(this.origin);
  8769. if (distToPoint === 0) {
  8770. return true;
  8771. }
  8772. const denominator = plane.normal.dot(this.direction);
  8773. if (denominator * distToPoint < 0) {
  8774. return true;
  8775. } // ray origin is behind the plane (and is pointing behind it)
  8776. return false;
  8777. }
  8778. intersectBox(box, target) {
  8779. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8780. const invdirx = 1 / this.direction.x,
  8781. invdiry = 1 / this.direction.y,
  8782. invdirz = 1 / this.direction.z;
  8783. const origin = this.origin;
  8784. if (invdirx >= 0) {
  8785. tmin = (box.min.x - origin.x) * invdirx;
  8786. tmax = (box.max.x - origin.x) * invdirx;
  8787. } else {
  8788. tmin = (box.max.x - origin.x) * invdirx;
  8789. tmax = (box.min.x - origin.x) * invdirx;
  8790. }
  8791. if (invdiry >= 0) {
  8792. tymin = (box.min.y - origin.y) * invdiry;
  8793. tymax = (box.max.y - origin.y) * invdiry;
  8794. } else {
  8795. tymin = (box.max.y - origin.y) * invdiry;
  8796. tymax = (box.min.y - origin.y) * invdiry;
  8797. }
  8798. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  8799. // (result of 0 * Infinity). x !== x returns true if x is NaN
  8800. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  8801. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  8802. if (invdirz >= 0) {
  8803. tzmin = (box.min.z - origin.z) * invdirz;
  8804. tzmax = (box.max.z - origin.z) * invdirz;
  8805. } else {
  8806. tzmin = (box.max.z - origin.z) * invdirz;
  8807. tzmax = (box.min.z - origin.z) * invdirz;
  8808. }
  8809. if (tmin > tzmax || tzmin > tmax) return null;
  8810. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  8811. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  8812. if (tmax < 0) return null;
  8813. return this.at(tmin >= 0 ? tmin : tmax, target);
  8814. }
  8815. intersectsBox(box) {
  8816. return this.intersectBox(box, _vector$a) !== null;
  8817. }
  8818. intersectTriangle(a, b, c, backfaceCulling, target) {
  8819. // Compute the offset origin, edges, and normal.
  8820. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8821. _edge1.subVectors(b, a);
  8822. _edge2.subVectors(c, a);
  8823. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8824. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8825. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8826. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8827. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8828. let DdN = this.direction.dot(_normal$1);
  8829. let sign;
  8830. if (DdN > 0) {
  8831. if (backfaceCulling) return null;
  8832. sign = 1;
  8833. } else if (DdN < 0) {
  8834. sign = -1;
  8835. DdN = -DdN;
  8836. } else {
  8837. return null;
  8838. }
  8839. _diff.subVectors(this.origin, a);
  8840. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  8841. if (DdQxE2 < 0) {
  8842. return null;
  8843. }
  8844. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  8845. if (DdE1xQ < 0) {
  8846. return null;
  8847. } // b1+b2 > 1, no intersection
  8848. if (DdQxE2 + DdE1xQ > DdN) {
  8849. return null;
  8850. } // Line intersects triangle, check if ray does.
  8851. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  8852. if (QdN < 0) {
  8853. return null;
  8854. } // Ray intersects triangle.
  8855. return this.at(QdN / DdN, target);
  8856. }
  8857. applyMatrix4(matrix4) {
  8858. this.origin.applyMatrix4(matrix4);
  8859. this.direction.transformDirection(matrix4);
  8860. return this;
  8861. }
  8862. equals(ray) {
  8863. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  8864. }
  8865. clone() {
  8866. return new this.constructor().copy(this);
  8867. }
  8868. }
  8869. class Matrix4 {
  8870. constructor() {
  8871. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  8872. if (arguments.length > 0) {
  8873. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  8874. }
  8875. }
  8876. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  8877. const te = this.elements;
  8878. te[0] = n11;
  8879. te[4] = n12;
  8880. te[8] = n13;
  8881. te[12] = n14;
  8882. te[1] = n21;
  8883. te[5] = n22;
  8884. te[9] = n23;
  8885. te[13] = n24;
  8886. te[2] = n31;
  8887. te[6] = n32;
  8888. te[10] = n33;
  8889. te[14] = n34;
  8890. te[3] = n41;
  8891. te[7] = n42;
  8892. te[11] = n43;
  8893. te[15] = n44;
  8894. return this;
  8895. }
  8896. identity() {
  8897. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  8898. return this;
  8899. }
  8900. clone() {
  8901. return new Matrix4().fromArray(this.elements);
  8902. }
  8903. copy(m) {
  8904. const te = this.elements;
  8905. const me = m.elements;
  8906. te[0] = me[0];
  8907. te[1] = me[1];
  8908. te[2] = me[2];
  8909. te[3] = me[3];
  8910. te[4] = me[4];
  8911. te[5] = me[5];
  8912. te[6] = me[6];
  8913. te[7] = me[7];
  8914. te[8] = me[8];
  8915. te[9] = me[9];
  8916. te[10] = me[10];
  8917. te[11] = me[11];
  8918. te[12] = me[12];
  8919. te[13] = me[13];
  8920. te[14] = me[14];
  8921. te[15] = me[15];
  8922. return this;
  8923. }
  8924. copyPosition(m) {
  8925. const te = this.elements,
  8926. me = m.elements;
  8927. te[12] = me[12];
  8928. te[13] = me[13];
  8929. te[14] = me[14];
  8930. return this;
  8931. }
  8932. setFromMatrix3(m) {
  8933. const me = m.elements;
  8934. 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);
  8935. return this;
  8936. }
  8937. extractBasis(xAxis, yAxis, zAxis) {
  8938. xAxis.setFromMatrixColumn(this, 0);
  8939. yAxis.setFromMatrixColumn(this, 1);
  8940. zAxis.setFromMatrixColumn(this, 2);
  8941. return this;
  8942. }
  8943. makeBasis(xAxis, yAxis, zAxis) {
  8944. 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);
  8945. return this;
  8946. }
  8947. extractRotation(m) {
  8948. // this method does not support reflection matrices
  8949. const te = this.elements;
  8950. const me = m.elements;
  8951. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  8952. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  8953. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  8954. te[0] = me[0] * scaleX;
  8955. te[1] = me[1] * scaleX;
  8956. te[2] = me[2] * scaleX;
  8957. te[3] = 0;
  8958. te[4] = me[4] * scaleY;
  8959. te[5] = me[5] * scaleY;
  8960. te[6] = me[6] * scaleY;
  8961. te[7] = 0;
  8962. te[8] = me[8] * scaleZ;
  8963. te[9] = me[9] * scaleZ;
  8964. te[10] = me[10] * scaleZ;
  8965. te[11] = 0;
  8966. te[12] = 0;
  8967. te[13] = 0;
  8968. te[14] = 0;
  8969. te[15] = 1;
  8970. return this;
  8971. }
  8972. makeRotationFromEuler(euler) {
  8973. if (!(euler && euler.isEuler)) {
  8974. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  8975. }
  8976. const te = this.elements;
  8977. const x = euler.x,
  8978. y = euler.y,
  8979. z = euler.z;
  8980. const a = Math.cos(x),
  8981. b = Math.sin(x);
  8982. const c = Math.cos(y),
  8983. d = Math.sin(y);
  8984. const e = Math.cos(z),
  8985. f = Math.sin(z);
  8986. if (euler.order === 'XYZ') {
  8987. const ae = a * e,
  8988. af = a * f,
  8989. be = b * e,
  8990. bf = b * f;
  8991. te[0] = c * e;
  8992. te[4] = -c * f;
  8993. te[8] = d;
  8994. te[1] = af + be * d;
  8995. te[5] = ae - bf * d;
  8996. te[9] = -b * c;
  8997. te[2] = bf - ae * d;
  8998. te[6] = be + af * d;
  8999. te[10] = a * c;
  9000. } else if (euler.order === 'YXZ') {
  9001. const ce = c * e,
  9002. cf = c * f,
  9003. de = d * e,
  9004. df = d * f;
  9005. te[0] = ce + df * b;
  9006. te[4] = de * b - cf;
  9007. te[8] = a * d;
  9008. te[1] = a * f;
  9009. te[5] = a * e;
  9010. te[9] = -b;
  9011. te[2] = cf * b - de;
  9012. te[6] = df + ce * b;
  9013. te[10] = a * c;
  9014. } else if (euler.order === 'ZXY') {
  9015. const ce = c * e,
  9016. cf = c * f,
  9017. de = d * e,
  9018. df = d * f;
  9019. te[0] = ce - df * b;
  9020. te[4] = -a * f;
  9021. te[8] = de + cf * b;
  9022. te[1] = cf + de * b;
  9023. te[5] = a * e;
  9024. te[9] = df - ce * b;
  9025. te[2] = -a * d;
  9026. te[6] = b;
  9027. te[10] = a * c;
  9028. } else if (euler.order === 'ZYX') {
  9029. const ae = a * e,
  9030. af = a * f,
  9031. be = b * e,
  9032. bf = b * f;
  9033. te[0] = c * e;
  9034. te[4] = be * d - af;
  9035. te[8] = ae * d + bf;
  9036. te[1] = c * f;
  9037. te[5] = bf * d + ae;
  9038. te[9] = af * d - be;
  9039. te[2] = -d;
  9040. te[6] = b * c;
  9041. te[10] = a * c;
  9042. } else if (euler.order === 'YZX') {
  9043. const ac = a * c,
  9044. ad = a * d,
  9045. bc = b * c,
  9046. bd = b * d;
  9047. te[0] = c * e;
  9048. te[4] = bd - ac * f;
  9049. te[8] = bc * f + ad;
  9050. te[1] = f;
  9051. te[5] = a * e;
  9052. te[9] = -b * e;
  9053. te[2] = -d * e;
  9054. te[6] = ad * f + bc;
  9055. te[10] = ac - bd * f;
  9056. } else if (euler.order === 'XZY') {
  9057. const ac = a * c,
  9058. ad = a * d,
  9059. bc = b * c,
  9060. bd = b * d;
  9061. te[0] = c * e;
  9062. te[4] = -f;
  9063. te[8] = d * e;
  9064. te[1] = ac * f + bd;
  9065. te[5] = a * e;
  9066. te[9] = ad * f - bc;
  9067. te[2] = bc * f - ad;
  9068. te[6] = b * e;
  9069. te[10] = bd * f + ac;
  9070. } // bottom row
  9071. te[3] = 0;
  9072. te[7] = 0;
  9073. te[11] = 0; // last column
  9074. te[12] = 0;
  9075. te[13] = 0;
  9076. te[14] = 0;
  9077. te[15] = 1;
  9078. return this;
  9079. }
  9080. makeRotationFromQuaternion(q) {
  9081. return this.compose(_zero, q, _one);
  9082. }
  9083. lookAt(eye, target, up) {
  9084. const te = this.elements;
  9085. _z.subVectors(eye, target);
  9086. if (_z.lengthSq() === 0) {
  9087. // eye and target are in the same position
  9088. _z.z = 1;
  9089. }
  9090. _z.normalize();
  9091. _x.crossVectors(up, _z);
  9092. if (_x.lengthSq() === 0) {
  9093. // up and z are parallel
  9094. if (Math.abs(up.z) === 1) {
  9095. _z.x += 0.0001;
  9096. } else {
  9097. _z.z += 0.0001;
  9098. }
  9099. _z.normalize();
  9100. _x.crossVectors(up, _z);
  9101. }
  9102. _x.normalize();
  9103. _y.crossVectors(_z, _x);
  9104. te[0] = _x.x;
  9105. te[4] = _y.x;
  9106. te[8] = _z.x;
  9107. te[1] = _x.y;
  9108. te[5] = _y.y;
  9109. te[9] = _z.y;
  9110. te[2] = _x.z;
  9111. te[6] = _y.z;
  9112. te[10] = _z.z;
  9113. return this;
  9114. }
  9115. multiply(m, n) {
  9116. if (n !== undefined) {
  9117. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  9118. return this.multiplyMatrices(m, n);
  9119. }
  9120. return this.multiplyMatrices(this, m);
  9121. }
  9122. premultiply(m) {
  9123. return this.multiplyMatrices(m, this);
  9124. }
  9125. multiplyMatrices(a, b) {
  9126. const ae = a.elements;
  9127. const be = b.elements;
  9128. const te = this.elements;
  9129. const a11 = ae[0],
  9130. a12 = ae[4],
  9131. a13 = ae[8],
  9132. a14 = ae[12];
  9133. const a21 = ae[1],
  9134. a22 = ae[5],
  9135. a23 = ae[9],
  9136. a24 = ae[13];
  9137. const a31 = ae[2],
  9138. a32 = ae[6],
  9139. a33 = ae[10],
  9140. a34 = ae[14];
  9141. const a41 = ae[3],
  9142. a42 = ae[7],
  9143. a43 = ae[11],
  9144. a44 = ae[15];
  9145. const b11 = be[0],
  9146. b12 = be[4],
  9147. b13 = be[8],
  9148. b14 = be[12];
  9149. const b21 = be[1],
  9150. b22 = be[5],
  9151. b23 = be[9],
  9152. b24 = be[13];
  9153. const b31 = be[2],
  9154. b32 = be[6],
  9155. b33 = be[10],
  9156. b34 = be[14];
  9157. const b41 = be[3],
  9158. b42 = be[7],
  9159. b43 = be[11],
  9160. b44 = be[15];
  9161. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9162. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9163. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9164. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9165. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9166. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9167. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9168. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9169. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9170. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9171. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9172. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9173. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9174. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9175. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9176. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9177. return this;
  9178. }
  9179. multiplyScalar(s) {
  9180. const te = this.elements;
  9181. te[0] *= s;
  9182. te[4] *= s;
  9183. te[8] *= s;
  9184. te[12] *= s;
  9185. te[1] *= s;
  9186. te[5] *= s;
  9187. te[9] *= s;
  9188. te[13] *= s;
  9189. te[2] *= s;
  9190. te[6] *= s;
  9191. te[10] *= s;
  9192. te[14] *= s;
  9193. te[3] *= s;
  9194. te[7] *= s;
  9195. te[11] *= s;
  9196. te[15] *= s;
  9197. return this;
  9198. }
  9199. determinant() {
  9200. const te = this.elements;
  9201. const n11 = te[0],
  9202. n12 = te[4],
  9203. n13 = te[8],
  9204. n14 = te[12];
  9205. const n21 = te[1],
  9206. n22 = te[5],
  9207. n23 = te[9],
  9208. n24 = te[13];
  9209. const n31 = te[2],
  9210. n32 = te[6],
  9211. n33 = te[10],
  9212. n34 = te[14];
  9213. const n41 = te[3],
  9214. n42 = te[7],
  9215. n43 = te[11],
  9216. n44 = te[15]; //TODO: make this more efficient
  9217. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  9218. 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);
  9219. }
  9220. transpose() {
  9221. const te = this.elements;
  9222. let tmp;
  9223. tmp = te[1];
  9224. te[1] = te[4];
  9225. te[4] = tmp;
  9226. tmp = te[2];
  9227. te[2] = te[8];
  9228. te[8] = tmp;
  9229. tmp = te[6];
  9230. te[6] = te[9];
  9231. te[9] = tmp;
  9232. tmp = te[3];
  9233. te[3] = te[12];
  9234. te[12] = tmp;
  9235. tmp = te[7];
  9236. te[7] = te[13];
  9237. te[13] = tmp;
  9238. tmp = te[11];
  9239. te[11] = te[14];
  9240. te[14] = tmp;
  9241. return this;
  9242. }
  9243. setPosition(x, y, z) {
  9244. const te = this.elements;
  9245. if (x.isVector3) {
  9246. te[12] = x.x;
  9247. te[13] = x.y;
  9248. te[14] = x.z;
  9249. } else {
  9250. te[12] = x;
  9251. te[13] = y;
  9252. te[14] = z;
  9253. }
  9254. return this;
  9255. }
  9256. invert() {
  9257. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9258. const te = this.elements,
  9259. n11 = te[0],
  9260. n21 = te[1],
  9261. n31 = te[2],
  9262. n41 = te[3],
  9263. n12 = te[4],
  9264. n22 = te[5],
  9265. n32 = te[6],
  9266. n42 = te[7],
  9267. n13 = te[8],
  9268. n23 = te[9],
  9269. n33 = te[10],
  9270. n43 = te[11],
  9271. n14 = te[12],
  9272. n24 = te[13],
  9273. n34 = te[14],
  9274. n44 = te[15],
  9275. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9276. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9277. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9278. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9279. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9280. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  9281. const detInv = 1 / det;
  9282. te[0] = t11 * detInv;
  9283. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  9284. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  9285. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  9286. te[4] = t12 * detInv;
  9287. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  9288. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  9289. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  9290. te[8] = t13 * detInv;
  9291. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  9292. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  9293. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  9294. te[12] = t14 * detInv;
  9295. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  9296. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  9297. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  9298. return this;
  9299. }
  9300. scale(v) {
  9301. const te = this.elements;
  9302. const x = v.x,
  9303. y = v.y,
  9304. z = v.z;
  9305. te[0] *= x;
  9306. te[4] *= y;
  9307. te[8] *= z;
  9308. te[1] *= x;
  9309. te[5] *= y;
  9310. te[9] *= z;
  9311. te[2] *= x;
  9312. te[6] *= y;
  9313. te[10] *= z;
  9314. te[3] *= x;
  9315. te[7] *= y;
  9316. te[11] *= z;
  9317. return this;
  9318. }
  9319. getMaxScaleOnAxis() {
  9320. const te = this.elements;
  9321. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  9322. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  9323. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  9324. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  9325. }
  9326. makeTranslation(x, y, z) {
  9327. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  9328. return this;
  9329. }
  9330. makeRotationX(theta) {
  9331. const c = Math.cos(theta),
  9332. s = Math.sin(theta);
  9333. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  9334. return this;
  9335. }
  9336. makeRotationY(theta) {
  9337. const c = Math.cos(theta),
  9338. s = Math.sin(theta);
  9339. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  9340. return this;
  9341. }
  9342. makeRotationZ(theta) {
  9343. const c = Math.cos(theta),
  9344. s = Math.sin(theta);
  9345. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  9346. return this;
  9347. }
  9348. makeRotationAxis(axis, angle) {
  9349. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9350. const c = Math.cos(angle);
  9351. const s = Math.sin(angle);
  9352. const t = 1 - c;
  9353. const x = axis.x,
  9354. y = axis.y,
  9355. z = axis.z;
  9356. const tx = t * x,
  9357. ty = t * y;
  9358. 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);
  9359. return this;
  9360. }
  9361. makeScale(x, y, z) {
  9362. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  9363. return this;
  9364. }
  9365. makeShear(xy, xz, yx, yz, zx, zy) {
  9366. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  9367. return this;
  9368. }
  9369. compose(position, quaternion, scale) {
  9370. const te = this.elements;
  9371. const x = quaternion._x,
  9372. y = quaternion._y,
  9373. z = quaternion._z,
  9374. w = quaternion._w;
  9375. const x2 = x + x,
  9376. y2 = y + y,
  9377. z2 = z + z;
  9378. const xx = x * x2,
  9379. xy = x * y2,
  9380. xz = x * z2;
  9381. const yy = y * y2,
  9382. yz = y * z2,
  9383. zz = z * z2;
  9384. const wx = w * x2,
  9385. wy = w * y2,
  9386. wz = w * z2;
  9387. const sx = scale.x,
  9388. sy = scale.y,
  9389. sz = scale.z;
  9390. te[0] = (1 - (yy + zz)) * sx;
  9391. te[1] = (xy + wz) * sx;
  9392. te[2] = (xz - wy) * sx;
  9393. te[3] = 0;
  9394. te[4] = (xy - wz) * sy;
  9395. te[5] = (1 - (xx + zz)) * sy;
  9396. te[6] = (yz + wx) * sy;
  9397. te[7] = 0;
  9398. te[8] = (xz + wy) * sz;
  9399. te[9] = (yz - wx) * sz;
  9400. te[10] = (1 - (xx + yy)) * sz;
  9401. te[11] = 0;
  9402. te[12] = position.x;
  9403. te[13] = position.y;
  9404. te[14] = position.z;
  9405. te[15] = 1;
  9406. return this;
  9407. }
  9408. decompose(position, quaternion, scale) {
  9409. const te = this.elements;
  9410. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  9411. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  9412. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  9413. const det = this.determinant();
  9414. if (det < 0) sx = -sx;
  9415. position.x = te[12];
  9416. position.y = te[13];
  9417. position.z = te[14]; // scale the rotation part
  9418. _m1$2.copy(this);
  9419. const invSX = 1 / sx;
  9420. const invSY = 1 / sy;
  9421. const invSZ = 1 / sz;
  9422. _m1$2.elements[0] *= invSX;
  9423. _m1$2.elements[1] *= invSX;
  9424. _m1$2.elements[2] *= invSX;
  9425. _m1$2.elements[4] *= invSY;
  9426. _m1$2.elements[5] *= invSY;
  9427. _m1$2.elements[6] *= invSY;
  9428. _m1$2.elements[8] *= invSZ;
  9429. _m1$2.elements[9] *= invSZ;
  9430. _m1$2.elements[10] *= invSZ;
  9431. quaternion.setFromRotationMatrix(_m1$2);
  9432. scale.x = sx;
  9433. scale.y = sy;
  9434. scale.z = sz;
  9435. return this;
  9436. }
  9437. makePerspective(left, right, top, bottom, near, far) {
  9438. if (far === undefined) {
  9439. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  9440. }
  9441. const te = this.elements;
  9442. const x = 2 * near / (right - left);
  9443. const y = 2 * near / (top - bottom);
  9444. const a = (right + left) / (right - left);
  9445. const b = (top + bottom) / (top - bottom);
  9446. const c = -(far + near) / (far - near);
  9447. const d = -2 * far * near / (far - near);
  9448. te[0] = x;
  9449. te[4] = 0;
  9450. te[8] = a;
  9451. te[12] = 0;
  9452. te[1] = 0;
  9453. te[5] = y;
  9454. te[9] = b;
  9455. te[13] = 0;
  9456. te[2] = 0;
  9457. te[6] = 0;
  9458. te[10] = c;
  9459. te[14] = d;
  9460. te[3] = 0;
  9461. te[7] = 0;
  9462. te[11] = -1;
  9463. te[15] = 0;
  9464. return this;
  9465. }
  9466. makeOrthographic(left, right, top, bottom, near, far) {
  9467. const te = this.elements;
  9468. const w = 1.0 / (right - left);
  9469. const h = 1.0 / (top - bottom);
  9470. const p = 1.0 / (far - near);
  9471. const x = (right + left) * w;
  9472. const y = (top + bottom) * h;
  9473. const z = (far + near) * p;
  9474. te[0] = 2 * w;
  9475. te[4] = 0;
  9476. te[8] = 0;
  9477. te[12] = -x;
  9478. te[1] = 0;
  9479. te[5] = 2 * h;
  9480. te[9] = 0;
  9481. te[13] = -y;
  9482. te[2] = 0;
  9483. te[6] = 0;
  9484. te[10] = -2 * p;
  9485. te[14] = -z;
  9486. te[3] = 0;
  9487. te[7] = 0;
  9488. te[11] = 0;
  9489. te[15] = 1;
  9490. return this;
  9491. }
  9492. equals(matrix) {
  9493. const te = this.elements;
  9494. const me = matrix.elements;
  9495. for (let i = 0; i < 16; i++) {
  9496. if (te[i] !== me[i]) return false;
  9497. }
  9498. return true;
  9499. }
  9500. fromArray(array, offset = 0) {
  9501. for (let i = 0; i < 16; i++) {
  9502. this.elements[i] = array[i + offset];
  9503. }
  9504. return this;
  9505. }
  9506. toArray(array = [], offset = 0) {
  9507. const te = this.elements;
  9508. array[offset] = te[0];
  9509. array[offset + 1] = te[1];
  9510. array[offset + 2] = te[2];
  9511. array[offset + 3] = te[3];
  9512. array[offset + 4] = te[4];
  9513. array[offset + 5] = te[5];
  9514. array[offset + 6] = te[6];
  9515. array[offset + 7] = te[7];
  9516. array[offset + 8] = te[8];
  9517. array[offset + 9] = te[9];
  9518. array[offset + 10] = te[10];
  9519. array[offset + 11] = te[11];
  9520. array[offset + 12] = te[12];
  9521. array[offset + 13] = te[13];
  9522. array[offset + 14] = te[14];
  9523. array[offset + 15] = te[15];
  9524. return array;
  9525. }
  9526. }
  9527. Matrix4.prototype.isMatrix4 = true;
  9528. const _v1$5 = /*@__PURE__*/new Vector3();
  9529. const _m1$2 = /*@__PURE__*/new Matrix4();
  9530. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  9531. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  9532. const _x = /*@__PURE__*/new Vector3();
  9533. const _y = /*@__PURE__*/new Vector3();
  9534. const _z = /*@__PURE__*/new Vector3();
  9535. const _matrix$1 = /*@__PURE__*/new Matrix4();
  9536. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  9537. class Euler {
  9538. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  9539. this._x = x;
  9540. this._y = y;
  9541. this._z = z;
  9542. this._order = order;
  9543. }
  9544. get x() {
  9545. return this._x;
  9546. }
  9547. set x(value) {
  9548. this._x = value;
  9549. this._onChangeCallback();
  9550. }
  9551. get y() {
  9552. return this._y;
  9553. }
  9554. set y(value) {
  9555. this._y = value;
  9556. this._onChangeCallback();
  9557. }
  9558. get z() {
  9559. return this._z;
  9560. }
  9561. set z(value) {
  9562. this._z = value;
  9563. this._onChangeCallback();
  9564. }
  9565. get order() {
  9566. return this._order;
  9567. }
  9568. set order(value) {
  9569. this._order = value;
  9570. this._onChangeCallback();
  9571. }
  9572. set(x, y, z, order = this._order) {
  9573. this._x = x;
  9574. this._y = y;
  9575. this._z = z;
  9576. this._order = order;
  9577. this._onChangeCallback();
  9578. return this;
  9579. }
  9580. clone() {
  9581. return new this.constructor(this._x, this._y, this._z, this._order);
  9582. }
  9583. copy(euler) {
  9584. this._x = euler._x;
  9585. this._y = euler._y;
  9586. this._z = euler._z;
  9587. this._order = euler._order;
  9588. this._onChangeCallback();
  9589. return this;
  9590. }
  9591. setFromRotationMatrix(m, order = this._order, update = true) {
  9592. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9593. const te = m.elements;
  9594. const m11 = te[0],
  9595. m12 = te[4],
  9596. m13 = te[8];
  9597. const m21 = te[1],
  9598. m22 = te[5],
  9599. m23 = te[9];
  9600. const m31 = te[2],
  9601. m32 = te[6],
  9602. m33 = te[10];
  9603. switch (order) {
  9604. case 'XYZ':
  9605. this._y = Math.asin(clamp(m13, -1, 1));
  9606. if (Math.abs(m13) < 0.9999999) {
  9607. this._x = Math.atan2(-m23, m33);
  9608. this._z = Math.atan2(-m12, m11);
  9609. } else {
  9610. this._x = Math.atan2(m32, m22);
  9611. this._z = 0;
  9612. }
  9613. break;
  9614. case 'YXZ':
  9615. this._x = Math.asin(-clamp(m23, -1, 1));
  9616. if (Math.abs(m23) < 0.9999999) {
  9617. this._y = Math.atan2(m13, m33);
  9618. this._z = Math.atan2(m21, m22);
  9619. } else {
  9620. this._y = Math.atan2(-m31, m11);
  9621. this._z = 0;
  9622. }
  9623. break;
  9624. case 'ZXY':
  9625. this._x = Math.asin(clamp(m32, -1, 1));
  9626. if (Math.abs(m32) < 0.9999999) {
  9627. this._y = Math.atan2(-m31, m33);
  9628. this._z = Math.atan2(-m12, m22);
  9629. } else {
  9630. this._y = 0;
  9631. this._z = Math.atan2(m21, m11);
  9632. }
  9633. break;
  9634. case 'ZYX':
  9635. this._y = Math.asin(-clamp(m31, -1, 1));
  9636. if (Math.abs(m31) < 0.9999999) {
  9637. this._x = Math.atan2(m32, m33);
  9638. this._z = Math.atan2(m21, m11);
  9639. } else {
  9640. this._x = 0;
  9641. this._z = Math.atan2(-m12, m22);
  9642. }
  9643. break;
  9644. case 'YZX':
  9645. this._z = Math.asin(clamp(m21, -1, 1));
  9646. if (Math.abs(m21) < 0.9999999) {
  9647. this._x = Math.atan2(-m23, m22);
  9648. this._y = Math.atan2(-m31, m11);
  9649. } else {
  9650. this._x = 0;
  9651. this._y = Math.atan2(m13, m33);
  9652. }
  9653. break;
  9654. case 'XZY':
  9655. this._z = Math.asin(-clamp(m12, -1, 1));
  9656. if (Math.abs(m12) < 0.9999999) {
  9657. this._x = Math.atan2(m32, m22);
  9658. this._y = Math.atan2(m13, m11);
  9659. } else {
  9660. this._x = Math.atan2(-m23, m33);
  9661. this._y = 0;
  9662. }
  9663. break;
  9664. default:
  9665. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  9666. }
  9667. this._order = order;
  9668. if (update === true) this._onChangeCallback();
  9669. return this;
  9670. }
  9671. setFromQuaternion(q, order, update) {
  9672. _matrix$1.makeRotationFromQuaternion(q);
  9673. return this.setFromRotationMatrix(_matrix$1, order, update);
  9674. }
  9675. setFromVector3(v, order = this._order) {
  9676. return this.set(v.x, v.y, v.z, order);
  9677. }
  9678. reorder(newOrder) {
  9679. // WARNING: this discards revolution information -bhouston
  9680. _quaternion$3.setFromEuler(this);
  9681. return this.setFromQuaternion(_quaternion$3, newOrder);
  9682. }
  9683. equals(euler) {
  9684. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  9685. }
  9686. fromArray(array) {
  9687. this._x = array[0];
  9688. this._y = array[1];
  9689. this._z = array[2];
  9690. if (array[3] !== undefined) this._order = array[3];
  9691. this._onChangeCallback();
  9692. return this;
  9693. }
  9694. toArray(array = [], offset = 0) {
  9695. array[offset] = this._x;
  9696. array[offset + 1] = this._y;
  9697. array[offset + 2] = this._z;
  9698. array[offset + 3] = this._order;
  9699. return array;
  9700. }
  9701. toVector3(optionalResult) {
  9702. if (optionalResult) {
  9703. return optionalResult.set(this._x, this._y, this._z);
  9704. } else {
  9705. return new Vector3(this._x, this._y, this._z);
  9706. }
  9707. }
  9708. _onChange(callback) {
  9709. this._onChangeCallback = callback;
  9710. return this;
  9711. }
  9712. _onChangeCallback() {}
  9713. }
  9714. Euler.prototype.isEuler = true;
  9715. Euler.DefaultOrder = 'XYZ';
  9716. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  9717. class Layers {
  9718. constructor() {
  9719. this.mask = 1 | 0;
  9720. }
  9721. set(channel) {
  9722. this.mask = 1 << channel | 0;
  9723. }
  9724. enable(channel) {
  9725. this.mask |= 1 << channel | 0;
  9726. }
  9727. enableAll() {
  9728. this.mask = 0xffffffff | 0;
  9729. }
  9730. toggle(channel) {
  9731. this.mask ^= 1 << channel | 0;
  9732. }
  9733. disable(channel) {
  9734. this.mask &= ~(1 << channel | 0);
  9735. }
  9736. disableAll() {
  9737. this.mask = 0;
  9738. }
  9739. test(layers) {
  9740. return (this.mask & layers.mask) !== 0;
  9741. }
  9742. }
  9743. let _object3DId = 0;
  9744. const _v1$4 = /*@__PURE__*/new Vector3();
  9745. const _q1 = /*@__PURE__*/new Quaternion();
  9746. const _m1$1 = /*@__PURE__*/new Matrix4();
  9747. const _target = /*@__PURE__*/new Vector3();
  9748. const _position$3 = /*@__PURE__*/new Vector3();
  9749. const _scale$2 = /*@__PURE__*/new Vector3();
  9750. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  9751. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  9752. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  9753. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  9754. const _addedEvent = {
  9755. type: 'added'
  9756. };
  9757. const _removedEvent = {
  9758. type: 'removed'
  9759. };
  9760. class Object3D extends EventDispatcher {
  9761. constructor() {
  9762. super();
  9763. Object.defineProperty(this, 'id', {
  9764. value: _object3DId++
  9765. });
  9766. this.uuid = generateUUID();
  9767. this.name = '';
  9768. this.type = 'Object3D';
  9769. this.parent = null;
  9770. this.children = [];
  9771. this.up = Object3D.DefaultUp.clone();
  9772. const position = new Vector3();
  9773. const rotation = new Euler();
  9774. const quaternion = new Quaternion();
  9775. const scale = new Vector3(1, 1, 1);
  9776. function onRotationChange() {
  9777. quaternion.setFromEuler(rotation, false);
  9778. }
  9779. function onQuaternionChange() {
  9780. rotation.setFromQuaternion(quaternion, undefined, false);
  9781. }
  9782. rotation._onChange(onRotationChange);
  9783. quaternion._onChange(onQuaternionChange);
  9784. Object.defineProperties(this, {
  9785. position: {
  9786. configurable: true,
  9787. enumerable: true,
  9788. value: position
  9789. },
  9790. rotation: {
  9791. configurable: true,
  9792. enumerable: true,
  9793. value: rotation
  9794. },
  9795. quaternion: {
  9796. configurable: true,
  9797. enumerable: true,
  9798. value: quaternion
  9799. },
  9800. scale: {
  9801. configurable: true,
  9802. enumerable: true,
  9803. value: scale
  9804. },
  9805. modelViewMatrix: {
  9806. value: new Matrix4()
  9807. },
  9808. normalMatrix: {
  9809. value: new Matrix3()
  9810. }
  9811. });
  9812. this.matrix = new Matrix4();
  9813. this.matrixWorld = new Matrix4();
  9814. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  9815. this.matrixWorldNeedsUpdate = false;
  9816. this.layers = new Layers();
  9817. this.visible = true;
  9818. this.castShadow = false;
  9819. this.receiveShadow = false;
  9820. this.frustumCulled = true;
  9821. this.renderOrder = 0;
  9822. this.animations = [];
  9823. this.userData = {};
  9824. }
  9825. onBeforeRender() {}
  9826. onAfterRender() {}
  9827. applyMatrix4(matrix) {
  9828. if (this.matrixAutoUpdate) this.updateMatrix();
  9829. this.matrix.premultiply(matrix);
  9830. this.matrix.decompose(this.position, this.quaternion, this.scale);
  9831. }
  9832. applyQuaternion(q) {
  9833. this.quaternion.premultiply(q);
  9834. return this;
  9835. }
  9836. setRotationFromAxisAngle(axis, angle) {
  9837. // assumes axis is normalized
  9838. this.quaternion.setFromAxisAngle(axis, angle);
  9839. }
  9840. setRotationFromEuler(euler) {
  9841. this.quaternion.setFromEuler(euler, true);
  9842. }
  9843. setRotationFromMatrix(m) {
  9844. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9845. this.quaternion.setFromRotationMatrix(m);
  9846. }
  9847. setRotationFromQuaternion(q) {
  9848. // assumes q is normalized
  9849. this.quaternion.copy(q);
  9850. }
  9851. rotateOnAxis(axis, angle) {
  9852. // rotate object on axis in object space
  9853. // axis is assumed to be normalized
  9854. _q1.setFromAxisAngle(axis, angle);
  9855. this.quaternion.multiply(_q1);
  9856. return this;
  9857. }
  9858. rotateOnWorldAxis(axis, angle) {
  9859. // rotate object on axis in world space
  9860. // axis is assumed to be normalized
  9861. // method assumes no rotated parent
  9862. _q1.setFromAxisAngle(axis, angle);
  9863. this.quaternion.premultiply(_q1);
  9864. return this;
  9865. }
  9866. rotateX(angle) {
  9867. return this.rotateOnAxis(_xAxis, angle);
  9868. }
  9869. rotateY(angle) {
  9870. return this.rotateOnAxis(_yAxis, angle);
  9871. }
  9872. rotateZ(angle) {
  9873. return this.rotateOnAxis(_zAxis, angle);
  9874. }
  9875. translateOnAxis(axis, distance) {
  9876. // translate object by distance along axis in object space
  9877. // axis is assumed to be normalized
  9878. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  9879. this.position.add(_v1$4.multiplyScalar(distance));
  9880. return this;
  9881. }
  9882. translateX(distance) {
  9883. return this.translateOnAxis(_xAxis, distance);
  9884. }
  9885. translateY(distance) {
  9886. return this.translateOnAxis(_yAxis, distance);
  9887. }
  9888. translateZ(distance) {
  9889. return this.translateOnAxis(_zAxis, distance);
  9890. }
  9891. localToWorld(vector) {
  9892. return vector.applyMatrix4(this.matrixWorld);
  9893. }
  9894. worldToLocal(vector) {
  9895. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  9896. }
  9897. lookAt(x, y, z) {
  9898. // This method does not support objects having non-uniformly-scaled parent(s)
  9899. if (x.isVector3) {
  9900. _target.copy(x);
  9901. } else {
  9902. _target.set(x, y, z);
  9903. }
  9904. const parent = this.parent;
  9905. this.updateWorldMatrix(true, false);
  9906. _position$3.setFromMatrixPosition(this.matrixWorld);
  9907. if (this.isCamera || this.isLight) {
  9908. _m1$1.lookAt(_position$3, _target, this.up);
  9909. } else {
  9910. _m1$1.lookAt(_target, _position$3, this.up);
  9911. }
  9912. this.quaternion.setFromRotationMatrix(_m1$1);
  9913. if (parent) {
  9914. _m1$1.extractRotation(parent.matrixWorld);
  9915. _q1.setFromRotationMatrix(_m1$1);
  9916. this.quaternion.premultiply(_q1.invert());
  9917. }
  9918. }
  9919. add(object) {
  9920. if (arguments.length > 1) {
  9921. for (let i = 0; i < arguments.length; i++) {
  9922. this.add(arguments[i]);
  9923. }
  9924. return this;
  9925. }
  9926. if (object === this) {
  9927. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  9928. return this;
  9929. }
  9930. if (object && object.isObject3D) {
  9931. if (object.parent !== null) {
  9932. object.parent.remove(object);
  9933. }
  9934. object.parent = this;
  9935. this.children.push(object);
  9936. object.dispatchEvent(_addedEvent);
  9937. } else {
  9938. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  9939. }
  9940. return this;
  9941. }
  9942. remove(object) {
  9943. if (arguments.length > 1) {
  9944. for (let i = 0; i < arguments.length; i++) {
  9945. this.remove(arguments[i]);
  9946. }
  9947. return this;
  9948. }
  9949. const index = this.children.indexOf(object);
  9950. if (index !== -1) {
  9951. object.parent = null;
  9952. this.children.splice(index, 1);
  9953. object.dispatchEvent(_removedEvent);
  9954. }
  9955. return this;
  9956. }
  9957. removeFromParent() {
  9958. const parent = this.parent;
  9959. if (parent !== null) {
  9960. parent.remove(this);
  9961. }
  9962. return this;
  9963. }
  9964. clear() {
  9965. for (let i = 0; i < this.children.length; i++) {
  9966. const object = this.children[i];
  9967. object.parent = null;
  9968. object.dispatchEvent(_removedEvent);
  9969. }
  9970. this.children.length = 0;
  9971. return this;
  9972. }
  9973. attach(object) {
  9974. // adds object as a child of this, while maintaining the object's world transform
  9975. this.updateWorldMatrix(true, false);
  9976. _m1$1.copy(this.matrixWorld).invert();
  9977. if (object.parent !== null) {
  9978. object.parent.updateWorldMatrix(true, false);
  9979. _m1$1.multiply(object.parent.matrixWorld);
  9980. }
  9981. object.applyMatrix4(_m1$1);
  9982. this.add(object);
  9983. object.updateWorldMatrix(false, true);
  9984. return this;
  9985. }
  9986. getObjectById(id) {
  9987. return this.getObjectByProperty('id', id);
  9988. }
  9989. getObjectByName(name) {
  9990. return this.getObjectByProperty('name', name);
  9991. }
  9992. getObjectByProperty(name, value) {
  9993. if (this[name] === value) return this;
  9994. for (let i = 0, l = this.children.length; i < l; i++) {
  9995. const child = this.children[i];
  9996. const object = child.getObjectByProperty(name, value);
  9997. if (object !== undefined) {
  9998. return object;
  9999. }
  10000. }
  10001. return undefined;
  10002. }
  10003. getWorldPosition(target) {
  10004. this.updateWorldMatrix(true, false);
  10005. return target.setFromMatrixPosition(this.matrixWorld);
  10006. }
  10007. getWorldQuaternion(target) {
  10008. this.updateWorldMatrix(true, false);
  10009. this.matrixWorld.decompose(_position$3, target, _scale$2);
  10010. return target;
  10011. }
  10012. getWorldScale(target) {
  10013. this.updateWorldMatrix(true, false);
  10014. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  10015. return target;
  10016. }
  10017. getWorldDirection(target) {
  10018. this.updateWorldMatrix(true, false);
  10019. const e = this.matrixWorld.elements;
  10020. return target.set(e[8], e[9], e[10]).normalize();
  10021. }
  10022. raycast() {}
  10023. traverse(callback) {
  10024. callback(this);
  10025. const children = this.children;
  10026. for (let i = 0, l = children.length; i < l; i++) {
  10027. children[i].traverse(callback);
  10028. }
  10029. }
  10030. traverseVisible(callback) {
  10031. if (this.visible === false) return;
  10032. callback(this);
  10033. const children = this.children;
  10034. for (let i = 0, l = children.length; i < l; i++) {
  10035. children[i].traverseVisible(callback);
  10036. }
  10037. }
  10038. traverseAncestors(callback) {
  10039. const parent = this.parent;
  10040. if (parent !== null) {
  10041. callback(parent);
  10042. parent.traverseAncestors(callback);
  10043. }
  10044. }
  10045. updateMatrix() {
  10046. this.matrix.compose(this.position, this.quaternion, this.scale);
  10047. this.matrixWorldNeedsUpdate = true;
  10048. }
  10049. updateMatrixWorld(force) {
  10050. if (this.matrixAutoUpdate) this.updateMatrix();
  10051. if (this.matrixWorldNeedsUpdate || force) {
  10052. if (this.parent === null) {
  10053. this.matrixWorld.copy(this.matrix);
  10054. } else {
  10055. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10056. }
  10057. this.matrixWorldNeedsUpdate = false;
  10058. force = true;
  10059. } // update children
  10060. const children = this.children;
  10061. for (let i = 0, l = children.length; i < l; i++) {
  10062. children[i].updateMatrixWorld(force);
  10063. }
  10064. }
  10065. updateWorldMatrix(updateParents, updateChildren) {
  10066. const parent = this.parent;
  10067. if (updateParents === true && parent !== null) {
  10068. parent.updateWorldMatrix(true, false);
  10069. }
  10070. if (this.matrixAutoUpdate) this.updateMatrix();
  10071. if (this.parent === null) {
  10072. this.matrixWorld.copy(this.matrix);
  10073. } else {
  10074. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10075. } // update children
  10076. if (updateChildren === true) {
  10077. const children = this.children;
  10078. for (let i = 0, l = children.length; i < l; i++) {
  10079. children[i].updateWorldMatrix(false, true);
  10080. }
  10081. }
  10082. }
  10083. toJSON(meta) {
  10084. // meta is a string when called from JSON.stringify
  10085. const isRootObject = meta === undefined || typeof meta === 'string';
  10086. const output = {}; // meta is a hash used to collect geometries, materials.
  10087. // not providing it implies that this is the root object
  10088. // being serialized.
  10089. if (isRootObject) {
  10090. // initialize meta obj
  10091. meta = {
  10092. geometries: {},
  10093. materials: {},
  10094. textures: {},
  10095. images: {},
  10096. shapes: {},
  10097. skeletons: {},
  10098. animations: {}
  10099. };
  10100. output.metadata = {
  10101. version: 4.5,
  10102. type: 'Object',
  10103. generator: 'Object3D.toJSON'
  10104. };
  10105. } // standard Object3D serialization
  10106. const object = {};
  10107. object.uuid = this.uuid;
  10108. object.type = this.type;
  10109. if (this.name !== '') object.name = this.name;
  10110. if (this.castShadow === true) object.castShadow = true;
  10111. if (this.receiveShadow === true) object.receiveShadow = true;
  10112. if (this.visible === false) object.visible = false;
  10113. if (this.frustumCulled === false) object.frustumCulled = false;
  10114. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  10115. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  10116. object.layers = this.layers.mask;
  10117. object.matrix = this.matrix.toArray();
  10118. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  10119. if (this.isInstancedMesh) {
  10120. object.type = 'InstancedMesh';
  10121. object.count = this.count;
  10122. object.instanceMatrix = this.instanceMatrix.toJSON();
  10123. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  10124. } //
  10125. function serialize(library, element) {
  10126. if (library[element.uuid] === undefined) {
  10127. library[element.uuid] = element.toJSON(meta);
  10128. }
  10129. return element.uuid;
  10130. }
  10131. if (this.isScene) {
  10132. if (this.background) {
  10133. if (this.background.isColor) {
  10134. object.background = this.background.toJSON();
  10135. } else if (this.background.isTexture) {
  10136. object.background = this.background.toJSON(meta).uuid;
  10137. }
  10138. }
  10139. if (this.environment && this.environment.isTexture) {
  10140. object.environment = this.environment.toJSON(meta).uuid;
  10141. }
  10142. } else if (this.isMesh || this.isLine || this.isPoints) {
  10143. object.geometry = serialize(meta.geometries, this.geometry);
  10144. const parameters = this.geometry.parameters;
  10145. if (parameters !== undefined && parameters.shapes !== undefined) {
  10146. const shapes = parameters.shapes;
  10147. if (Array.isArray(shapes)) {
  10148. for (let i = 0, l = shapes.length; i < l; i++) {
  10149. const shape = shapes[i];
  10150. serialize(meta.shapes, shape);
  10151. }
  10152. } else {
  10153. serialize(meta.shapes, shapes);
  10154. }
  10155. }
  10156. }
  10157. if (this.isSkinnedMesh) {
  10158. object.bindMode = this.bindMode;
  10159. object.bindMatrix = this.bindMatrix.toArray();
  10160. if (this.skeleton !== undefined) {
  10161. serialize(meta.skeletons, this.skeleton);
  10162. object.skeleton = this.skeleton.uuid;
  10163. }
  10164. }
  10165. if (this.material !== undefined) {
  10166. if (Array.isArray(this.material)) {
  10167. const uuids = [];
  10168. for (let i = 0, l = this.material.length; i < l; i++) {
  10169. uuids.push(serialize(meta.materials, this.material[i]));
  10170. }
  10171. object.material = uuids;
  10172. } else {
  10173. object.material = serialize(meta.materials, this.material);
  10174. }
  10175. } //
  10176. if (this.children.length > 0) {
  10177. object.children = [];
  10178. for (let i = 0; i < this.children.length; i++) {
  10179. object.children.push(this.children[i].toJSON(meta).object);
  10180. }
  10181. } //
  10182. if (this.animations.length > 0) {
  10183. object.animations = [];
  10184. for (let i = 0; i < this.animations.length; i++) {
  10185. const animation = this.animations[i];
  10186. object.animations.push(serialize(meta.animations, animation));
  10187. }
  10188. }
  10189. if (isRootObject) {
  10190. const geometries = extractFromCache(meta.geometries);
  10191. const materials = extractFromCache(meta.materials);
  10192. const textures = extractFromCache(meta.textures);
  10193. const images = extractFromCache(meta.images);
  10194. const shapes = extractFromCache(meta.shapes);
  10195. const skeletons = extractFromCache(meta.skeletons);
  10196. const animations = extractFromCache(meta.animations);
  10197. if (geometries.length > 0) output.geometries = geometries;
  10198. if (materials.length > 0) output.materials = materials;
  10199. if (textures.length > 0) output.textures = textures;
  10200. if (images.length > 0) output.images = images;
  10201. if (shapes.length > 0) output.shapes = shapes;
  10202. if (skeletons.length > 0) output.skeletons = skeletons;
  10203. if (animations.length > 0) output.animations = animations;
  10204. }
  10205. output.object = object;
  10206. return output; // extract data from the cache hash
  10207. // remove metadata on each item
  10208. // and return as array
  10209. function extractFromCache(cache) {
  10210. const values = [];
  10211. for (const key in cache) {
  10212. const data = cache[key];
  10213. delete data.metadata;
  10214. values.push(data);
  10215. }
  10216. return values;
  10217. }
  10218. }
  10219. clone(recursive) {
  10220. return new this.constructor().copy(this, recursive);
  10221. }
  10222. copy(source, recursive = true) {
  10223. this.name = source.name;
  10224. this.up.copy(source.up);
  10225. this.position.copy(source.position);
  10226. this.rotation.order = source.rotation.order;
  10227. this.quaternion.copy(source.quaternion);
  10228. this.scale.copy(source.scale);
  10229. this.matrix.copy(source.matrix);
  10230. this.matrixWorld.copy(source.matrixWorld);
  10231. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10232. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10233. this.layers.mask = source.layers.mask;
  10234. this.visible = source.visible;
  10235. this.castShadow = source.castShadow;
  10236. this.receiveShadow = source.receiveShadow;
  10237. this.frustumCulled = source.frustumCulled;
  10238. this.renderOrder = source.renderOrder;
  10239. this.userData = JSON.parse(JSON.stringify(source.userData));
  10240. if (recursive === true) {
  10241. for (let i = 0; i < source.children.length; i++) {
  10242. const child = source.children[i];
  10243. this.add(child.clone());
  10244. }
  10245. }
  10246. return this;
  10247. }
  10248. }
  10249. Object3D.DefaultUp = new Vector3(0, 1, 0);
  10250. Object3D.DefaultMatrixAutoUpdate = true;
  10251. Object3D.prototype.isObject3D = true;
  10252. const _v0$1 = /*@__PURE__*/new Vector3();
  10253. const _v1$3 = /*@__PURE__*/new Vector3();
  10254. const _v2$2 = /*@__PURE__*/new Vector3();
  10255. const _v3$1 = /*@__PURE__*/new Vector3();
  10256. const _vab = /*@__PURE__*/new Vector3();
  10257. const _vac = /*@__PURE__*/new Vector3();
  10258. const _vbc = /*@__PURE__*/new Vector3();
  10259. const _vap = /*@__PURE__*/new Vector3();
  10260. const _vbp = /*@__PURE__*/new Vector3();
  10261. const _vcp = /*@__PURE__*/new Vector3();
  10262. class Triangle {
  10263. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  10264. this.a = a;
  10265. this.b = b;
  10266. this.c = c;
  10267. }
  10268. static getNormal(a, b, c, target) {
  10269. target.subVectors(c, b);
  10270. _v0$1.subVectors(a, b);
  10271. target.cross(_v0$1);
  10272. const targetLengthSq = target.lengthSq();
  10273. if (targetLengthSq > 0) {
  10274. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  10275. }
  10276. return target.set(0, 0, 0);
  10277. } // static/instance method to calculate barycentric coordinates
  10278. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10279. static getBarycoord(point, a, b, c, target) {
  10280. _v0$1.subVectors(c, a);
  10281. _v1$3.subVectors(b, a);
  10282. _v2$2.subVectors(point, a);
  10283. const dot00 = _v0$1.dot(_v0$1);
  10284. const dot01 = _v0$1.dot(_v1$3);
  10285. const dot02 = _v0$1.dot(_v2$2);
  10286. const dot11 = _v1$3.dot(_v1$3);
  10287. const dot12 = _v1$3.dot(_v2$2);
  10288. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  10289. if (denom === 0) {
  10290. // arbitrary location outside of triangle?
  10291. // not sure if this is the best idea, maybe should be returning undefined
  10292. return target.set(-2, -1, -1);
  10293. }
  10294. const invDenom = 1 / denom;
  10295. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  10296. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  10297. return target.set(1 - u - v, v, u);
  10298. }
  10299. static containsPoint(point, a, b, c) {
  10300. this.getBarycoord(point, a, b, c, _v3$1);
  10301. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  10302. }
  10303. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  10304. this.getBarycoord(point, p1, p2, p3, _v3$1);
  10305. target.set(0, 0);
  10306. target.addScaledVector(uv1, _v3$1.x);
  10307. target.addScaledVector(uv2, _v3$1.y);
  10308. target.addScaledVector(uv3, _v3$1.z);
  10309. return target;
  10310. }
  10311. static isFrontFacing(a, b, c, direction) {
  10312. _v0$1.subVectors(c, b);
  10313. _v1$3.subVectors(a, b); // strictly front facing
  10314. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  10315. }
  10316. set(a, b, c) {
  10317. this.a.copy(a);
  10318. this.b.copy(b);
  10319. this.c.copy(c);
  10320. return this;
  10321. }
  10322. setFromPointsAndIndices(points, i0, i1, i2) {
  10323. this.a.copy(points[i0]);
  10324. this.b.copy(points[i1]);
  10325. this.c.copy(points[i2]);
  10326. return this;
  10327. }
  10328. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  10329. this.a.fromBufferAttribute(attribute, i0);
  10330. this.b.fromBufferAttribute(attribute, i1);
  10331. this.c.fromBufferAttribute(attribute, i2);
  10332. return this;
  10333. }
  10334. clone() {
  10335. return new this.constructor().copy(this);
  10336. }
  10337. copy(triangle) {
  10338. this.a.copy(triangle.a);
  10339. this.b.copy(triangle.b);
  10340. this.c.copy(triangle.c);
  10341. return this;
  10342. }
  10343. getArea() {
  10344. _v0$1.subVectors(this.c, this.b);
  10345. _v1$3.subVectors(this.a, this.b);
  10346. return _v0$1.cross(_v1$3).length() * 0.5;
  10347. }
  10348. getMidpoint(target) {
  10349. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  10350. }
  10351. getNormal(target) {
  10352. return Triangle.getNormal(this.a, this.b, this.c, target);
  10353. }
  10354. getPlane(target) {
  10355. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  10356. }
  10357. getBarycoord(point, target) {
  10358. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  10359. }
  10360. getUV(point, uv1, uv2, uv3, target) {
  10361. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  10362. }
  10363. containsPoint(point) {
  10364. return Triangle.containsPoint(point, this.a, this.b, this.c);
  10365. }
  10366. isFrontFacing(direction) {
  10367. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  10368. }
  10369. intersectsBox(box) {
  10370. return box.intersectsTriangle(this);
  10371. }
  10372. closestPointToPoint(p, target) {
  10373. const a = this.a,
  10374. b = this.b,
  10375. c = this.c;
  10376. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  10377. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  10378. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  10379. // basically, we're distinguishing which of the voronoi regions of the triangle
  10380. // the point lies in with the minimum amount of redundant computation.
  10381. _vab.subVectors(b, a);
  10382. _vac.subVectors(c, a);
  10383. _vap.subVectors(p, a);
  10384. const d1 = _vab.dot(_vap);
  10385. const d2 = _vac.dot(_vap);
  10386. if (d1 <= 0 && d2 <= 0) {
  10387. // vertex region of A; barycentric coords (1, 0, 0)
  10388. return target.copy(a);
  10389. }
  10390. _vbp.subVectors(p, b);
  10391. const d3 = _vab.dot(_vbp);
  10392. const d4 = _vac.dot(_vbp);
  10393. if (d3 >= 0 && d4 <= d3) {
  10394. // vertex region of B; barycentric coords (0, 1, 0)
  10395. return target.copy(b);
  10396. }
  10397. const vc = d1 * d4 - d3 * d2;
  10398. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  10399. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  10400. return target.copy(a).addScaledVector(_vab, v);
  10401. }
  10402. _vcp.subVectors(p, c);
  10403. const d5 = _vab.dot(_vcp);
  10404. const d6 = _vac.dot(_vcp);
  10405. if (d6 >= 0 && d5 <= d6) {
  10406. // vertex region of C; barycentric coords (0, 0, 1)
  10407. return target.copy(c);
  10408. }
  10409. const vb = d5 * d2 - d1 * d6;
  10410. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  10411. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  10412. return target.copy(a).addScaledVector(_vac, w);
  10413. }
  10414. const va = d3 * d6 - d5 * d4;
  10415. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  10416. _vbc.subVectors(c, b);
  10417. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  10418. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  10419. } // face region
  10420. const denom = 1 / (va + vb + vc); // u = va * denom
  10421. v = vb * denom;
  10422. w = vc * denom;
  10423. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  10424. }
  10425. equals(triangle) {
  10426. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  10427. }
  10428. }
  10429. let materialId = 0;
  10430. class Material extends EventDispatcher {
  10431. constructor() {
  10432. super();
  10433. Object.defineProperty(this, 'id', {
  10434. value: materialId++
  10435. });
  10436. this.uuid = generateUUID();
  10437. this.name = '';
  10438. this.type = 'Material';
  10439. this.fog = true;
  10440. this.blending = NormalBlending;
  10441. this.side = FrontSide;
  10442. this.vertexColors = false;
  10443. this.opacity = 1;
  10444. this.format = RGBAFormat;
  10445. this.transparent = false;
  10446. this.blendSrc = SrcAlphaFactor;
  10447. this.blendDst = OneMinusSrcAlphaFactor;
  10448. this.blendEquation = AddEquation;
  10449. this.blendSrcAlpha = null;
  10450. this.blendDstAlpha = null;
  10451. this.blendEquationAlpha = null;
  10452. this.depthFunc = LessEqualDepth;
  10453. this.depthTest = true;
  10454. this.depthWrite = true;
  10455. this.stencilWriteMask = 0xff;
  10456. this.stencilFunc = AlwaysStencilFunc;
  10457. this.stencilRef = 0;
  10458. this.stencilFuncMask = 0xff;
  10459. this.stencilFail = KeepStencilOp;
  10460. this.stencilZFail = KeepStencilOp;
  10461. this.stencilZPass = KeepStencilOp;
  10462. this.stencilWrite = false;
  10463. this.clippingPlanes = null;
  10464. this.clipIntersection = false;
  10465. this.clipShadows = false;
  10466. this.shadowSide = null;
  10467. this.colorWrite = true;
  10468. this.precision = null; // override the renderer's default precision for this material
  10469. this.polygonOffset = false;
  10470. this.polygonOffsetFactor = 0;
  10471. this.polygonOffsetUnits = 0;
  10472. this.dithering = false;
  10473. this.alphaToCoverage = false;
  10474. this.premultipliedAlpha = false;
  10475. this.visible = true;
  10476. this.toneMapped = true;
  10477. this.userData = {};
  10478. this.version = 0;
  10479. this._alphaTest = 0;
  10480. }
  10481. get alphaTest() {
  10482. return this._alphaTest;
  10483. }
  10484. set alphaTest(value) {
  10485. if (this._alphaTest > 0 !== value > 0) {
  10486. this.version++;
  10487. }
  10488. this._alphaTest = value;
  10489. }
  10490. onBuild() {}
  10491. onBeforeRender() {}
  10492. onBeforeCompile() {}
  10493. customProgramCacheKey() {
  10494. return this.onBeforeCompile.toString();
  10495. }
  10496. setValues(values) {
  10497. if (values === undefined) return;
  10498. for (const key in values) {
  10499. const newValue = values[key];
  10500. if (newValue === undefined) {
  10501. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  10502. continue;
  10503. } // for backward compatability if shading is set in the constructor
  10504. if (key === 'shading') {
  10505. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  10506. this.flatShading = newValue === FlatShading ? true : false;
  10507. continue;
  10508. }
  10509. const currentValue = this[key];
  10510. if (currentValue === undefined) {
  10511. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  10512. continue;
  10513. }
  10514. if (currentValue && currentValue.isColor) {
  10515. currentValue.set(newValue);
  10516. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  10517. currentValue.copy(newValue);
  10518. } else {
  10519. this[key] = newValue;
  10520. }
  10521. }
  10522. }
  10523. toJSON(meta) {
  10524. const isRoot = meta === undefined || typeof meta === 'string';
  10525. if (isRoot) {
  10526. meta = {
  10527. textures: {},
  10528. images: {}
  10529. };
  10530. }
  10531. const data = {
  10532. metadata: {
  10533. version: 4.5,
  10534. type: 'Material',
  10535. generator: 'Material.toJSON'
  10536. }
  10537. }; // standard Material serialization
  10538. data.uuid = this.uuid;
  10539. data.type = this.type;
  10540. if (this.name !== '') data.name = this.name;
  10541. if (this.color && this.color.isColor) data.color = this.color.getHex();
  10542. if (this.roughness !== undefined) data.roughness = this.roughness;
  10543. if (this.metalness !== undefined) data.metalness = this.metalness;
  10544. if (this.sheen !== undefined) data.sheen = this.sheen;
  10545. if (this.sheenTint && this.sheenTint.isColor) data.sheenTint = this.sheenTint.getHex();
  10546. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  10547. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  10548. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  10549. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  10550. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  10551. if (this.specularTint && this.specularTint.isColor) data.specularTint = this.specularTint.getHex();
  10552. if (this.shininess !== undefined) data.shininess = this.shininess;
  10553. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  10554. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  10555. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  10556. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  10557. }
  10558. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  10559. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  10560. }
  10561. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  10562. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  10563. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10564. }
  10565. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  10566. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  10567. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  10568. if (this.lightMap && this.lightMap.isTexture) {
  10569. data.lightMap = this.lightMap.toJSON(meta).uuid;
  10570. data.lightMapIntensity = this.lightMapIntensity;
  10571. }
  10572. if (this.aoMap && this.aoMap.isTexture) {
  10573. data.aoMap = this.aoMap.toJSON(meta).uuid;
  10574. data.aoMapIntensity = this.aoMapIntensity;
  10575. }
  10576. if (this.bumpMap && this.bumpMap.isTexture) {
  10577. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  10578. data.bumpScale = this.bumpScale;
  10579. }
  10580. if (this.normalMap && this.normalMap.isTexture) {
  10581. data.normalMap = this.normalMap.toJSON(meta).uuid;
  10582. data.normalMapType = this.normalMapType;
  10583. data.normalScale = this.normalScale.toArray();
  10584. }
  10585. if (this.displacementMap && this.displacementMap.isTexture) {
  10586. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  10587. data.displacementScale = this.displacementScale;
  10588. data.displacementBias = this.displacementBias;
  10589. }
  10590. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  10591. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  10592. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  10593. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  10594. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  10595. if (this.specularTintMap && this.specularTintMap.isTexture) data.specularTintMap = this.specularTintMap.toJSON(meta).uuid;
  10596. if (this.envMap && this.envMap.isTexture) {
  10597. data.envMap = this.envMap.toJSON(meta).uuid;
  10598. if (this.combine !== undefined) data.combine = this.combine;
  10599. }
  10600. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  10601. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  10602. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  10603. if (this.gradientMap && this.gradientMap.isTexture) {
  10604. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  10605. }
  10606. if (this.transmission !== undefined) data.transmission = this.transmission;
  10607. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  10608. if (this.thickness !== undefined) data.thickness = this.thickness;
  10609. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  10610. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  10611. if (this.attenuationTint !== undefined) data.attenuationTint = this.attenuationTint.getHex();
  10612. if (this.size !== undefined) data.size = this.size;
  10613. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  10614. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  10615. if (this.blending !== NormalBlending) data.blending = this.blending;
  10616. if (this.side !== FrontSide) data.side = this.side;
  10617. if (this.vertexColors) data.vertexColors = true;
  10618. if (this.opacity < 1) data.opacity = this.opacity;
  10619. if (this.format !== RGBAFormat) data.format = this.format;
  10620. if (this.transparent === true) data.transparent = this.transparent;
  10621. data.depthFunc = this.depthFunc;
  10622. data.depthTest = this.depthTest;
  10623. data.depthWrite = this.depthWrite;
  10624. data.colorWrite = this.colorWrite;
  10625. data.stencilWrite = this.stencilWrite;
  10626. data.stencilWriteMask = this.stencilWriteMask;
  10627. data.stencilFunc = this.stencilFunc;
  10628. data.stencilRef = this.stencilRef;
  10629. data.stencilFuncMask = this.stencilFuncMask;
  10630. data.stencilFail = this.stencilFail;
  10631. data.stencilZFail = this.stencilZFail;
  10632. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  10633. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  10634. if (this.polygonOffset === true) data.polygonOffset = true;
  10635. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  10636. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  10637. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  10638. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  10639. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  10640. if (this.scale !== undefined) data.scale = this.scale;
  10641. if (this.dithering === true) data.dithering = true;
  10642. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  10643. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  10644. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  10645. if (this.wireframe === true) data.wireframe = this.wireframe;
  10646. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  10647. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  10648. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  10649. if (this.flatShading === true) data.flatShading = this.flatShading;
  10650. if (this.visible === false) data.visible = false;
  10651. if (this.toneMapped === false) data.toneMapped = false;
  10652. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  10653. function extractFromCache(cache) {
  10654. const values = [];
  10655. for (const key in cache) {
  10656. const data = cache[key];
  10657. delete data.metadata;
  10658. values.push(data);
  10659. }
  10660. return values;
  10661. }
  10662. if (isRoot) {
  10663. const textures = extractFromCache(meta.textures);
  10664. const images = extractFromCache(meta.images);
  10665. if (textures.length > 0) data.textures = textures;
  10666. if (images.length > 0) data.images = images;
  10667. }
  10668. return data;
  10669. }
  10670. clone() {
  10671. return new this.constructor().copy(this);
  10672. }
  10673. copy(source) {
  10674. this.name = source.name;
  10675. this.fog = source.fog;
  10676. this.blending = source.blending;
  10677. this.side = source.side;
  10678. this.vertexColors = source.vertexColors;
  10679. this.opacity = source.opacity;
  10680. this.format = source.format;
  10681. this.transparent = source.transparent;
  10682. this.blendSrc = source.blendSrc;
  10683. this.blendDst = source.blendDst;
  10684. this.blendEquation = source.blendEquation;
  10685. this.blendSrcAlpha = source.blendSrcAlpha;
  10686. this.blendDstAlpha = source.blendDstAlpha;
  10687. this.blendEquationAlpha = source.blendEquationAlpha;
  10688. this.depthFunc = source.depthFunc;
  10689. this.depthTest = source.depthTest;
  10690. this.depthWrite = source.depthWrite;
  10691. this.stencilWriteMask = source.stencilWriteMask;
  10692. this.stencilFunc = source.stencilFunc;
  10693. this.stencilRef = source.stencilRef;
  10694. this.stencilFuncMask = source.stencilFuncMask;
  10695. this.stencilFail = source.stencilFail;
  10696. this.stencilZFail = source.stencilZFail;
  10697. this.stencilZPass = source.stencilZPass;
  10698. this.stencilWrite = source.stencilWrite;
  10699. const srcPlanes = source.clippingPlanes;
  10700. let dstPlanes = null;
  10701. if (srcPlanes !== null) {
  10702. const n = srcPlanes.length;
  10703. dstPlanes = new Array(n);
  10704. for (let i = 0; i !== n; ++i) {
  10705. dstPlanes[i] = srcPlanes[i].clone();
  10706. }
  10707. }
  10708. this.clippingPlanes = dstPlanes;
  10709. this.clipIntersection = source.clipIntersection;
  10710. this.clipShadows = source.clipShadows;
  10711. this.shadowSide = source.shadowSide;
  10712. this.colorWrite = source.colorWrite;
  10713. this.precision = source.precision;
  10714. this.polygonOffset = source.polygonOffset;
  10715. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10716. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10717. this.dithering = source.dithering;
  10718. this.alphaTest = source.alphaTest;
  10719. this.alphaToCoverage = source.alphaToCoverage;
  10720. this.premultipliedAlpha = source.premultipliedAlpha;
  10721. this.visible = source.visible;
  10722. this.toneMapped = source.toneMapped;
  10723. this.userData = JSON.parse(JSON.stringify(source.userData));
  10724. return this;
  10725. }
  10726. dispose() {
  10727. this.dispatchEvent({
  10728. type: 'dispose'
  10729. });
  10730. }
  10731. set needsUpdate(value) {
  10732. if (value === true) this.version++;
  10733. }
  10734. }
  10735. Material.prototype.isMaterial = true;
  10736. const _colorKeywords = {
  10737. 'aliceblue': 0xF0F8FF,
  10738. 'antiquewhite': 0xFAEBD7,
  10739. 'aqua': 0x00FFFF,
  10740. 'aquamarine': 0x7FFFD4,
  10741. 'azure': 0xF0FFFF,
  10742. 'beige': 0xF5F5DC,
  10743. 'bisque': 0xFFE4C4,
  10744. 'black': 0x000000,
  10745. 'blanchedalmond': 0xFFEBCD,
  10746. 'blue': 0x0000FF,
  10747. 'blueviolet': 0x8A2BE2,
  10748. 'brown': 0xA52A2A,
  10749. 'burlywood': 0xDEB887,
  10750. 'cadetblue': 0x5F9EA0,
  10751. 'chartreuse': 0x7FFF00,
  10752. 'chocolate': 0xD2691E,
  10753. 'coral': 0xFF7F50,
  10754. 'cornflowerblue': 0x6495ED,
  10755. 'cornsilk': 0xFFF8DC,
  10756. 'crimson': 0xDC143C,
  10757. 'cyan': 0x00FFFF,
  10758. 'darkblue': 0x00008B,
  10759. 'darkcyan': 0x008B8B,
  10760. 'darkgoldenrod': 0xB8860B,
  10761. 'darkgray': 0xA9A9A9,
  10762. 'darkgreen': 0x006400,
  10763. 'darkgrey': 0xA9A9A9,
  10764. 'darkkhaki': 0xBDB76B,
  10765. 'darkmagenta': 0x8B008B,
  10766. 'darkolivegreen': 0x556B2F,
  10767. 'darkorange': 0xFF8C00,
  10768. 'darkorchid': 0x9932CC,
  10769. 'darkred': 0x8B0000,
  10770. 'darksalmon': 0xE9967A,
  10771. 'darkseagreen': 0x8FBC8F,
  10772. 'darkslateblue': 0x483D8B,
  10773. 'darkslategray': 0x2F4F4F,
  10774. 'darkslategrey': 0x2F4F4F,
  10775. 'darkturquoise': 0x00CED1,
  10776. 'darkviolet': 0x9400D3,
  10777. 'deeppink': 0xFF1493,
  10778. 'deepskyblue': 0x00BFFF,
  10779. 'dimgray': 0x696969,
  10780. 'dimgrey': 0x696969,
  10781. 'dodgerblue': 0x1E90FF,
  10782. 'firebrick': 0xB22222,
  10783. 'floralwhite': 0xFFFAF0,
  10784. 'forestgreen': 0x228B22,
  10785. 'fuchsia': 0xFF00FF,
  10786. 'gainsboro': 0xDCDCDC,
  10787. 'ghostwhite': 0xF8F8FF,
  10788. 'gold': 0xFFD700,
  10789. 'goldenrod': 0xDAA520,
  10790. 'gray': 0x808080,
  10791. 'green': 0x008000,
  10792. 'greenyellow': 0xADFF2F,
  10793. 'grey': 0x808080,
  10794. 'honeydew': 0xF0FFF0,
  10795. 'hotpink': 0xFF69B4,
  10796. 'indianred': 0xCD5C5C,
  10797. 'indigo': 0x4B0082,
  10798. 'ivory': 0xFFFFF0,
  10799. 'khaki': 0xF0E68C,
  10800. 'lavender': 0xE6E6FA,
  10801. 'lavenderblush': 0xFFF0F5,
  10802. 'lawngreen': 0x7CFC00,
  10803. 'lemonchiffon': 0xFFFACD,
  10804. 'lightblue': 0xADD8E6,
  10805. 'lightcoral': 0xF08080,
  10806. 'lightcyan': 0xE0FFFF,
  10807. 'lightgoldenrodyellow': 0xFAFAD2,
  10808. 'lightgray': 0xD3D3D3,
  10809. 'lightgreen': 0x90EE90,
  10810. 'lightgrey': 0xD3D3D3,
  10811. 'lightpink': 0xFFB6C1,
  10812. 'lightsalmon': 0xFFA07A,
  10813. 'lightseagreen': 0x20B2AA,
  10814. 'lightskyblue': 0x87CEFA,
  10815. 'lightslategray': 0x778899,
  10816. 'lightslategrey': 0x778899,
  10817. 'lightsteelblue': 0xB0C4DE,
  10818. 'lightyellow': 0xFFFFE0,
  10819. 'lime': 0x00FF00,
  10820. 'limegreen': 0x32CD32,
  10821. 'linen': 0xFAF0E6,
  10822. 'magenta': 0xFF00FF,
  10823. 'maroon': 0x800000,
  10824. 'mediumaquamarine': 0x66CDAA,
  10825. 'mediumblue': 0x0000CD,
  10826. 'mediumorchid': 0xBA55D3,
  10827. 'mediumpurple': 0x9370DB,
  10828. 'mediumseagreen': 0x3CB371,
  10829. 'mediumslateblue': 0x7B68EE,
  10830. 'mediumspringgreen': 0x00FA9A,
  10831. 'mediumturquoise': 0x48D1CC,
  10832. 'mediumvioletred': 0xC71585,
  10833. 'midnightblue': 0x191970,
  10834. 'mintcream': 0xF5FFFA,
  10835. 'mistyrose': 0xFFE4E1,
  10836. 'moccasin': 0xFFE4B5,
  10837. 'navajowhite': 0xFFDEAD,
  10838. 'navy': 0x000080,
  10839. 'oldlace': 0xFDF5E6,
  10840. 'olive': 0x808000,
  10841. 'olivedrab': 0x6B8E23,
  10842. 'orange': 0xFFA500,
  10843. 'orangered': 0xFF4500,
  10844. 'orchid': 0xDA70D6,
  10845. 'palegoldenrod': 0xEEE8AA,
  10846. 'palegreen': 0x98FB98,
  10847. 'paleturquoise': 0xAFEEEE,
  10848. 'palevioletred': 0xDB7093,
  10849. 'papayawhip': 0xFFEFD5,
  10850. 'peachpuff': 0xFFDAB9,
  10851. 'peru': 0xCD853F,
  10852. 'pink': 0xFFC0CB,
  10853. 'plum': 0xDDA0DD,
  10854. 'powderblue': 0xB0E0E6,
  10855. 'purple': 0x800080,
  10856. 'rebeccapurple': 0x663399,
  10857. 'red': 0xFF0000,
  10858. 'rosybrown': 0xBC8F8F,
  10859. 'royalblue': 0x4169E1,
  10860. 'saddlebrown': 0x8B4513,
  10861. 'salmon': 0xFA8072,
  10862. 'sandybrown': 0xF4A460,
  10863. 'seagreen': 0x2E8B57,
  10864. 'seashell': 0xFFF5EE,
  10865. 'sienna': 0xA0522D,
  10866. 'silver': 0xC0C0C0,
  10867. 'skyblue': 0x87CEEB,
  10868. 'slateblue': 0x6A5ACD,
  10869. 'slategray': 0x708090,
  10870. 'slategrey': 0x708090,
  10871. 'snow': 0xFFFAFA,
  10872. 'springgreen': 0x00FF7F,
  10873. 'steelblue': 0x4682B4,
  10874. 'tan': 0xD2B48C,
  10875. 'teal': 0x008080,
  10876. 'thistle': 0xD8BFD8,
  10877. 'tomato': 0xFF6347,
  10878. 'turquoise': 0x40E0D0,
  10879. 'violet': 0xEE82EE,
  10880. 'wheat': 0xF5DEB3,
  10881. 'white': 0xFFFFFF,
  10882. 'whitesmoke': 0xF5F5F5,
  10883. 'yellow': 0xFFFF00,
  10884. 'yellowgreen': 0x9ACD32
  10885. };
  10886. const _hslA = {
  10887. h: 0,
  10888. s: 0,
  10889. l: 0
  10890. };
  10891. const _hslB = {
  10892. h: 0,
  10893. s: 0,
  10894. l: 0
  10895. };
  10896. function hue2rgb(p, q, t) {
  10897. if (t < 0) t += 1;
  10898. if (t > 1) t -= 1;
  10899. if (t < 1 / 6) return p + (q - p) * 6 * t;
  10900. if (t < 1 / 2) return q;
  10901. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  10902. return p;
  10903. }
  10904. function SRGBToLinear(c) {
  10905. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  10906. }
  10907. function LinearToSRGB(c) {
  10908. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  10909. }
  10910. class Color {
  10911. constructor(r, g, b) {
  10912. if (g === undefined && b === undefined) {
  10913. // r is THREE.Color, hex or string
  10914. return this.set(r);
  10915. }
  10916. return this.setRGB(r, g, b);
  10917. }
  10918. set(value) {
  10919. if (value && value.isColor) {
  10920. this.copy(value);
  10921. } else if (typeof value === 'number') {
  10922. this.setHex(value);
  10923. } else if (typeof value === 'string') {
  10924. this.setStyle(value);
  10925. }
  10926. return this;
  10927. }
  10928. setScalar(scalar) {
  10929. this.r = scalar;
  10930. this.g = scalar;
  10931. this.b = scalar;
  10932. return this;
  10933. }
  10934. setHex(hex) {
  10935. hex = Math.floor(hex);
  10936. this.r = (hex >> 16 & 255) / 255;
  10937. this.g = (hex >> 8 & 255) / 255;
  10938. this.b = (hex & 255) / 255;
  10939. return this;
  10940. }
  10941. setRGB(r, g, b) {
  10942. this.r = r;
  10943. this.g = g;
  10944. this.b = b;
  10945. return this;
  10946. }
  10947. setHSL(h, s, l) {
  10948. // h,s,l ranges are in 0.0 - 1.0
  10949. h = euclideanModulo(h, 1);
  10950. s = clamp(s, 0, 1);
  10951. l = clamp(l, 0, 1);
  10952. if (s === 0) {
  10953. this.r = this.g = this.b = l;
  10954. } else {
  10955. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  10956. const q = 2 * l - p;
  10957. this.r = hue2rgb(q, p, h + 1 / 3);
  10958. this.g = hue2rgb(q, p, h);
  10959. this.b = hue2rgb(q, p, h - 1 / 3);
  10960. }
  10961. return this;
  10962. }
  10963. setStyle(style) {
  10964. function handleAlpha(string) {
  10965. if (string === undefined) return;
  10966. if (parseFloat(string) < 1) {
  10967. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  10968. }
  10969. }
  10970. let m;
  10971. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  10972. // rgb / hsl
  10973. let color;
  10974. const name = m[1];
  10975. const components = m[2];
  10976. switch (name) {
  10977. case 'rgb':
  10978. case 'rgba':
  10979. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  10980. // rgb(255,0,0) rgba(255,0,0,0.5)
  10981. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  10982. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  10983. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  10984. handleAlpha(color[4]);
  10985. return this;
  10986. }
  10987. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  10988. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10989. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  10990. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  10991. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  10992. handleAlpha(color[4]);
  10993. return this;
  10994. }
  10995. break;
  10996. case 'hsl':
  10997. case 'hsla':
  10998. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  10999. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11000. const h = parseFloat(color[1]) / 360;
  11001. const s = parseInt(color[2], 10) / 100;
  11002. const l = parseInt(color[3], 10) / 100;
  11003. handleAlpha(color[4]);
  11004. return this.setHSL(h, s, l);
  11005. }
  11006. break;
  11007. }
  11008. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  11009. // hex color
  11010. const hex = m[1];
  11011. const size = hex.length;
  11012. if (size === 3) {
  11013. // #ff0
  11014. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  11015. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  11016. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  11017. return this;
  11018. } else if (size === 6) {
  11019. // #ff0000
  11020. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  11021. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  11022. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  11023. return this;
  11024. }
  11025. }
  11026. if (style && style.length > 0) {
  11027. return this.setColorName(style);
  11028. }
  11029. return this;
  11030. }
  11031. setColorName(style) {
  11032. // color keywords
  11033. const hex = _colorKeywords[style.toLowerCase()];
  11034. if (hex !== undefined) {
  11035. // red
  11036. this.setHex(hex);
  11037. } else {
  11038. // unknown color
  11039. console.warn('THREE.Color: Unknown color ' + style);
  11040. }
  11041. return this;
  11042. }
  11043. clone() {
  11044. return new this.constructor(this.r, this.g, this.b);
  11045. }
  11046. copy(color) {
  11047. this.r = color.r;
  11048. this.g = color.g;
  11049. this.b = color.b;
  11050. return this;
  11051. }
  11052. copyGammaToLinear(color, gammaFactor = 2.0) {
  11053. this.r = Math.pow(color.r, gammaFactor);
  11054. this.g = Math.pow(color.g, gammaFactor);
  11055. this.b = Math.pow(color.b, gammaFactor);
  11056. return this;
  11057. }
  11058. copyLinearToGamma(color, gammaFactor = 2.0) {
  11059. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  11060. this.r = Math.pow(color.r, safeInverse);
  11061. this.g = Math.pow(color.g, safeInverse);
  11062. this.b = Math.pow(color.b, safeInverse);
  11063. return this;
  11064. }
  11065. convertGammaToLinear(gammaFactor) {
  11066. this.copyGammaToLinear(this, gammaFactor);
  11067. return this;
  11068. }
  11069. convertLinearToGamma(gammaFactor) {
  11070. this.copyLinearToGamma(this, gammaFactor);
  11071. return this;
  11072. }
  11073. copySRGBToLinear(color) {
  11074. this.r = SRGBToLinear(color.r);
  11075. this.g = SRGBToLinear(color.g);
  11076. this.b = SRGBToLinear(color.b);
  11077. return this;
  11078. }
  11079. copyLinearToSRGB(color) {
  11080. this.r = LinearToSRGB(color.r);
  11081. this.g = LinearToSRGB(color.g);
  11082. this.b = LinearToSRGB(color.b);
  11083. return this;
  11084. }
  11085. convertSRGBToLinear() {
  11086. this.copySRGBToLinear(this);
  11087. return this;
  11088. }
  11089. convertLinearToSRGB() {
  11090. this.copyLinearToSRGB(this);
  11091. return this;
  11092. }
  11093. getHex() {
  11094. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  11095. }
  11096. getHexString() {
  11097. return ('000000' + this.getHex().toString(16)).slice(-6);
  11098. }
  11099. getHSL(target) {
  11100. // h,s,l ranges are in 0.0 - 1.0
  11101. const r = this.r,
  11102. g = this.g,
  11103. b = this.b;
  11104. const max = Math.max(r, g, b);
  11105. const min = Math.min(r, g, b);
  11106. let hue, saturation;
  11107. const lightness = (min + max) / 2.0;
  11108. if (min === max) {
  11109. hue = 0;
  11110. saturation = 0;
  11111. } else {
  11112. const delta = max - min;
  11113. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  11114. switch (max) {
  11115. case r:
  11116. hue = (g - b) / delta + (g < b ? 6 : 0);
  11117. break;
  11118. case g:
  11119. hue = (b - r) / delta + 2;
  11120. break;
  11121. case b:
  11122. hue = (r - g) / delta + 4;
  11123. break;
  11124. }
  11125. hue /= 6;
  11126. }
  11127. target.h = hue;
  11128. target.s = saturation;
  11129. target.l = lightness;
  11130. return target;
  11131. }
  11132. getStyle() {
  11133. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  11134. }
  11135. offsetHSL(h, s, l) {
  11136. this.getHSL(_hslA);
  11137. _hslA.h += h;
  11138. _hslA.s += s;
  11139. _hslA.l += l;
  11140. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  11141. return this;
  11142. }
  11143. add(color) {
  11144. this.r += color.r;
  11145. this.g += color.g;
  11146. this.b += color.b;
  11147. return this;
  11148. }
  11149. addColors(color1, color2) {
  11150. this.r = color1.r + color2.r;
  11151. this.g = color1.g + color2.g;
  11152. this.b = color1.b + color2.b;
  11153. return this;
  11154. }
  11155. addScalar(s) {
  11156. this.r += s;
  11157. this.g += s;
  11158. this.b += s;
  11159. return this;
  11160. }
  11161. sub(color) {
  11162. this.r = Math.max(0, this.r - color.r);
  11163. this.g = Math.max(0, this.g - color.g);
  11164. this.b = Math.max(0, this.b - color.b);
  11165. return this;
  11166. }
  11167. multiply(color) {
  11168. this.r *= color.r;
  11169. this.g *= color.g;
  11170. this.b *= color.b;
  11171. return this;
  11172. }
  11173. multiplyScalar(s) {
  11174. this.r *= s;
  11175. this.g *= s;
  11176. this.b *= s;
  11177. return this;
  11178. }
  11179. lerp(color, alpha) {
  11180. this.r += (color.r - this.r) * alpha;
  11181. this.g += (color.g - this.g) * alpha;
  11182. this.b += (color.b - this.b) * alpha;
  11183. return this;
  11184. }
  11185. lerpColors(color1, color2, alpha) {
  11186. this.r = color1.r + (color2.r - color1.r) * alpha;
  11187. this.g = color1.g + (color2.g - color1.g) * alpha;
  11188. this.b = color1.b + (color2.b - color1.b) * alpha;
  11189. return this;
  11190. }
  11191. lerpHSL(color, alpha) {
  11192. this.getHSL(_hslA);
  11193. color.getHSL(_hslB);
  11194. const h = lerp(_hslA.h, _hslB.h, alpha);
  11195. const s = lerp(_hslA.s, _hslB.s, alpha);
  11196. const l = lerp(_hslA.l, _hslB.l, alpha);
  11197. this.setHSL(h, s, l);
  11198. return this;
  11199. }
  11200. equals(c) {
  11201. return c.r === this.r && c.g === this.g && c.b === this.b;
  11202. }
  11203. fromArray(array, offset = 0) {
  11204. this.r = array[offset];
  11205. this.g = array[offset + 1];
  11206. this.b = array[offset + 2];
  11207. return this;
  11208. }
  11209. toArray(array = [], offset = 0) {
  11210. array[offset] = this.r;
  11211. array[offset + 1] = this.g;
  11212. array[offset + 2] = this.b;
  11213. return array;
  11214. }
  11215. fromBufferAttribute(attribute, index) {
  11216. this.r = attribute.getX(index);
  11217. this.g = attribute.getY(index);
  11218. this.b = attribute.getZ(index);
  11219. if (attribute.normalized === true) {
  11220. // assuming Uint8Array
  11221. this.r /= 255;
  11222. this.g /= 255;
  11223. this.b /= 255;
  11224. }
  11225. return this;
  11226. }
  11227. toJSON() {
  11228. return this.getHex();
  11229. }
  11230. }
  11231. Color.NAMES = _colorKeywords;
  11232. Color.prototype.isColor = true;
  11233. Color.prototype.r = 1;
  11234. Color.prototype.g = 1;
  11235. Color.prototype.b = 1;
  11236. /**
  11237. * parameters = {
  11238. * color: <hex>,
  11239. * opacity: <float>,
  11240. * map: new THREE.Texture( <Image> ),
  11241. *
  11242. * lightMap: new THREE.Texture( <Image> ),
  11243. * lightMapIntensity: <float>
  11244. *
  11245. * aoMap: new THREE.Texture( <Image> ),
  11246. * aoMapIntensity: <float>
  11247. *
  11248. * specularMap: new THREE.Texture( <Image> ),
  11249. *
  11250. * alphaMap: new THREE.Texture( <Image> ),
  11251. *
  11252. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  11253. * combine: THREE.Multiply,
  11254. * reflectivity: <float>,
  11255. * refractionRatio: <float>,
  11256. *
  11257. * depthTest: <bool>,
  11258. * depthWrite: <bool>,
  11259. *
  11260. * wireframe: <boolean>,
  11261. * wireframeLinewidth: <float>,
  11262. * }
  11263. */
  11264. class MeshBasicMaterial extends Material {
  11265. constructor(parameters) {
  11266. super();
  11267. this.type = 'MeshBasicMaterial';
  11268. this.color = new Color(0xffffff); // emissive
  11269. this.map = null;
  11270. this.lightMap = null;
  11271. this.lightMapIntensity = 1.0;
  11272. this.aoMap = null;
  11273. this.aoMapIntensity = 1.0;
  11274. this.specularMap = null;
  11275. this.alphaMap = null;
  11276. this.envMap = null;
  11277. this.combine = MultiplyOperation;
  11278. this.reflectivity = 1;
  11279. this.refractionRatio = 0.98;
  11280. this.wireframe = false;
  11281. this.wireframeLinewidth = 1;
  11282. this.wireframeLinecap = 'round';
  11283. this.wireframeLinejoin = 'round';
  11284. this.setValues(parameters);
  11285. }
  11286. copy(source) {
  11287. super.copy(source);
  11288. this.color.copy(source.color);
  11289. this.map = source.map;
  11290. this.lightMap = source.lightMap;
  11291. this.lightMapIntensity = source.lightMapIntensity;
  11292. this.aoMap = source.aoMap;
  11293. this.aoMapIntensity = source.aoMapIntensity;
  11294. this.specularMap = source.specularMap;
  11295. this.alphaMap = source.alphaMap;
  11296. this.envMap = source.envMap;
  11297. this.combine = source.combine;
  11298. this.reflectivity = source.reflectivity;
  11299. this.refractionRatio = source.refractionRatio;
  11300. this.wireframe = source.wireframe;
  11301. this.wireframeLinewidth = source.wireframeLinewidth;
  11302. this.wireframeLinecap = source.wireframeLinecap;
  11303. this.wireframeLinejoin = source.wireframeLinejoin;
  11304. return this;
  11305. }
  11306. }
  11307. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11308. const _vector$9 = /*@__PURE__*/new Vector3();
  11309. const _vector2$1 = /*@__PURE__*/new Vector2();
  11310. class BufferAttribute {
  11311. constructor(array, itemSize, normalized) {
  11312. if (Array.isArray(array)) {
  11313. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  11314. }
  11315. this.name = '';
  11316. this.array = array;
  11317. this.itemSize = itemSize;
  11318. this.count = array !== undefined ? array.length / itemSize : 0;
  11319. this.normalized = normalized === true;
  11320. this.usage = StaticDrawUsage;
  11321. this.updateRange = {
  11322. offset: 0,
  11323. count: -1
  11324. };
  11325. this.version = 0;
  11326. }
  11327. onUploadCallback() {}
  11328. set needsUpdate(value) {
  11329. if (value === true) this.version++;
  11330. }
  11331. setUsage(value) {
  11332. this.usage = value;
  11333. return this;
  11334. }
  11335. copy(source) {
  11336. this.name = source.name;
  11337. this.array = new source.array.constructor(source.array);
  11338. this.itemSize = source.itemSize;
  11339. this.count = source.count;
  11340. this.normalized = source.normalized;
  11341. this.usage = source.usage;
  11342. return this;
  11343. }
  11344. copyAt(index1, attribute, index2) {
  11345. index1 *= this.itemSize;
  11346. index2 *= attribute.itemSize;
  11347. for (let i = 0, l = this.itemSize; i < l; i++) {
  11348. this.array[index1 + i] = attribute.array[index2 + i];
  11349. }
  11350. return this;
  11351. }
  11352. copyArray(array) {
  11353. this.array.set(array);
  11354. return this;
  11355. }
  11356. copyColorsArray(colors) {
  11357. const array = this.array;
  11358. let offset = 0;
  11359. for (let i = 0, l = colors.length; i < l; i++) {
  11360. let color = colors[i];
  11361. if (color === undefined) {
  11362. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  11363. color = new Color();
  11364. }
  11365. array[offset++] = color.r;
  11366. array[offset++] = color.g;
  11367. array[offset++] = color.b;
  11368. }
  11369. return this;
  11370. }
  11371. copyVector2sArray(vectors) {
  11372. const array = this.array;
  11373. let offset = 0;
  11374. for (let i = 0, l = vectors.length; i < l; i++) {
  11375. let vector = vectors[i];
  11376. if (vector === undefined) {
  11377. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  11378. vector = new Vector2();
  11379. }
  11380. array[offset++] = vector.x;
  11381. array[offset++] = vector.y;
  11382. }
  11383. return this;
  11384. }
  11385. copyVector3sArray(vectors) {
  11386. const array = this.array;
  11387. let offset = 0;
  11388. for (let i = 0, l = vectors.length; i < l; i++) {
  11389. let vector = vectors[i];
  11390. if (vector === undefined) {
  11391. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  11392. vector = new Vector3();
  11393. }
  11394. array[offset++] = vector.x;
  11395. array[offset++] = vector.y;
  11396. array[offset++] = vector.z;
  11397. }
  11398. return this;
  11399. }
  11400. copyVector4sArray(vectors) {
  11401. const array = this.array;
  11402. let offset = 0;
  11403. for (let i = 0, l = vectors.length; i < l; i++) {
  11404. let vector = vectors[i];
  11405. if (vector === undefined) {
  11406. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  11407. vector = new Vector4();
  11408. }
  11409. array[offset++] = vector.x;
  11410. array[offset++] = vector.y;
  11411. array[offset++] = vector.z;
  11412. array[offset++] = vector.w;
  11413. }
  11414. return this;
  11415. }
  11416. applyMatrix3(m) {
  11417. if (this.itemSize === 2) {
  11418. for (let i = 0, l = this.count; i < l; i++) {
  11419. _vector2$1.fromBufferAttribute(this, i);
  11420. _vector2$1.applyMatrix3(m);
  11421. this.setXY(i, _vector2$1.x, _vector2$1.y);
  11422. }
  11423. } else if (this.itemSize === 3) {
  11424. for (let i = 0, l = this.count; i < l; i++) {
  11425. _vector$9.fromBufferAttribute(this, i);
  11426. _vector$9.applyMatrix3(m);
  11427. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  11428. }
  11429. }
  11430. return this;
  11431. }
  11432. applyMatrix4(m) {
  11433. for (let i = 0, l = this.count; i < l; i++) {
  11434. _vector$9.x = this.getX(i);
  11435. _vector$9.y = this.getY(i);
  11436. _vector$9.z = this.getZ(i);
  11437. _vector$9.applyMatrix4(m);
  11438. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  11439. }
  11440. return this;
  11441. }
  11442. applyNormalMatrix(m) {
  11443. for (let i = 0, l = this.count; i < l; i++) {
  11444. _vector$9.x = this.getX(i);
  11445. _vector$9.y = this.getY(i);
  11446. _vector$9.z = this.getZ(i);
  11447. _vector$9.applyNormalMatrix(m);
  11448. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  11449. }
  11450. return this;
  11451. }
  11452. transformDirection(m) {
  11453. for (let i = 0, l = this.count; i < l; i++) {
  11454. _vector$9.x = this.getX(i);
  11455. _vector$9.y = this.getY(i);
  11456. _vector$9.z = this.getZ(i);
  11457. _vector$9.transformDirection(m);
  11458. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  11459. }
  11460. return this;
  11461. }
  11462. set(value, offset = 0) {
  11463. this.array.set(value, offset);
  11464. return this;
  11465. }
  11466. getX(index) {
  11467. return this.array[index * this.itemSize];
  11468. }
  11469. setX(index, x) {
  11470. this.array[index * this.itemSize] = x;
  11471. return this;
  11472. }
  11473. getY(index) {
  11474. return this.array[index * this.itemSize + 1];
  11475. }
  11476. setY(index, y) {
  11477. this.array[index * this.itemSize + 1] = y;
  11478. return this;
  11479. }
  11480. getZ(index) {
  11481. return this.array[index * this.itemSize + 2];
  11482. }
  11483. setZ(index, z) {
  11484. this.array[index * this.itemSize + 2] = z;
  11485. return this;
  11486. }
  11487. getW(index) {
  11488. return this.array[index * this.itemSize + 3];
  11489. }
  11490. setW(index, w) {
  11491. this.array[index * this.itemSize + 3] = w;
  11492. return this;
  11493. }
  11494. setXY(index, x, y) {
  11495. index *= this.itemSize;
  11496. this.array[index + 0] = x;
  11497. this.array[index + 1] = y;
  11498. return this;
  11499. }
  11500. setXYZ(index, x, y, z) {
  11501. index *= this.itemSize;
  11502. this.array[index + 0] = x;
  11503. this.array[index + 1] = y;
  11504. this.array[index + 2] = z;
  11505. return this;
  11506. }
  11507. setXYZW(index, x, y, z, w) {
  11508. index *= this.itemSize;
  11509. this.array[index + 0] = x;
  11510. this.array[index + 1] = y;
  11511. this.array[index + 2] = z;
  11512. this.array[index + 3] = w;
  11513. return this;
  11514. }
  11515. onUpload(callback) {
  11516. this.onUploadCallback = callback;
  11517. return this;
  11518. }
  11519. clone() {
  11520. return new this.constructor(this.array, this.itemSize).copy(this);
  11521. }
  11522. toJSON() {
  11523. const data = {
  11524. itemSize: this.itemSize,
  11525. type: this.array.constructor.name,
  11526. array: Array.prototype.slice.call(this.array),
  11527. normalized: this.normalized
  11528. };
  11529. if (this.name !== '') data.name = this.name;
  11530. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  11531. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  11532. return data;
  11533. }
  11534. }
  11535. BufferAttribute.prototype.isBufferAttribute = true; //
  11536. class Int8BufferAttribute extends BufferAttribute {
  11537. constructor(array, itemSize, normalized) {
  11538. super(new Int8Array(array), itemSize, normalized);
  11539. }
  11540. }
  11541. class Uint8BufferAttribute extends BufferAttribute {
  11542. constructor(array, itemSize, normalized) {
  11543. super(new Uint8Array(array), itemSize, normalized);
  11544. }
  11545. }
  11546. class Uint8ClampedBufferAttribute extends BufferAttribute {
  11547. constructor(array, itemSize, normalized) {
  11548. super(new Uint8ClampedArray(array), itemSize, normalized);
  11549. }
  11550. }
  11551. class Int16BufferAttribute extends BufferAttribute {
  11552. constructor(array, itemSize, normalized) {
  11553. super(new Int16Array(array), itemSize, normalized);
  11554. }
  11555. }
  11556. class Uint16BufferAttribute extends BufferAttribute {
  11557. constructor(array, itemSize, normalized) {
  11558. super(new Uint16Array(array), itemSize, normalized);
  11559. }
  11560. }
  11561. class Int32BufferAttribute extends BufferAttribute {
  11562. constructor(array, itemSize, normalized) {
  11563. super(new Int32Array(array), itemSize, normalized);
  11564. }
  11565. }
  11566. class Uint32BufferAttribute extends BufferAttribute {
  11567. constructor(array, itemSize, normalized) {
  11568. super(new Uint32Array(array), itemSize, normalized);
  11569. }
  11570. }
  11571. class Float16BufferAttribute extends BufferAttribute {
  11572. constructor(array, itemSize, normalized) {
  11573. super(new Uint16Array(array), itemSize, normalized);
  11574. }
  11575. }
  11576. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  11577. class Float32BufferAttribute extends BufferAttribute {
  11578. constructor(array, itemSize, normalized) {
  11579. super(new Float32Array(array), itemSize, normalized);
  11580. }
  11581. }
  11582. class Float64BufferAttribute extends BufferAttribute {
  11583. constructor(array, itemSize, normalized) {
  11584. super(new Float64Array(array), itemSize, normalized);
  11585. }
  11586. } //
  11587. let _id = 0;
  11588. const _m1 = /*@__PURE__*/new Matrix4();
  11589. const _obj = /*@__PURE__*/new Object3D();
  11590. const _offset = /*@__PURE__*/new Vector3();
  11591. const _box$1 = /*@__PURE__*/new Box3();
  11592. const _boxMorphTargets = /*@__PURE__*/new Box3();
  11593. const _vector$8 = /*@__PURE__*/new Vector3();
  11594. class BufferGeometry extends EventDispatcher {
  11595. constructor() {
  11596. super();
  11597. Object.defineProperty(this, 'id', {
  11598. value: _id++
  11599. });
  11600. this.uuid = generateUUID();
  11601. this.name = '';
  11602. this.type = 'BufferGeometry';
  11603. this.index = null;
  11604. this.attributes = {};
  11605. this.morphAttributes = {};
  11606. this.morphTargetsRelative = false;
  11607. this.groups = [];
  11608. this.boundingBox = null;
  11609. this.boundingSphere = null;
  11610. this.drawRange = {
  11611. start: 0,
  11612. count: Infinity
  11613. };
  11614. this.userData = {};
  11615. }
  11616. getIndex() {
  11617. return this.index;
  11618. }
  11619. setIndex(index) {
  11620. if (Array.isArray(index)) {
  11621. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  11622. } else {
  11623. this.index = index;
  11624. }
  11625. return this;
  11626. }
  11627. getAttribute(name) {
  11628. return this.attributes[name];
  11629. }
  11630. setAttribute(name, attribute) {
  11631. this.attributes[name] = attribute;
  11632. return this;
  11633. }
  11634. deleteAttribute(name) {
  11635. delete this.attributes[name];
  11636. return this;
  11637. }
  11638. hasAttribute(name) {
  11639. return this.attributes[name] !== undefined;
  11640. }
  11641. addGroup(start, count, materialIndex = 0) {
  11642. this.groups.push({
  11643. start: start,
  11644. count: count,
  11645. materialIndex: materialIndex
  11646. });
  11647. }
  11648. clearGroups() {
  11649. this.groups = [];
  11650. }
  11651. setDrawRange(start, count) {
  11652. this.drawRange.start = start;
  11653. this.drawRange.count = count;
  11654. }
  11655. applyMatrix4(matrix) {
  11656. const position = this.attributes.position;
  11657. if (position !== undefined) {
  11658. position.applyMatrix4(matrix);
  11659. position.needsUpdate = true;
  11660. }
  11661. const normal = this.attributes.normal;
  11662. if (normal !== undefined) {
  11663. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  11664. normal.applyNormalMatrix(normalMatrix);
  11665. normal.needsUpdate = true;
  11666. }
  11667. const tangent = this.attributes.tangent;
  11668. if (tangent !== undefined) {
  11669. tangent.transformDirection(matrix);
  11670. tangent.needsUpdate = true;
  11671. }
  11672. if (this.boundingBox !== null) {
  11673. this.computeBoundingBox();
  11674. }
  11675. if (this.boundingSphere !== null) {
  11676. this.computeBoundingSphere();
  11677. }
  11678. return this;
  11679. }
  11680. applyQuaternion(q) {
  11681. _m1.makeRotationFromQuaternion(q);
  11682. this.applyMatrix4(_m1);
  11683. return this;
  11684. }
  11685. rotateX(angle) {
  11686. // rotate geometry around world x-axis
  11687. _m1.makeRotationX(angle);
  11688. this.applyMatrix4(_m1);
  11689. return this;
  11690. }
  11691. rotateY(angle) {
  11692. // rotate geometry around world y-axis
  11693. _m1.makeRotationY(angle);
  11694. this.applyMatrix4(_m1);
  11695. return this;
  11696. }
  11697. rotateZ(angle) {
  11698. // rotate geometry around world z-axis
  11699. _m1.makeRotationZ(angle);
  11700. this.applyMatrix4(_m1);
  11701. return this;
  11702. }
  11703. translate(x, y, z) {
  11704. // translate geometry
  11705. _m1.makeTranslation(x, y, z);
  11706. this.applyMatrix4(_m1);
  11707. return this;
  11708. }
  11709. scale(x, y, z) {
  11710. // scale geometry
  11711. _m1.makeScale(x, y, z);
  11712. this.applyMatrix4(_m1);
  11713. return this;
  11714. }
  11715. lookAt(vector) {
  11716. _obj.lookAt(vector);
  11717. _obj.updateMatrix();
  11718. this.applyMatrix4(_obj.matrix);
  11719. return this;
  11720. }
  11721. center() {
  11722. this.computeBoundingBox();
  11723. this.boundingBox.getCenter(_offset).negate();
  11724. this.translate(_offset.x, _offset.y, _offset.z);
  11725. return this;
  11726. }
  11727. setFromPoints(points) {
  11728. const position = [];
  11729. for (let i = 0, l = points.length; i < l; i++) {
  11730. const point = points[i];
  11731. position.push(point.x, point.y, point.z || 0);
  11732. }
  11733. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  11734. return this;
  11735. }
  11736. computeBoundingBox() {
  11737. if (this.boundingBox === null) {
  11738. this.boundingBox = new Box3();
  11739. }
  11740. const position = this.attributes.position;
  11741. const morphAttributesPosition = this.morphAttributes.position;
  11742. if (position && position.isGLBufferAttribute) {
  11743. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  11744. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  11745. return;
  11746. }
  11747. if (position !== undefined) {
  11748. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  11749. if (morphAttributesPosition) {
  11750. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  11751. const morphAttribute = morphAttributesPosition[i];
  11752. _box$1.setFromBufferAttribute(morphAttribute);
  11753. if (this.morphTargetsRelative) {
  11754. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  11755. this.boundingBox.expandByPoint(_vector$8);
  11756. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  11757. this.boundingBox.expandByPoint(_vector$8);
  11758. } else {
  11759. this.boundingBox.expandByPoint(_box$1.min);
  11760. this.boundingBox.expandByPoint(_box$1.max);
  11761. }
  11762. }
  11763. }
  11764. } else {
  11765. this.boundingBox.makeEmpty();
  11766. }
  11767. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  11768. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  11769. }
  11770. }
  11771. computeBoundingSphere() {
  11772. if (this.boundingSphere === null) {
  11773. this.boundingSphere = new Sphere();
  11774. }
  11775. const position = this.attributes.position;
  11776. const morphAttributesPosition = this.morphAttributes.position;
  11777. if (position && position.isGLBufferAttribute) {
  11778. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  11779. this.boundingSphere.set(new Vector3(), Infinity);
  11780. return;
  11781. }
  11782. if (position) {
  11783. // first, find the center of the bounding sphere
  11784. const center = this.boundingSphere.center;
  11785. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  11786. if (morphAttributesPosition) {
  11787. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  11788. const morphAttribute = morphAttributesPosition[i];
  11789. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  11790. if (this.morphTargetsRelative) {
  11791. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  11792. _box$1.expandByPoint(_vector$8);
  11793. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  11794. _box$1.expandByPoint(_vector$8);
  11795. } else {
  11796. _box$1.expandByPoint(_boxMorphTargets.min);
  11797. _box$1.expandByPoint(_boxMorphTargets.max);
  11798. }
  11799. }
  11800. }
  11801. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  11802. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11803. let maxRadiusSq = 0;
  11804. for (let i = 0, il = position.count; i < il; i++) {
  11805. _vector$8.fromBufferAttribute(position, i);
  11806. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  11807. } // process morph attributes if present
  11808. if (morphAttributesPosition) {
  11809. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  11810. const morphAttribute = morphAttributesPosition[i];
  11811. const morphTargetsRelative = this.morphTargetsRelative;
  11812. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  11813. _vector$8.fromBufferAttribute(morphAttribute, j);
  11814. if (morphTargetsRelative) {
  11815. _offset.fromBufferAttribute(position, j);
  11816. _vector$8.add(_offset);
  11817. }
  11818. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  11819. }
  11820. }
  11821. }
  11822. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  11823. if (isNaN(this.boundingSphere.radius)) {
  11824. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  11825. }
  11826. }
  11827. }
  11828. computeTangents() {
  11829. const index = this.index;
  11830. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  11831. // (per vertex tangents)
  11832. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  11833. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  11834. return;
  11835. }
  11836. const indices = index.array;
  11837. const positions = attributes.position.array;
  11838. const normals = attributes.normal.array;
  11839. const uvs = attributes.uv.array;
  11840. const nVertices = positions.length / 3;
  11841. if (attributes.tangent === undefined) {
  11842. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  11843. }
  11844. const tangents = attributes.tangent.array;
  11845. const tan1 = [],
  11846. tan2 = [];
  11847. for (let i = 0; i < nVertices; i++) {
  11848. tan1[i] = new Vector3();
  11849. tan2[i] = new Vector3();
  11850. }
  11851. const vA = new Vector3(),
  11852. vB = new Vector3(),
  11853. vC = new Vector3(),
  11854. uvA = new Vector2(),
  11855. uvB = new Vector2(),
  11856. uvC = new Vector2(),
  11857. sdir = new Vector3(),
  11858. tdir = new Vector3();
  11859. function handleTriangle(a, b, c) {
  11860. vA.fromArray(positions, a * 3);
  11861. vB.fromArray(positions, b * 3);
  11862. vC.fromArray(positions, c * 3);
  11863. uvA.fromArray(uvs, a * 2);
  11864. uvB.fromArray(uvs, b * 2);
  11865. uvC.fromArray(uvs, c * 2);
  11866. vB.sub(vA);
  11867. vC.sub(vA);
  11868. uvB.sub(uvA);
  11869. uvC.sub(uvA);
  11870. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  11871. if (!isFinite(r)) return;
  11872. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  11873. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  11874. tan1[a].add(sdir);
  11875. tan1[b].add(sdir);
  11876. tan1[c].add(sdir);
  11877. tan2[a].add(tdir);
  11878. tan2[b].add(tdir);
  11879. tan2[c].add(tdir);
  11880. }
  11881. let groups = this.groups;
  11882. if (groups.length === 0) {
  11883. groups = [{
  11884. start: 0,
  11885. count: indices.length
  11886. }];
  11887. }
  11888. for (let i = 0, il = groups.length; i < il; ++i) {
  11889. const group = groups[i];
  11890. const start = group.start;
  11891. const count = group.count;
  11892. for (let j = start, jl = start + count; j < jl; j += 3) {
  11893. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  11894. }
  11895. }
  11896. const tmp = new Vector3(),
  11897. tmp2 = new Vector3();
  11898. const n = new Vector3(),
  11899. n2 = new Vector3();
  11900. function handleVertex(v) {
  11901. n.fromArray(normals, v * 3);
  11902. n2.copy(n);
  11903. const t = tan1[v]; // Gram-Schmidt orthogonalize
  11904. tmp.copy(t);
  11905. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  11906. tmp2.crossVectors(n2, t);
  11907. const test = tmp2.dot(tan2[v]);
  11908. const w = test < 0.0 ? -1.0 : 1.0;
  11909. tangents[v * 4] = tmp.x;
  11910. tangents[v * 4 + 1] = tmp.y;
  11911. tangents[v * 4 + 2] = tmp.z;
  11912. tangents[v * 4 + 3] = w;
  11913. }
  11914. for (let i = 0, il = groups.length; i < il; ++i) {
  11915. const group = groups[i];
  11916. const start = group.start;
  11917. const count = group.count;
  11918. for (let j = start, jl = start + count; j < jl; j += 3) {
  11919. handleVertex(indices[j + 0]);
  11920. handleVertex(indices[j + 1]);
  11921. handleVertex(indices[j + 2]);
  11922. }
  11923. }
  11924. }
  11925. computeVertexNormals() {
  11926. const index = this.index;
  11927. const positionAttribute = this.getAttribute('position');
  11928. if (positionAttribute !== undefined) {
  11929. let normalAttribute = this.getAttribute('normal');
  11930. if (normalAttribute === undefined) {
  11931. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  11932. this.setAttribute('normal', normalAttribute);
  11933. } else {
  11934. // reset existing normals to zero
  11935. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  11936. normalAttribute.setXYZ(i, 0, 0, 0);
  11937. }
  11938. }
  11939. const pA = new Vector3(),
  11940. pB = new Vector3(),
  11941. pC = new Vector3();
  11942. const nA = new Vector3(),
  11943. nB = new Vector3(),
  11944. nC = new Vector3();
  11945. const cb = new Vector3(),
  11946. ab = new Vector3(); // indexed elements
  11947. if (index) {
  11948. for (let i = 0, il = index.count; i < il; i += 3) {
  11949. const vA = index.getX(i + 0);
  11950. const vB = index.getX(i + 1);
  11951. const vC = index.getX(i + 2);
  11952. pA.fromBufferAttribute(positionAttribute, vA);
  11953. pB.fromBufferAttribute(positionAttribute, vB);
  11954. pC.fromBufferAttribute(positionAttribute, vC);
  11955. cb.subVectors(pC, pB);
  11956. ab.subVectors(pA, pB);
  11957. cb.cross(ab);
  11958. nA.fromBufferAttribute(normalAttribute, vA);
  11959. nB.fromBufferAttribute(normalAttribute, vB);
  11960. nC.fromBufferAttribute(normalAttribute, vC);
  11961. nA.add(cb);
  11962. nB.add(cb);
  11963. nC.add(cb);
  11964. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  11965. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  11966. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  11967. }
  11968. } else {
  11969. // non-indexed elements (unconnected triangle soup)
  11970. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  11971. pA.fromBufferAttribute(positionAttribute, i + 0);
  11972. pB.fromBufferAttribute(positionAttribute, i + 1);
  11973. pC.fromBufferAttribute(positionAttribute, i + 2);
  11974. cb.subVectors(pC, pB);
  11975. ab.subVectors(pA, pB);
  11976. cb.cross(ab);
  11977. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  11978. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  11979. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  11980. }
  11981. }
  11982. this.normalizeNormals();
  11983. normalAttribute.needsUpdate = true;
  11984. }
  11985. }
  11986. merge(geometry, offset) {
  11987. if (!(geometry && geometry.isBufferGeometry)) {
  11988. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  11989. return;
  11990. }
  11991. if (offset === undefined) {
  11992. offset = 0;
  11993. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  11994. }
  11995. const attributes = this.attributes;
  11996. for (const key in attributes) {
  11997. if (geometry.attributes[key] === undefined) continue;
  11998. const attribute1 = attributes[key];
  11999. const attributeArray1 = attribute1.array;
  12000. const attribute2 = geometry.attributes[key];
  12001. const attributeArray2 = attribute2.array;
  12002. const attributeOffset = attribute2.itemSize * offset;
  12003. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  12004. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  12005. attributeArray1[j] = attributeArray2[i];
  12006. }
  12007. }
  12008. return this;
  12009. }
  12010. normalizeNormals() {
  12011. const normals = this.attributes.normal;
  12012. for (let i = 0, il = normals.count; i < il; i++) {
  12013. _vector$8.fromBufferAttribute(normals, i);
  12014. _vector$8.normalize();
  12015. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  12016. }
  12017. }
  12018. toNonIndexed() {
  12019. function convertBufferAttribute(attribute, indices) {
  12020. const array = attribute.array;
  12021. const itemSize = attribute.itemSize;
  12022. const normalized = attribute.normalized;
  12023. const array2 = new array.constructor(indices.length * itemSize);
  12024. let index = 0,
  12025. index2 = 0;
  12026. for (let i = 0, l = indices.length; i < l; i++) {
  12027. if (attribute.isInterleavedBufferAttribute) {
  12028. index = indices[i] * attribute.data.stride + attribute.offset;
  12029. } else {
  12030. index = indices[i] * itemSize;
  12031. }
  12032. for (let j = 0; j < itemSize; j++) {
  12033. array2[index2++] = array[index++];
  12034. }
  12035. }
  12036. return new BufferAttribute(array2, itemSize, normalized);
  12037. } //
  12038. if (this.index === null) {
  12039. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  12040. return this;
  12041. }
  12042. const geometry2 = new BufferGeometry();
  12043. const indices = this.index.array;
  12044. const attributes = this.attributes; // attributes
  12045. for (const name in attributes) {
  12046. const attribute = attributes[name];
  12047. const newAttribute = convertBufferAttribute(attribute, indices);
  12048. geometry2.setAttribute(name, newAttribute);
  12049. } // morph attributes
  12050. const morphAttributes = this.morphAttributes;
  12051. for (const name in morphAttributes) {
  12052. const morphArray = [];
  12053. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  12054. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  12055. const attribute = morphAttribute[i];
  12056. const newAttribute = convertBufferAttribute(attribute, indices);
  12057. morphArray.push(newAttribute);
  12058. }
  12059. geometry2.morphAttributes[name] = morphArray;
  12060. }
  12061. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  12062. const groups = this.groups;
  12063. for (let i = 0, l = groups.length; i < l; i++) {
  12064. const group = groups[i];
  12065. geometry2.addGroup(group.start, group.count, group.materialIndex);
  12066. }
  12067. return geometry2;
  12068. }
  12069. toJSON() {
  12070. const data = {
  12071. metadata: {
  12072. version: 4.5,
  12073. type: 'BufferGeometry',
  12074. generator: 'BufferGeometry.toJSON'
  12075. }
  12076. }; // standard BufferGeometry serialization
  12077. data.uuid = this.uuid;
  12078. data.type = this.type;
  12079. if (this.name !== '') data.name = this.name;
  12080. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  12081. if (this.parameters !== undefined) {
  12082. const parameters = this.parameters;
  12083. for (const key in parameters) {
  12084. if (parameters[key] !== undefined) data[key] = parameters[key];
  12085. }
  12086. return data;
  12087. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  12088. data.data = {
  12089. attributes: {}
  12090. };
  12091. const index = this.index;
  12092. if (index !== null) {
  12093. data.data.index = {
  12094. type: index.array.constructor.name,
  12095. array: Array.prototype.slice.call(index.array)
  12096. };
  12097. }
  12098. const attributes = this.attributes;
  12099. for (const key in attributes) {
  12100. const attribute = attributes[key];
  12101. data.data.attributes[key] = attribute.toJSON(data.data);
  12102. }
  12103. const morphAttributes = {};
  12104. let hasMorphAttributes = false;
  12105. for (const key in this.morphAttributes) {
  12106. const attributeArray = this.morphAttributes[key];
  12107. const array = [];
  12108. for (let i = 0, il = attributeArray.length; i < il; i++) {
  12109. const attribute = attributeArray[i];
  12110. array.push(attribute.toJSON(data.data));
  12111. }
  12112. if (array.length > 0) {
  12113. morphAttributes[key] = array;
  12114. hasMorphAttributes = true;
  12115. }
  12116. }
  12117. if (hasMorphAttributes) {
  12118. data.data.morphAttributes = morphAttributes;
  12119. data.data.morphTargetsRelative = this.morphTargetsRelative;
  12120. }
  12121. const groups = this.groups;
  12122. if (groups.length > 0) {
  12123. data.data.groups = JSON.parse(JSON.stringify(groups));
  12124. }
  12125. const boundingSphere = this.boundingSphere;
  12126. if (boundingSphere !== null) {
  12127. data.data.boundingSphere = {
  12128. center: boundingSphere.center.toArray(),
  12129. radius: boundingSphere.radius
  12130. };
  12131. }
  12132. return data;
  12133. }
  12134. clone() {
  12135. return new this.constructor().copy(this);
  12136. }
  12137. copy(source) {
  12138. // reset
  12139. this.index = null;
  12140. this.attributes = {};
  12141. this.morphAttributes = {};
  12142. this.groups = [];
  12143. this.boundingBox = null;
  12144. this.boundingSphere = null; // used for storing cloned, shared data
  12145. const data = {}; // name
  12146. this.name = source.name; // index
  12147. const index = source.index;
  12148. if (index !== null) {
  12149. this.setIndex(index.clone(data));
  12150. } // attributes
  12151. const attributes = source.attributes;
  12152. for (const name in attributes) {
  12153. const attribute = attributes[name];
  12154. this.setAttribute(name, attribute.clone(data));
  12155. } // morph attributes
  12156. const morphAttributes = source.morphAttributes;
  12157. for (const name in morphAttributes) {
  12158. const array = [];
  12159. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  12160. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  12161. array.push(morphAttribute[i].clone(data));
  12162. }
  12163. this.morphAttributes[name] = array;
  12164. }
  12165. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  12166. const groups = source.groups;
  12167. for (let i = 0, l = groups.length; i < l; i++) {
  12168. const group = groups[i];
  12169. this.addGroup(group.start, group.count, group.materialIndex);
  12170. } // bounding box
  12171. const boundingBox = source.boundingBox;
  12172. if (boundingBox !== null) {
  12173. this.boundingBox = boundingBox.clone();
  12174. } // bounding sphere
  12175. const boundingSphere = source.boundingSphere;
  12176. if (boundingSphere !== null) {
  12177. this.boundingSphere = boundingSphere.clone();
  12178. } // draw range
  12179. this.drawRange.start = source.drawRange.start;
  12180. this.drawRange.count = source.drawRange.count; // user data
  12181. this.userData = source.userData; // geometry generator parameters
  12182. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  12183. return this;
  12184. }
  12185. dispose() {
  12186. this.dispatchEvent({
  12187. type: 'dispose'
  12188. });
  12189. }
  12190. }
  12191. BufferGeometry.prototype.isBufferGeometry = true;
  12192. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  12193. const _ray$2 = /*@__PURE__*/new Ray();
  12194. const _sphere$3 = /*@__PURE__*/new Sphere();
  12195. const _vA$1 = /*@__PURE__*/new Vector3();
  12196. const _vB$1 = /*@__PURE__*/new Vector3();
  12197. const _vC$1 = /*@__PURE__*/new Vector3();
  12198. const _tempA = /*@__PURE__*/new Vector3();
  12199. const _tempB = /*@__PURE__*/new Vector3();
  12200. const _tempC = /*@__PURE__*/new Vector3();
  12201. const _morphA = /*@__PURE__*/new Vector3();
  12202. const _morphB = /*@__PURE__*/new Vector3();
  12203. const _morphC = /*@__PURE__*/new Vector3();
  12204. const _uvA$1 = /*@__PURE__*/new Vector2();
  12205. const _uvB$1 = /*@__PURE__*/new Vector2();
  12206. const _uvC$1 = /*@__PURE__*/new Vector2();
  12207. const _intersectionPoint = /*@__PURE__*/new Vector3();
  12208. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  12209. class Mesh extends Object3D {
  12210. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  12211. super();
  12212. this.type = 'Mesh';
  12213. this.geometry = geometry;
  12214. this.material = material;
  12215. this.updateMorphTargets();
  12216. }
  12217. copy(source) {
  12218. super.copy(source);
  12219. if (source.morphTargetInfluences !== undefined) {
  12220. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12221. }
  12222. if (source.morphTargetDictionary !== undefined) {
  12223. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  12224. }
  12225. this.material = source.material;
  12226. this.geometry = source.geometry;
  12227. return this;
  12228. }
  12229. updateMorphTargets() {
  12230. const geometry = this.geometry;
  12231. if (geometry.isBufferGeometry) {
  12232. const morphAttributes = geometry.morphAttributes;
  12233. const keys = Object.keys(morphAttributes);
  12234. if (keys.length > 0) {
  12235. const morphAttribute = morphAttributes[keys[0]];
  12236. if (morphAttribute !== undefined) {
  12237. this.morphTargetInfluences = [];
  12238. this.morphTargetDictionary = {};
  12239. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  12240. const name = morphAttribute[m].name || String(m);
  12241. this.morphTargetInfluences.push(0);
  12242. this.morphTargetDictionary[name] = m;
  12243. }
  12244. }
  12245. }
  12246. } else {
  12247. const morphTargets = geometry.morphTargets;
  12248. if (morphTargets !== undefined && morphTargets.length > 0) {
  12249. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  12250. }
  12251. }
  12252. }
  12253. raycast(raycaster, intersects) {
  12254. const geometry = this.geometry;
  12255. const material = this.material;
  12256. const matrixWorld = this.matrixWorld;
  12257. if (material === undefined) return; // Checking boundingSphere distance to ray
  12258. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  12259. _sphere$3.copy(geometry.boundingSphere);
  12260. _sphere$3.applyMatrix4(matrixWorld);
  12261. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  12262. _inverseMatrix$2.copy(matrixWorld).invert();
  12263. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  12264. if (geometry.boundingBox !== null) {
  12265. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  12266. }
  12267. let intersection;
  12268. if (geometry.isBufferGeometry) {
  12269. const index = geometry.index;
  12270. const position = geometry.attributes.position;
  12271. const morphPosition = geometry.morphAttributes.position;
  12272. const morphTargetsRelative = geometry.morphTargetsRelative;
  12273. const uv = geometry.attributes.uv;
  12274. const uv2 = geometry.attributes.uv2;
  12275. const groups = geometry.groups;
  12276. const drawRange = geometry.drawRange;
  12277. if (index !== null) {
  12278. // indexed buffer geometry
  12279. if (Array.isArray(material)) {
  12280. for (let i = 0, il = groups.length; i < il; i++) {
  12281. const group = groups[i];
  12282. const groupMaterial = material[group.materialIndex];
  12283. const start = Math.max(group.start, drawRange.start);
  12284. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  12285. for (let j = start, jl = end; j < jl; j += 3) {
  12286. const a = index.getX(j);
  12287. const b = index.getX(j + 1);
  12288. const c = index.getX(j + 2);
  12289. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  12290. if (intersection) {
  12291. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  12292. intersection.face.materialIndex = group.materialIndex;
  12293. intersects.push(intersection);
  12294. }
  12295. }
  12296. }
  12297. } else {
  12298. const start = Math.max(0, drawRange.start);
  12299. const end = Math.min(index.count, drawRange.start + drawRange.count);
  12300. for (let i = start, il = end; i < il; i += 3) {
  12301. const a = index.getX(i);
  12302. const b = index.getX(i + 1);
  12303. const c = index.getX(i + 2);
  12304. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  12305. if (intersection) {
  12306. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  12307. intersects.push(intersection);
  12308. }
  12309. }
  12310. }
  12311. } else if (position !== undefined) {
  12312. // non-indexed buffer geometry
  12313. if (Array.isArray(material)) {
  12314. for (let i = 0, il = groups.length; i < il; i++) {
  12315. const group = groups[i];
  12316. const groupMaterial = material[group.materialIndex];
  12317. const start = Math.max(group.start, drawRange.start);
  12318. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  12319. for (let j = start, jl = end; j < jl; j += 3) {
  12320. const a = j;
  12321. const b = j + 1;
  12322. const c = j + 2;
  12323. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  12324. if (intersection) {
  12325. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  12326. intersection.face.materialIndex = group.materialIndex;
  12327. intersects.push(intersection);
  12328. }
  12329. }
  12330. }
  12331. } else {
  12332. const start = Math.max(0, drawRange.start);
  12333. const end = Math.min(position.count, drawRange.start + drawRange.count);
  12334. for (let i = start, il = end; i < il; i += 3) {
  12335. const a = i;
  12336. const b = i + 1;
  12337. const c = i + 2;
  12338. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  12339. if (intersection) {
  12340. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  12341. intersects.push(intersection);
  12342. }
  12343. }
  12344. }
  12345. }
  12346. } else if (geometry.isGeometry) {
  12347. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  12348. }
  12349. }
  12350. }
  12351. Mesh.prototype.isMesh = true;
  12352. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  12353. let intersect;
  12354. if (material.side === BackSide) {
  12355. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  12356. } else {
  12357. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  12358. }
  12359. if (intersect === null) return null;
  12360. _intersectionPointWorld.copy(point);
  12361. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  12362. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  12363. if (distance < raycaster.near || distance > raycaster.far) return null;
  12364. return {
  12365. distance: distance,
  12366. point: _intersectionPointWorld.clone(),
  12367. object: object
  12368. };
  12369. }
  12370. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  12371. _vA$1.fromBufferAttribute(position, a);
  12372. _vB$1.fromBufferAttribute(position, b);
  12373. _vC$1.fromBufferAttribute(position, c);
  12374. const morphInfluences = object.morphTargetInfluences;
  12375. if (morphPosition && morphInfluences) {
  12376. _morphA.set(0, 0, 0);
  12377. _morphB.set(0, 0, 0);
  12378. _morphC.set(0, 0, 0);
  12379. for (let i = 0, il = morphPosition.length; i < il; i++) {
  12380. const influence = morphInfluences[i];
  12381. const morphAttribute = morphPosition[i];
  12382. if (influence === 0) continue;
  12383. _tempA.fromBufferAttribute(morphAttribute, a);
  12384. _tempB.fromBufferAttribute(morphAttribute, b);
  12385. _tempC.fromBufferAttribute(morphAttribute, c);
  12386. if (morphTargetsRelative) {
  12387. _morphA.addScaledVector(_tempA, influence);
  12388. _morphB.addScaledVector(_tempB, influence);
  12389. _morphC.addScaledVector(_tempC, influence);
  12390. } else {
  12391. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  12392. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  12393. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  12394. }
  12395. }
  12396. _vA$1.add(_morphA);
  12397. _vB$1.add(_morphB);
  12398. _vC$1.add(_morphC);
  12399. }
  12400. if (object.isSkinnedMesh) {
  12401. object.boneTransform(a, _vA$1);
  12402. object.boneTransform(b, _vB$1);
  12403. object.boneTransform(c, _vC$1);
  12404. }
  12405. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  12406. if (intersection) {
  12407. if (uv) {
  12408. _uvA$1.fromBufferAttribute(uv, a);
  12409. _uvB$1.fromBufferAttribute(uv, b);
  12410. _uvC$1.fromBufferAttribute(uv, c);
  12411. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  12412. }
  12413. if (uv2) {
  12414. _uvA$1.fromBufferAttribute(uv2, a);
  12415. _uvB$1.fromBufferAttribute(uv2, b);
  12416. _uvC$1.fromBufferAttribute(uv2, c);
  12417. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  12418. }
  12419. const face = {
  12420. a: a,
  12421. b: b,
  12422. c: c,
  12423. normal: new Vector3(),
  12424. materialIndex: 0
  12425. };
  12426. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  12427. intersection.face = face;
  12428. }
  12429. return intersection;
  12430. }
  12431. class BoxGeometry extends BufferGeometry {
  12432. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  12433. super();
  12434. this.type = 'BoxGeometry';
  12435. this.parameters = {
  12436. width: width,
  12437. height: height,
  12438. depth: depth,
  12439. widthSegments: widthSegments,
  12440. heightSegments: heightSegments,
  12441. depthSegments: depthSegments
  12442. };
  12443. const scope = this; // segments
  12444. widthSegments = Math.floor(widthSegments);
  12445. heightSegments = Math.floor(heightSegments);
  12446. depthSegments = Math.floor(depthSegments); // buffers
  12447. const indices = [];
  12448. const vertices = [];
  12449. const normals = [];
  12450. const uvs = []; // helper variables
  12451. let numberOfVertices = 0;
  12452. let groupStart = 0; // build each side of the box geometry
  12453. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  12454. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  12455. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  12456. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  12457. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  12458. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  12459. // build geometry
  12460. this.setIndex(indices);
  12461. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  12462. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  12463. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  12464. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  12465. const segmentWidth = width / gridX;
  12466. const segmentHeight = height / gridY;
  12467. const widthHalf = width / 2;
  12468. const heightHalf = height / 2;
  12469. const depthHalf = depth / 2;
  12470. const gridX1 = gridX + 1;
  12471. const gridY1 = gridY + 1;
  12472. let vertexCounter = 0;
  12473. let groupCount = 0;
  12474. const vector = new Vector3(); // generate vertices, normals and uvs
  12475. for (let iy = 0; iy < gridY1; iy++) {
  12476. const y = iy * segmentHeight - heightHalf;
  12477. for (let ix = 0; ix < gridX1; ix++) {
  12478. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  12479. vector[u] = x * udir;
  12480. vector[v] = y * vdir;
  12481. vector[w] = depthHalf; // now apply vector to vertex buffer
  12482. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  12483. vector[u] = 0;
  12484. vector[v] = 0;
  12485. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  12486. normals.push(vector.x, vector.y, vector.z); // uvs
  12487. uvs.push(ix / gridX);
  12488. uvs.push(1 - iy / gridY); // counters
  12489. vertexCounter += 1;
  12490. }
  12491. } // indices
  12492. // 1. you need three indices to draw a single face
  12493. // 2. a single segment consists of two faces
  12494. // 3. so we need to generate six (2*3) indices per segment
  12495. for (let iy = 0; iy < gridY; iy++) {
  12496. for (let ix = 0; ix < gridX; ix++) {
  12497. const a = numberOfVertices + ix + gridX1 * iy;
  12498. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  12499. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  12500. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  12501. indices.push(a, b, d);
  12502. indices.push(b, c, d); // increase counter
  12503. groupCount += 6;
  12504. }
  12505. } // add a group to the geometry. this will ensure multi material support
  12506. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  12507. groupStart += groupCount; // update total number of vertices
  12508. numberOfVertices += vertexCounter;
  12509. }
  12510. }
  12511. static fromJSON(data) {
  12512. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  12513. }
  12514. }
  12515. /**
  12516. * Uniform Utilities
  12517. */
  12518. function cloneUniforms(src) {
  12519. const dst = {};
  12520. for (const u in src) {
  12521. dst[u] = {};
  12522. for (const p in src[u]) {
  12523. const property = src[u][p];
  12524. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  12525. dst[u][p] = property.clone();
  12526. } else if (Array.isArray(property)) {
  12527. dst[u][p] = property.slice();
  12528. } else {
  12529. dst[u][p] = property;
  12530. }
  12531. }
  12532. }
  12533. return dst;
  12534. }
  12535. function mergeUniforms(uniforms) {
  12536. const merged = {};
  12537. for (let u = 0; u < uniforms.length; u++) {
  12538. const tmp = cloneUniforms(uniforms[u]);
  12539. for (const p in tmp) {
  12540. merged[p] = tmp[p];
  12541. }
  12542. }
  12543. return merged;
  12544. } // Legacy
  12545. const UniformsUtils = {
  12546. clone: cloneUniforms,
  12547. merge: mergeUniforms
  12548. };
  12549. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12550. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12551. /**
  12552. * parameters = {
  12553. * defines: { "label" : "value" },
  12554. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  12555. *
  12556. * fragmentShader: <string>,
  12557. * vertexShader: <string>,
  12558. *
  12559. * wireframe: <boolean>,
  12560. * wireframeLinewidth: <float>,
  12561. *
  12562. * lights: <bool>
  12563. * }
  12564. */
  12565. class ShaderMaterial extends Material {
  12566. constructor(parameters) {
  12567. super();
  12568. this.type = 'ShaderMaterial';
  12569. this.defines = {};
  12570. this.uniforms = {};
  12571. this.vertexShader = default_vertex;
  12572. this.fragmentShader = default_fragment;
  12573. this.linewidth = 1;
  12574. this.wireframe = false;
  12575. this.wireframeLinewidth = 1;
  12576. this.fog = false; // set to use scene fog
  12577. this.lights = false; // set to use scene lights
  12578. this.clipping = false; // set to use user-defined clipping planes
  12579. this.extensions = {
  12580. derivatives: false,
  12581. // set to use derivatives
  12582. fragDepth: false,
  12583. // set to use fragment depth values
  12584. drawBuffers: false,
  12585. // set to use draw buffers
  12586. shaderTextureLOD: false // set to use shader texture LOD
  12587. }; // When rendered geometry doesn't include these attributes but the material does,
  12588. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12589. this.defaultAttributeValues = {
  12590. 'color': [1, 1, 1],
  12591. 'uv': [0, 0],
  12592. 'uv2': [0, 0]
  12593. };
  12594. this.index0AttributeName = undefined;
  12595. this.uniformsNeedUpdate = false;
  12596. this.glslVersion = null;
  12597. if (parameters !== undefined) {
  12598. if (parameters.attributes !== undefined) {
  12599. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  12600. }
  12601. this.setValues(parameters);
  12602. }
  12603. }
  12604. copy(source) {
  12605. super.copy(source);
  12606. this.fragmentShader = source.fragmentShader;
  12607. this.vertexShader = source.vertexShader;
  12608. this.uniforms = cloneUniforms(source.uniforms);
  12609. this.defines = Object.assign({}, source.defines);
  12610. this.wireframe = source.wireframe;
  12611. this.wireframeLinewidth = source.wireframeLinewidth;
  12612. this.lights = source.lights;
  12613. this.clipping = source.clipping;
  12614. this.extensions = Object.assign({}, source.extensions);
  12615. this.glslVersion = source.glslVersion;
  12616. return this;
  12617. }
  12618. toJSON(meta) {
  12619. const data = super.toJSON(meta);
  12620. data.glslVersion = this.glslVersion;
  12621. data.uniforms = {};
  12622. for (const name in this.uniforms) {
  12623. const uniform = this.uniforms[name];
  12624. const value = uniform.value;
  12625. if (value && value.isTexture) {
  12626. data.uniforms[name] = {
  12627. type: 't',
  12628. value: value.toJSON(meta).uuid
  12629. };
  12630. } else if (value && value.isColor) {
  12631. data.uniforms[name] = {
  12632. type: 'c',
  12633. value: value.getHex()
  12634. };
  12635. } else if (value && value.isVector2) {
  12636. data.uniforms[name] = {
  12637. type: 'v2',
  12638. value: value.toArray()
  12639. };
  12640. } else if (value && value.isVector3) {
  12641. data.uniforms[name] = {
  12642. type: 'v3',
  12643. value: value.toArray()
  12644. };
  12645. } else if (value && value.isVector4) {
  12646. data.uniforms[name] = {
  12647. type: 'v4',
  12648. value: value.toArray()
  12649. };
  12650. } else if (value && value.isMatrix3) {
  12651. data.uniforms[name] = {
  12652. type: 'm3',
  12653. value: value.toArray()
  12654. };
  12655. } else if (value && value.isMatrix4) {
  12656. data.uniforms[name] = {
  12657. type: 'm4',
  12658. value: value.toArray()
  12659. };
  12660. } else {
  12661. data.uniforms[name] = {
  12662. value: value
  12663. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12664. }
  12665. }
  12666. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  12667. data.vertexShader = this.vertexShader;
  12668. data.fragmentShader = this.fragmentShader;
  12669. const extensions = {};
  12670. for (const key in this.extensions) {
  12671. if (this.extensions[key] === true) extensions[key] = true;
  12672. }
  12673. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  12674. return data;
  12675. }
  12676. }
  12677. ShaderMaterial.prototype.isShaderMaterial = true;
  12678. class Camera extends Object3D {
  12679. constructor() {
  12680. super();
  12681. this.type = 'Camera';
  12682. this.matrixWorldInverse = new Matrix4();
  12683. this.projectionMatrix = new Matrix4();
  12684. this.projectionMatrixInverse = new Matrix4();
  12685. }
  12686. copy(source, recursive) {
  12687. super.copy(source, recursive);
  12688. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  12689. this.projectionMatrix.copy(source.projectionMatrix);
  12690. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  12691. return this;
  12692. }
  12693. getWorldDirection(target) {
  12694. this.updateWorldMatrix(true, false);
  12695. const e = this.matrixWorld.elements;
  12696. return target.set(-e[8], -e[9], -e[10]).normalize();
  12697. }
  12698. updateMatrixWorld(force) {
  12699. super.updateMatrixWorld(force);
  12700. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  12701. }
  12702. updateWorldMatrix(updateParents, updateChildren) {
  12703. super.updateWorldMatrix(updateParents, updateChildren);
  12704. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  12705. }
  12706. clone() {
  12707. return new this.constructor().copy(this);
  12708. }
  12709. }
  12710. Camera.prototype.isCamera = true;
  12711. class PerspectiveCamera extends Camera {
  12712. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  12713. super();
  12714. this.type = 'PerspectiveCamera';
  12715. this.fov = fov;
  12716. this.zoom = 1;
  12717. this.near = near;
  12718. this.far = far;
  12719. this.focus = 10;
  12720. this.aspect = aspect;
  12721. this.view = null;
  12722. this.filmGauge = 35; // width of the film (default in millimeters)
  12723. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  12724. this.updateProjectionMatrix();
  12725. }
  12726. copy(source, recursive) {
  12727. super.copy(source, recursive);
  12728. this.fov = source.fov;
  12729. this.zoom = source.zoom;
  12730. this.near = source.near;
  12731. this.far = source.far;
  12732. this.focus = source.focus;
  12733. this.aspect = source.aspect;
  12734. this.view = source.view === null ? null : Object.assign({}, source.view);
  12735. this.filmGauge = source.filmGauge;
  12736. this.filmOffset = source.filmOffset;
  12737. return this;
  12738. }
  12739. /**
  12740. * Sets the FOV by focal length in respect to the current .filmGauge.
  12741. *
  12742. * The default film gauge is 35, so that the focal length can be specified for
  12743. * a 35mm (full frame) camera.
  12744. *
  12745. * Values for focal length and film gauge must have the same unit.
  12746. */
  12747. setFocalLength(focalLength) {
  12748. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  12749. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  12750. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  12751. this.updateProjectionMatrix();
  12752. }
  12753. /**
  12754. * Calculates the focal length from the current .fov and .filmGauge.
  12755. */
  12756. getFocalLength() {
  12757. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  12758. return 0.5 * this.getFilmHeight() / vExtentSlope;
  12759. }
  12760. getEffectiveFOV() {
  12761. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  12762. }
  12763. getFilmWidth() {
  12764. // film not completely covered in portrait format (aspect < 1)
  12765. return this.filmGauge * Math.min(this.aspect, 1);
  12766. }
  12767. getFilmHeight() {
  12768. // film not completely covered in landscape format (aspect > 1)
  12769. return this.filmGauge / Math.max(this.aspect, 1);
  12770. }
  12771. /**
  12772. * Sets an offset in a larger frustum. This is useful for multi-window or
  12773. * multi-monitor/multi-machine setups.
  12774. *
  12775. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  12776. * the monitors are in grid like this
  12777. *
  12778. * +---+---+---+
  12779. * | A | B | C |
  12780. * +---+---+---+
  12781. * | D | E | F |
  12782. * +---+---+---+
  12783. *
  12784. * then for each monitor you would call it like this
  12785. *
  12786. * const w = 1920;
  12787. * const h = 1080;
  12788. * const fullWidth = w * 3;
  12789. * const fullHeight = h * 2;
  12790. *
  12791. * --A--
  12792. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  12793. * --B--
  12794. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  12795. * --C--
  12796. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  12797. * --D--
  12798. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  12799. * --E--
  12800. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  12801. * --F--
  12802. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  12803. *
  12804. * Note there is no reason monitors have to be the same size or in a grid.
  12805. */
  12806. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  12807. this.aspect = fullWidth / fullHeight;
  12808. if (this.view === null) {
  12809. this.view = {
  12810. enabled: true,
  12811. fullWidth: 1,
  12812. fullHeight: 1,
  12813. offsetX: 0,
  12814. offsetY: 0,
  12815. width: 1,
  12816. height: 1
  12817. };
  12818. }
  12819. this.view.enabled = true;
  12820. this.view.fullWidth = fullWidth;
  12821. this.view.fullHeight = fullHeight;
  12822. this.view.offsetX = x;
  12823. this.view.offsetY = y;
  12824. this.view.width = width;
  12825. this.view.height = height;
  12826. this.updateProjectionMatrix();
  12827. }
  12828. clearViewOffset() {
  12829. if (this.view !== null) {
  12830. this.view.enabled = false;
  12831. }
  12832. this.updateProjectionMatrix();
  12833. }
  12834. updateProjectionMatrix() {
  12835. const near = this.near;
  12836. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  12837. let height = 2 * top;
  12838. let width = this.aspect * height;
  12839. let left = -0.5 * width;
  12840. const view = this.view;
  12841. if (this.view !== null && this.view.enabled) {
  12842. const fullWidth = view.fullWidth,
  12843. fullHeight = view.fullHeight;
  12844. left += view.offsetX * width / fullWidth;
  12845. top -= view.offsetY * height / fullHeight;
  12846. width *= view.width / fullWidth;
  12847. height *= view.height / fullHeight;
  12848. }
  12849. const skew = this.filmOffset;
  12850. if (skew !== 0) left += near * skew / this.getFilmWidth();
  12851. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  12852. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  12853. }
  12854. toJSON(meta) {
  12855. const data = super.toJSON(meta);
  12856. data.object.fov = this.fov;
  12857. data.object.zoom = this.zoom;
  12858. data.object.near = this.near;
  12859. data.object.far = this.far;
  12860. data.object.focus = this.focus;
  12861. data.object.aspect = this.aspect;
  12862. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  12863. data.object.filmGauge = this.filmGauge;
  12864. data.object.filmOffset = this.filmOffset;
  12865. return data;
  12866. }
  12867. }
  12868. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  12869. const fov = 90,
  12870. aspect = 1;
  12871. class CubeCamera extends Object3D {
  12872. constructor(near, far, renderTarget) {
  12873. super();
  12874. this.type = 'CubeCamera';
  12875. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  12876. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  12877. return;
  12878. }
  12879. this.renderTarget = renderTarget;
  12880. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  12881. cameraPX.layers = this.layers;
  12882. cameraPX.up.set(0, -1, 0);
  12883. cameraPX.lookAt(new Vector3(1, 0, 0));
  12884. this.add(cameraPX);
  12885. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  12886. cameraNX.layers = this.layers;
  12887. cameraNX.up.set(0, -1, 0);
  12888. cameraNX.lookAt(new Vector3(-1, 0, 0));
  12889. this.add(cameraNX);
  12890. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  12891. cameraPY.layers = this.layers;
  12892. cameraPY.up.set(0, 0, 1);
  12893. cameraPY.lookAt(new Vector3(0, 1, 0));
  12894. this.add(cameraPY);
  12895. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  12896. cameraNY.layers = this.layers;
  12897. cameraNY.up.set(0, 0, -1);
  12898. cameraNY.lookAt(new Vector3(0, -1, 0));
  12899. this.add(cameraNY);
  12900. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  12901. cameraPZ.layers = this.layers;
  12902. cameraPZ.up.set(0, -1, 0);
  12903. cameraPZ.lookAt(new Vector3(0, 0, 1));
  12904. this.add(cameraPZ);
  12905. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  12906. cameraNZ.layers = this.layers;
  12907. cameraNZ.up.set(0, -1, 0);
  12908. cameraNZ.lookAt(new Vector3(0, 0, -1));
  12909. this.add(cameraNZ);
  12910. }
  12911. update(renderer, scene) {
  12912. if (this.parent === null) this.updateMatrixWorld();
  12913. const renderTarget = this.renderTarget;
  12914. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  12915. const currentXrEnabled = renderer.xr.enabled;
  12916. const currentRenderTarget = renderer.getRenderTarget();
  12917. renderer.xr.enabled = false;
  12918. const generateMipmaps = renderTarget.texture.generateMipmaps;
  12919. renderTarget.texture.generateMipmaps = false;
  12920. renderer.setRenderTarget(renderTarget, 0);
  12921. renderer.render(scene, cameraPX);
  12922. renderer.setRenderTarget(renderTarget, 1);
  12923. renderer.render(scene, cameraNX);
  12924. renderer.setRenderTarget(renderTarget, 2);
  12925. renderer.render(scene, cameraPY);
  12926. renderer.setRenderTarget(renderTarget, 3);
  12927. renderer.render(scene, cameraNY);
  12928. renderer.setRenderTarget(renderTarget, 4);
  12929. renderer.render(scene, cameraPZ);
  12930. renderTarget.texture.generateMipmaps = generateMipmaps;
  12931. renderer.setRenderTarget(renderTarget, 5);
  12932. renderer.render(scene, cameraNZ);
  12933. renderer.setRenderTarget(currentRenderTarget);
  12934. renderer.xr.enabled = currentXrEnabled;
  12935. }
  12936. }
  12937. class CubeTexture extends Texture {
  12938. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  12939. images = images !== undefined ? images : [];
  12940. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  12941. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  12942. this.flipY = false;
  12943. }
  12944. get images() {
  12945. return this.image;
  12946. }
  12947. set images(value) {
  12948. this.image = value;
  12949. }
  12950. }
  12951. CubeTexture.prototype.isCubeTexture = true;
  12952. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  12953. constructor(size, options, dummy) {
  12954. if (Number.isInteger(options)) {
  12955. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  12956. options = dummy;
  12957. }
  12958. super(size, size, options);
  12959. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  12960. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  12961. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  12962. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  12963. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  12964. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  12965. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  12966. this.texture.isRenderTargetTexture = true;
  12967. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  12968. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  12969. this.texture._needsFlipEnvMap = false;
  12970. }
  12971. fromEquirectangularTexture(renderer, texture) {
  12972. this.texture.type = texture.type;
  12973. this.texture.format = RGBAFormat; // see #18859
  12974. this.texture.encoding = texture.encoding;
  12975. this.texture.generateMipmaps = texture.generateMipmaps;
  12976. this.texture.minFilter = texture.minFilter;
  12977. this.texture.magFilter = texture.magFilter;
  12978. const shader = {
  12979. uniforms: {
  12980. tEquirect: {
  12981. value: null
  12982. }
  12983. },
  12984. vertexShader:
  12985. /* glsl */
  12986. `
  12987. varying vec3 vWorldDirection;
  12988. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  12989. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  12990. }
  12991. void main() {
  12992. vWorldDirection = transformDirection( position, modelMatrix );
  12993. #include <begin_vertex>
  12994. #include <project_vertex>
  12995. }
  12996. `,
  12997. fragmentShader:
  12998. /* glsl */
  12999. `
  13000. uniform sampler2D tEquirect;
  13001. varying vec3 vWorldDirection;
  13002. #include <common>
  13003. void main() {
  13004. vec3 direction = normalize( vWorldDirection );
  13005. vec2 sampleUV = equirectUv( direction );
  13006. gl_FragColor = texture2D( tEquirect, sampleUV );
  13007. }
  13008. `
  13009. };
  13010. const geometry = new BoxGeometry(5, 5, 5);
  13011. const material = new ShaderMaterial({
  13012. name: 'CubemapFromEquirect',
  13013. uniforms: cloneUniforms(shader.uniforms),
  13014. vertexShader: shader.vertexShader,
  13015. fragmentShader: shader.fragmentShader,
  13016. side: BackSide,
  13017. blending: NoBlending
  13018. });
  13019. material.uniforms.tEquirect.value = texture;
  13020. const mesh = new Mesh(geometry, material);
  13021. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  13022. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  13023. const camera = new CubeCamera(1, 10, this);
  13024. camera.update(renderer, mesh);
  13025. texture.minFilter = currentMinFilter;
  13026. mesh.geometry.dispose();
  13027. mesh.material.dispose();
  13028. return this;
  13029. }
  13030. clear(renderer, color, depth, stencil) {
  13031. const currentRenderTarget = renderer.getRenderTarget();
  13032. for (let i = 0; i < 6; i++) {
  13033. renderer.setRenderTarget(this, i);
  13034. renderer.clear(color, depth, stencil);
  13035. }
  13036. renderer.setRenderTarget(currentRenderTarget);
  13037. }
  13038. }
  13039. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  13040. const _vector1 = /*@__PURE__*/new Vector3();
  13041. const _vector2 = /*@__PURE__*/new Vector3();
  13042. const _normalMatrix = /*@__PURE__*/new Matrix3();
  13043. class Plane {
  13044. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  13045. // normal is assumed to be normalized
  13046. this.normal = normal;
  13047. this.constant = constant;
  13048. }
  13049. set(normal, constant) {
  13050. this.normal.copy(normal);
  13051. this.constant = constant;
  13052. return this;
  13053. }
  13054. setComponents(x, y, z, w) {
  13055. this.normal.set(x, y, z);
  13056. this.constant = w;
  13057. return this;
  13058. }
  13059. setFromNormalAndCoplanarPoint(normal, point) {
  13060. this.normal.copy(normal);
  13061. this.constant = -point.dot(this.normal);
  13062. return this;
  13063. }
  13064. setFromCoplanarPoints(a, b, c) {
  13065. const 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)?
  13066. this.setFromNormalAndCoplanarPoint(normal, a);
  13067. return this;
  13068. }
  13069. copy(plane) {
  13070. this.normal.copy(plane.normal);
  13071. this.constant = plane.constant;
  13072. return this;
  13073. }
  13074. normalize() {
  13075. // Note: will lead to a divide by zero if the plane is invalid.
  13076. const inverseNormalLength = 1.0 / this.normal.length();
  13077. this.normal.multiplyScalar(inverseNormalLength);
  13078. this.constant *= inverseNormalLength;
  13079. return this;
  13080. }
  13081. negate() {
  13082. this.constant *= -1;
  13083. this.normal.negate();
  13084. return this;
  13085. }
  13086. distanceToPoint(point) {
  13087. return this.normal.dot(point) + this.constant;
  13088. }
  13089. distanceToSphere(sphere) {
  13090. return this.distanceToPoint(sphere.center) - sphere.radius;
  13091. }
  13092. projectPoint(point, target) {
  13093. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  13094. }
  13095. intersectLine(line, target) {
  13096. const direction = line.delta(_vector1);
  13097. const denominator = this.normal.dot(direction);
  13098. if (denominator === 0) {
  13099. // line is coplanar, return origin
  13100. if (this.distanceToPoint(line.start) === 0) {
  13101. return target.copy(line.start);
  13102. } // Unsure if this is the correct method to handle this case.
  13103. return null;
  13104. }
  13105. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  13106. if (t < 0 || t > 1) {
  13107. return null;
  13108. }
  13109. return target.copy(direction).multiplyScalar(t).add(line.start);
  13110. }
  13111. intersectsLine(line) {
  13112. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  13113. const startSign = this.distanceToPoint(line.start);
  13114. const endSign = this.distanceToPoint(line.end);
  13115. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  13116. }
  13117. intersectsBox(box) {
  13118. return box.intersectsPlane(this);
  13119. }
  13120. intersectsSphere(sphere) {
  13121. return sphere.intersectsPlane(this);
  13122. }
  13123. coplanarPoint(target) {
  13124. return target.copy(this.normal).multiplyScalar(-this.constant);
  13125. }
  13126. applyMatrix4(matrix, optionalNormalMatrix) {
  13127. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  13128. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  13129. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  13130. this.constant = -referencePoint.dot(normal);
  13131. return this;
  13132. }
  13133. translate(offset) {
  13134. this.constant -= offset.dot(this.normal);
  13135. return this;
  13136. }
  13137. equals(plane) {
  13138. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  13139. }
  13140. clone() {
  13141. return new this.constructor().copy(this);
  13142. }
  13143. }
  13144. Plane.prototype.isPlane = true;
  13145. const _sphere$2 = /*@__PURE__*/new Sphere();
  13146. const _vector$7 = /*@__PURE__*/new Vector3();
  13147. class Frustum {
  13148. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  13149. this.planes = [p0, p1, p2, p3, p4, p5];
  13150. }
  13151. set(p0, p1, p2, p3, p4, p5) {
  13152. const planes = this.planes;
  13153. planes[0].copy(p0);
  13154. planes[1].copy(p1);
  13155. planes[2].copy(p2);
  13156. planes[3].copy(p3);
  13157. planes[4].copy(p4);
  13158. planes[5].copy(p5);
  13159. return this;
  13160. }
  13161. copy(frustum) {
  13162. const planes = this.planes;
  13163. for (let i = 0; i < 6; i++) {
  13164. planes[i].copy(frustum.planes[i]);
  13165. }
  13166. return this;
  13167. }
  13168. setFromProjectionMatrix(m) {
  13169. const planes = this.planes;
  13170. const me = m.elements;
  13171. const me0 = me[0],
  13172. me1 = me[1],
  13173. me2 = me[2],
  13174. me3 = me[3];
  13175. const me4 = me[4],
  13176. me5 = me[5],
  13177. me6 = me[6],
  13178. me7 = me[7];
  13179. const me8 = me[8],
  13180. me9 = me[9],
  13181. me10 = me[10],
  13182. me11 = me[11];
  13183. const me12 = me[12],
  13184. me13 = me[13],
  13185. me14 = me[14],
  13186. me15 = me[15];
  13187. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  13188. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  13189. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  13190. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  13191. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  13192. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  13193. return this;
  13194. }
  13195. intersectsObject(object) {
  13196. const geometry = object.geometry;
  13197. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  13198. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  13199. return this.intersectsSphere(_sphere$2);
  13200. }
  13201. intersectsSprite(sprite) {
  13202. _sphere$2.center.set(0, 0, 0);
  13203. _sphere$2.radius = 0.7071067811865476;
  13204. _sphere$2.applyMatrix4(sprite.matrixWorld);
  13205. return this.intersectsSphere(_sphere$2);
  13206. }
  13207. intersectsSphere(sphere) {
  13208. const planes = this.planes;
  13209. const center = sphere.center;
  13210. const negRadius = -sphere.radius;
  13211. for (let i = 0; i < 6; i++) {
  13212. const distance = planes[i].distanceToPoint(center);
  13213. if (distance < negRadius) {
  13214. return false;
  13215. }
  13216. }
  13217. return true;
  13218. }
  13219. intersectsBox(box) {
  13220. const planes = this.planes;
  13221. for (let i = 0; i < 6; i++) {
  13222. const plane = planes[i]; // corner at max distance
  13223. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  13224. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  13225. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  13226. if (plane.distanceToPoint(_vector$7) < 0) {
  13227. return false;
  13228. }
  13229. }
  13230. return true;
  13231. }
  13232. containsPoint(point) {
  13233. const planes = this.planes;
  13234. for (let i = 0; i < 6; i++) {
  13235. if (planes[i].distanceToPoint(point) < 0) {
  13236. return false;
  13237. }
  13238. }
  13239. return true;
  13240. }
  13241. clone() {
  13242. return new this.constructor().copy(this);
  13243. }
  13244. }
  13245. function WebGLAnimation() {
  13246. let context = null;
  13247. let isAnimating = false;
  13248. let animationLoop = null;
  13249. let requestId = null;
  13250. function onAnimationFrame(time, frame) {
  13251. animationLoop(time, frame);
  13252. requestId = context.requestAnimationFrame(onAnimationFrame);
  13253. }
  13254. return {
  13255. start: function () {
  13256. if (isAnimating === true) return;
  13257. if (animationLoop === null) return;
  13258. requestId = context.requestAnimationFrame(onAnimationFrame);
  13259. isAnimating = true;
  13260. },
  13261. stop: function () {
  13262. context.cancelAnimationFrame(requestId);
  13263. isAnimating = false;
  13264. },
  13265. setAnimationLoop: function (callback) {
  13266. animationLoop = callback;
  13267. },
  13268. setContext: function (value) {
  13269. context = value;
  13270. }
  13271. };
  13272. }
  13273. function WebGLAttributes(gl, capabilities) {
  13274. const isWebGL2 = capabilities.isWebGL2;
  13275. const buffers = new WeakMap();
  13276. function createBuffer(attribute, bufferType) {
  13277. const array = attribute.array;
  13278. const usage = attribute.usage;
  13279. const buffer = gl.createBuffer();
  13280. gl.bindBuffer(bufferType, buffer);
  13281. gl.bufferData(bufferType, array, usage);
  13282. attribute.onUploadCallback();
  13283. let type = gl.FLOAT;
  13284. if (array instanceof Float32Array) {
  13285. type = gl.FLOAT;
  13286. } else if (array instanceof Float64Array) {
  13287. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  13288. } else if (array instanceof Uint16Array) {
  13289. if (attribute.isFloat16BufferAttribute) {
  13290. if (isWebGL2) {
  13291. type = gl.HALF_FLOAT;
  13292. } else {
  13293. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  13294. }
  13295. } else {
  13296. type = gl.UNSIGNED_SHORT;
  13297. }
  13298. } else if (array instanceof Int16Array) {
  13299. type = gl.SHORT;
  13300. } else if (array instanceof Uint32Array) {
  13301. type = gl.UNSIGNED_INT;
  13302. } else if (array instanceof Int32Array) {
  13303. type = gl.INT;
  13304. } else if (array instanceof Int8Array) {
  13305. type = gl.BYTE;
  13306. } else if (array instanceof Uint8Array) {
  13307. type = gl.UNSIGNED_BYTE;
  13308. } else if (array instanceof Uint8ClampedArray) {
  13309. type = gl.UNSIGNED_BYTE;
  13310. }
  13311. return {
  13312. buffer: buffer,
  13313. type: type,
  13314. bytesPerElement: array.BYTES_PER_ELEMENT,
  13315. version: attribute.version
  13316. };
  13317. }
  13318. function updateBuffer(buffer, attribute, bufferType) {
  13319. const array = attribute.array;
  13320. const updateRange = attribute.updateRange;
  13321. gl.bindBuffer(bufferType, buffer);
  13322. if (updateRange.count === -1) {
  13323. // Not using update ranges
  13324. gl.bufferSubData(bufferType, 0, array);
  13325. } else {
  13326. if (isWebGL2) {
  13327. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  13328. } else {
  13329. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  13330. }
  13331. updateRange.count = -1; // reset range
  13332. }
  13333. } //
  13334. function get(attribute) {
  13335. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13336. return buffers.get(attribute);
  13337. }
  13338. function remove(attribute) {
  13339. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13340. const data = buffers.get(attribute);
  13341. if (data) {
  13342. gl.deleteBuffer(data.buffer);
  13343. buffers.delete(attribute);
  13344. }
  13345. }
  13346. function update(attribute, bufferType) {
  13347. if (attribute.isGLBufferAttribute) {
  13348. const cached = buffers.get(attribute);
  13349. if (!cached || cached.version < attribute.version) {
  13350. buffers.set(attribute, {
  13351. buffer: attribute.buffer,
  13352. type: attribute.type,
  13353. bytesPerElement: attribute.elementSize,
  13354. version: attribute.version
  13355. });
  13356. }
  13357. return;
  13358. }
  13359. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  13360. const data = buffers.get(attribute);
  13361. if (data === undefined) {
  13362. buffers.set(attribute, createBuffer(attribute, bufferType));
  13363. } else if (data.version < attribute.version) {
  13364. updateBuffer(data.buffer, attribute, bufferType);
  13365. data.version = attribute.version;
  13366. }
  13367. }
  13368. return {
  13369. get: get,
  13370. remove: remove,
  13371. update: update
  13372. };
  13373. }
  13374. class PlaneGeometry extends BufferGeometry {
  13375. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  13376. super();
  13377. this.type = 'PlaneGeometry';
  13378. this.parameters = {
  13379. width: width,
  13380. height: height,
  13381. widthSegments: widthSegments,
  13382. heightSegments: heightSegments
  13383. };
  13384. const width_half = width / 2;
  13385. const height_half = height / 2;
  13386. const gridX = Math.floor(widthSegments);
  13387. const gridY = Math.floor(heightSegments);
  13388. const gridX1 = gridX + 1;
  13389. const gridY1 = gridY + 1;
  13390. const segment_width = width / gridX;
  13391. const segment_height = height / gridY; //
  13392. const indices = [];
  13393. const vertices = [];
  13394. const normals = [];
  13395. const uvs = [];
  13396. for (let iy = 0; iy < gridY1; iy++) {
  13397. const y = iy * segment_height - height_half;
  13398. for (let ix = 0; ix < gridX1; ix++) {
  13399. const x = ix * segment_width - width_half;
  13400. vertices.push(x, -y, 0);
  13401. normals.push(0, 0, 1);
  13402. uvs.push(ix / gridX);
  13403. uvs.push(1 - iy / gridY);
  13404. }
  13405. }
  13406. for (let iy = 0; iy < gridY; iy++) {
  13407. for (let ix = 0; ix < gridX; ix++) {
  13408. const a = ix + gridX1 * iy;
  13409. const b = ix + gridX1 * (iy + 1);
  13410. const c = ix + 1 + gridX1 * (iy + 1);
  13411. const d = ix + 1 + gridX1 * iy;
  13412. indices.push(a, b, d);
  13413. indices.push(b, c, d);
  13414. }
  13415. }
  13416. this.setIndex(indices);
  13417. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  13418. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  13419. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  13420. }
  13421. static fromJSON(data) {
  13422. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  13423. }
  13424. }
  13425. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  13426. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  13427. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  13428. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  13429. 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.roughness );\n\t#endif\n#endif";
  13430. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  13431. var begin_vertex = "vec3 transformed = vec3( position );";
  13432. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  13433. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_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_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * 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}\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_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenTint, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenTint * ( D * V );\n}\n#endif";
  13434. 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, float faceDirection ) {\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 ) * faceDirection;\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";
  13435. 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";
  13436. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  13437. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  13438. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  13439. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  13440. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  13441. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  13442. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  13443. 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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 USE_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}\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}";
  13444. 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";
  13445. 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";
  13446. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  13447. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  13448. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  13449. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  13450. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  13451. 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}";
  13452. 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\tenvColor = envMapTexelToLinear( envColor );\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#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";
  13453. 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";
  13454. 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";
  13455. 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";
  13456. 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";
  13457. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  13458. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  13459. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  13460. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\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";
  13461. 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}";
  13462. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  13463. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  13464. 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.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\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\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  13465. 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 vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\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 getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.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 getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.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 getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.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 vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  13466. 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 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  13467. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  13468. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\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\treflectedLight.directDiffuse += irradiance * BRDF_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_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)";
  13469. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  13470. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\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\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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_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)";
  13471. 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.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\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.sheenTint = sheenTint;\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n#endif";
  13472. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\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\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.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}\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.roughness;\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#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenTint, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_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_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 USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += 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}";
  13473. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_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\tgetPointLightInfo( 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\tgetSpotLightInfo( 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\tgetDirectionalLightInfo( 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.normal );\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.normal );\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";
  13474. 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 += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  13475. 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";
  13476. 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";
  13477. 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";
  13478. 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";
  13479. 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";
  13480. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  13481. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  13482. 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";
  13483. 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";
  13484. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  13485. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  13486. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  13487. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  13488. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  13489. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#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 * faceDirection;\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 * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\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;";
  13490. 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 * faceDirection;\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, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  13491. var normal_pars_fragment = "#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";
  13492. var normal_pars_vertex = "#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";
  13493. var normal_vertex = "#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";
  13494. 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, float faceDirection ) {\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\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  13495. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  13496. 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, faceDirection );\n\t#endif\n#endif";
  13497. 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";
  13498. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  13499. 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}";
  13500. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  13501. 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;";
  13502. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  13503. 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";
  13504. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  13505. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  13506. 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";
  13507. 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";
  13508. 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";
  13509. 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}";
  13510. 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";
  13511. 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";
  13512. 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";
  13513. 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";
  13514. 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";
  13515. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  13516. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  13517. 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; }";
  13518. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  13519. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  13520. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  13521. 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";
  13522. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  13523. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  13524. 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";
  13525. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  13526. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\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";
  13527. const vertex$g = "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}";
  13528. const fragment$g = "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}";
  13529. const vertex$f = "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}";
  13530. const fragment$f = "#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}";
  13531. const vertex$e = "#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}";
  13532. const fragment$e = "#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 <alphatest_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}";
  13533. const vertex$d = "#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}";
  13534. const fragment$d = "#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 <alphatest_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}";
  13535. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  13536. const fragment$c = "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}";
  13537. const vertex$b = "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}";
  13538. const fragment$b = "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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  13539. const vertex$a = "#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#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\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 <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  13540. const fragment$a = "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 <alphatest_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\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\t#include <output_fragment>\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}";
  13541. const vertex$9 = "#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}";
  13542. const fragment$9 = "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 <alphatest_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_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_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\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}";
  13543. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\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 <normal_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#include <normal_vertex>\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}";
  13544. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_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\t#include <output_fragment>\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}";
  13545. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_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\t#include <normal_vertex>\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}";
  13546. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_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}";
  13547. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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 <normal_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 <normal_vertex>\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}";
  13548. const fragment$6 = "#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 <alphatest_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 <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  13549. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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 <normal_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 <normal_vertex>\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#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  13550. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n\tuniform float sheenRoughness;\n#endif\nvarying vec3 vViewPosition;\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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_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 <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_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#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 <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 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\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}";
  13551. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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 <normal_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 <normal_vertex>\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}";
  13552. const fragment$4 = "#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 <alphatest_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 <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  13553. const vertex$3 = "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}";
  13554. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  13555. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  13556. const fragment$2 = "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}";
  13557. const vertex$1 = "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}";
  13558. const fragment$1 = "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 <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  13559. const ShaderChunk = {
  13560. alphamap_fragment: alphamap_fragment,
  13561. alphamap_pars_fragment: alphamap_pars_fragment,
  13562. alphatest_fragment: alphatest_fragment,
  13563. alphatest_pars_fragment: alphatest_pars_fragment,
  13564. aomap_fragment: aomap_fragment,
  13565. aomap_pars_fragment: aomap_pars_fragment,
  13566. begin_vertex: begin_vertex,
  13567. beginnormal_vertex: beginnormal_vertex,
  13568. bsdfs: bsdfs,
  13569. bumpmap_pars_fragment: bumpmap_pars_fragment,
  13570. clipping_planes_fragment: clipping_planes_fragment,
  13571. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  13572. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  13573. clipping_planes_vertex: clipping_planes_vertex,
  13574. color_fragment: color_fragment,
  13575. color_pars_fragment: color_pars_fragment,
  13576. color_pars_vertex: color_pars_vertex,
  13577. color_vertex: color_vertex,
  13578. common: common,
  13579. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  13580. defaultnormal_vertex: defaultnormal_vertex,
  13581. displacementmap_pars_vertex: displacementmap_pars_vertex,
  13582. displacementmap_vertex: displacementmap_vertex,
  13583. emissivemap_fragment: emissivemap_fragment,
  13584. emissivemap_pars_fragment: emissivemap_pars_fragment,
  13585. encodings_fragment: encodings_fragment,
  13586. encodings_pars_fragment: encodings_pars_fragment,
  13587. envmap_fragment: envmap_fragment,
  13588. envmap_common_pars_fragment: envmap_common_pars_fragment,
  13589. envmap_pars_fragment: envmap_pars_fragment,
  13590. envmap_pars_vertex: envmap_pars_vertex,
  13591. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  13592. envmap_vertex: envmap_vertex,
  13593. fog_vertex: fog_vertex,
  13594. fog_pars_vertex: fog_pars_vertex,
  13595. fog_fragment: fog_fragment,
  13596. fog_pars_fragment: fog_pars_fragment,
  13597. gradientmap_pars_fragment: gradientmap_pars_fragment,
  13598. lightmap_fragment: lightmap_fragment,
  13599. lightmap_pars_fragment: lightmap_pars_fragment,
  13600. lights_lambert_vertex: lights_lambert_vertex,
  13601. lights_pars_begin: lights_pars_begin,
  13602. lights_toon_fragment: lights_toon_fragment,
  13603. lights_toon_pars_fragment: lights_toon_pars_fragment,
  13604. lights_phong_fragment: lights_phong_fragment,
  13605. lights_phong_pars_fragment: lights_phong_pars_fragment,
  13606. lights_physical_fragment: lights_physical_fragment,
  13607. lights_physical_pars_fragment: lights_physical_pars_fragment,
  13608. lights_fragment_begin: lights_fragment_begin,
  13609. lights_fragment_maps: lights_fragment_maps,
  13610. lights_fragment_end: lights_fragment_end,
  13611. logdepthbuf_fragment: logdepthbuf_fragment,
  13612. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  13613. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  13614. logdepthbuf_vertex: logdepthbuf_vertex,
  13615. map_fragment: map_fragment,
  13616. map_pars_fragment: map_pars_fragment,
  13617. map_particle_fragment: map_particle_fragment,
  13618. map_particle_pars_fragment: map_particle_pars_fragment,
  13619. metalnessmap_fragment: metalnessmap_fragment,
  13620. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  13621. morphnormal_vertex: morphnormal_vertex,
  13622. morphtarget_pars_vertex: morphtarget_pars_vertex,
  13623. morphtarget_vertex: morphtarget_vertex,
  13624. normal_fragment_begin: normal_fragment_begin,
  13625. normal_fragment_maps: normal_fragment_maps,
  13626. normal_pars_fragment: normal_pars_fragment,
  13627. normal_pars_vertex: normal_pars_vertex,
  13628. normal_vertex: normal_vertex,
  13629. normalmap_pars_fragment: normalmap_pars_fragment,
  13630. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  13631. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  13632. clearcoat_pars_fragment: clearcoat_pars_fragment,
  13633. output_fragment: output_fragment,
  13634. packing: packing,
  13635. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  13636. project_vertex: project_vertex,
  13637. dithering_fragment: dithering_fragment,
  13638. dithering_pars_fragment: dithering_pars_fragment,
  13639. roughnessmap_fragment: roughnessmap_fragment,
  13640. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  13641. shadowmap_pars_fragment: shadowmap_pars_fragment,
  13642. shadowmap_pars_vertex: shadowmap_pars_vertex,
  13643. shadowmap_vertex: shadowmap_vertex,
  13644. shadowmask_pars_fragment: shadowmask_pars_fragment,
  13645. skinbase_vertex: skinbase_vertex,
  13646. skinning_pars_vertex: skinning_pars_vertex,
  13647. skinning_vertex: skinning_vertex,
  13648. skinnormal_vertex: skinnormal_vertex,
  13649. specularmap_fragment: specularmap_fragment,
  13650. specularmap_pars_fragment: specularmap_pars_fragment,
  13651. tonemapping_fragment: tonemapping_fragment,
  13652. tonemapping_pars_fragment: tonemapping_pars_fragment,
  13653. transmission_fragment: transmission_fragment,
  13654. transmission_pars_fragment: transmission_pars_fragment,
  13655. uv_pars_fragment: uv_pars_fragment,
  13656. uv_pars_vertex: uv_pars_vertex,
  13657. uv_vertex: uv_vertex,
  13658. uv2_pars_fragment: uv2_pars_fragment,
  13659. uv2_pars_vertex: uv2_pars_vertex,
  13660. uv2_vertex: uv2_vertex,
  13661. worldpos_vertex: worldpos_vertex,
  13662. background_vert: vertex$g,
  13663. background_frag: fragment$g,
  13664. cube_vert: vertex$f,
  13665. cube_frag: fragment$f,
  13666. depth_vert: vertex$e,
  13667. depth_frag: fragment$e,
  13668. distanceRGBA_vert: vertex$d,
  13669. distanceRGBA_frag: fragment$d,
  13670. equirect_vert: vertex$c,
  13671. equirect_frag: fragment$c,
  13672. linedashed_vert: vertex$b,
  13673. linedashed_frag: fragment$b,
  13674. meshbasic_vert: vertex$a,
  13675. meshbasic_frag: fragment$a,
  13676. meshlambert_vert: vertex$9,
  13677. meshlambert_frag: fragment$9,
  13678. meshmatcap_vert: vertex$8,
  13679. meshmatcap_frag: fragment$8,
  13680. meshnormal_vert: vertex$7,
  13681. meshnormal_frag: fragment$7,
  13682. meshphong_vert: vertex$6,
  13683. meshphong_frag: fragment$6,
  13684. meshphysical_vert: vertex$5,
  13685. meshphysical_frag: fragment$5,
  13686. meshtoon_vert: vertex$4,
  13687. meshtoon_frag: fragment$4,
  13688. points_vert: vertex$3,
  13689. points_frag: fragment$3,
  13690. shadow_vert: vertex$2,
  13691. shadow_frag: fragment$2,
  13692. sprite_vert: vertex$1,
  13693. sprite_frag: fragment$1
  13694. };
  13695. /**
  13696. * Uniforms library for shared webgl shaders
  13697. */
  13698. const UniformsLib = {
  13699. common: {
  13700. diffuse: {
  13701. value: new Color(0xffffff)
  13702. },
  13703. opacity: {
  13704. value: 1.0
  13705. },
  13706. map: {
  13707. value: null
  13708. },
  13709. uvTransform: {
  13710. value: new Matrix3()
  13711. },
  13712. uv2Transform: {
  13713. value: new Matrix3()
  13714. },
  13715. alphaMap: {
  13716. value: null
  13717. },
  13718. alphaTest: {
  13719. value: 0
  13720. }
  13721. },
  13722. specularmap: {
  13723. specularMap: {
  13724. value: null
  13725. }
  13726. },
  13727. envmap: {
  13728. envMap: {
  13729. value: null
  13730. },
  13731. flipEnvMap: {
  13732. value: -1
  13733. },
  13734. reflectivity: {
  13735. value: 1.0
  13736. },
  13737. // basic, lambert, phong
  13738. ior: {
  13739. value: 1.5
  13740. },
  13741. // standard, physical
  13742. refractionRatio: {
  13743. value: 0.98
  13744. },
  13745. maxMipLevel: {
  13746. value: 0
  13747. }
  13748. },
  13749. aomap: {
  13750. aoMap: {
  13751. value: null
  13752. },
  13753. aoMapIntensity: {
  13754. value: 1
  13755. }
  13756. },
  13757. lightmap: {
  13758. lightMap: {
  13759. value: null
  13760. },
  13761. lightMapIntensity: {
  13762. value: 1
  13763. }
  13764. },
  13765. emissivemap: {
  13766. emissiveMap: {
  13767. value: null
  13768. }
  13769. },
  13770. bumpmap: {
  13771. bumpMap: {
  13772. value: null
  13773. },
  13774. bumpScale: {
  13775. value: 1
  13776. }
  13777. },
  13778. normalmap: {
  13779. normalMap: {
  13780. value: null
  13781. },
  13782. normalScale: {
  13783. value: new Vector2(1, 1)
  13784. }
  13785. },
  13786. displacementmap: {
  13787. displacementMap: {
  13788. value: null
  13789. },
  13790. displacementScale: {
  13791. value: 1
  13792. },
  13793. displacementBias: {
  13794. value: 0
  13795. }
  13796. },
  13797. roughnessmap: {
  13798. roughnessMap: {
  13799. value: null
  13800. }
  13801. },
  13802. metalnessmap: {
  13803. metalnessMap: {
  13804. value: null
  13805. }
  13806. },
  13807. gradientmap: {
  13808. gradientMap: {
  13809. value: null
  13810. }
  13811. },
  13812. fog: {
  13813. fogDensity: {
  13814. value: 0.00025
  13815. },
  13816. fogNear: {
  13817. value: 1
  13818. },
  13819. fogFar: {
  13820. value: 2000
  13821. },
  13822. fogColor: {
  13823. value: new Color(0xffffff)
  13824. }
  13825. },
  13826. lights: {
  13827. ambientLightColor: {
  13828. value: []
  13829. },
  13830. lightProbe: {
  13831. value: []
  13832. },
  13833. directionalLights: {
  13834. value: [],
  13835. properties: {
  13836. direction: {},
  13837. color: {}
  13838. }
  13839. },
  13840. directionalLightShadows: {
  13841. value: [],
  13842. properties: {
  13843. shadowBias: {},
  13844. shadowNormalBias: {},
  13845. shadowRadius: {},
  13846. shadowMapSize: {}
  13847. }
  13848. },
  13849. directionalShadowMap: {
  13850. value: []
  13851. },
  13852. directionalShadowMatrix: {
  13853. value: []
  13854. },
  13855. spotLights: {
  13856. value: [],
  13857. properties: {
  13858. color: {},
  13859. position: {},
  13860. direction: {},
  13861. distance: {},
  13862. coneCos: {},
  13863. penumbraCos: {},
  13864. decay: {}
  13865. }
  13866. },
  13867. spotLightShadows: {
  13868. value: [],
  13869. properties: {
  13870. shadowBias: {},
  13871. shadowNormalBias: {},
  13872. shadowRadius: {},
  13873. shadowMapSize: {}
  13874. }
  13875. },
  13876. spotShadowMap: {
  13877. value: []
  13878. },
  13879. spotShadowMatrix: {
  13880. value: []
  13881. },
  13882. pointLights: {
  13883. value: [],
  13884. properties: {
  13885. color: {},
  13886. position: {},
  13887. decay: {},
  13888. distance: {}
  13889. }
  13890. },
  13891. pointLightShadows: {
  13892. value: [],
  13893. properties: {
  13894. shadowBias: {},
  13895. shadowNormalBias: {},
  13896. shadowRadius: {},
  13897. shadowMapSize: {},
  13898. shadowCameraNear: {},
  13899. shadowCameraFar: {}
  13900. }
  13901. },
  13902. pointShadowMap: {
  13903. value: []
  13904. },
  13905. pointShadowMatrix: {
  13906. value: []
  13907. },
  13908. hemisphereLights: {
  13909. value: [],
  13910. properties: {
  13911. direction: {},
  13912. skyColor: {},
  13913. groundColor: {}
  13914. }
  13915. },
  13916. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  13917. rectAreaLights: {
  13918. value: [],
  13919. properties: {
  13920. color: {},
  13921. position: {},
  13922. width: {},
  13923. height: {}
  13924. }
  13925. },
  13926. ltc_1: {
  13927. value: null
  13928. },
  13929. ltc_2: {
  13930. value: null
  13931. }
  13932. },
  13933. points: {
  13934. diffuse: {
  13935. value: new Color(0xffffff)
  13936. },
  13937. opacity: {
  13938. value: 1.0
  13939. },
  13940. size: {
  13941. value: 1.0
  13942. },
  13943. scale: {
  13944. value: 1.0
  13945. },
  13946. map: {
  13947. value: null
  13948. },
  13949. alphaMap: {
  13950. value: null
  13951. },
  13952. alphaTest: {
  13953. value: 0
  13954. },
  13955. uvTransform: {
  13956. value: new Matrix3()
  13957. }
  13958. },
  13959. sprite: {
  13960. diffuse: {
  13961. value: new Color(0xffffff)
  13962. },
  13963. opacity: {
  13964. value: 1.0
  13965. },
  13966. center: {
  13967. value: new Vector2(0.5, 0.5)
  13968. },
  13969. rotation: {
  13970. value: 0.0
  13971. },
  13972. map: {
  13973. value: null
  13974. },
  13975. alphaMap: {
  13976. value: null
  13977. },
  13978. alphaTest: {
  13979. value: 0
  13980. },
  13981. uvTransform: {
  13982. value: new Matrix3()
  13983. }
  13984. }
  13985. };
  13986. const ShaderLib = {
  13987. basic: {
  13988. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  13989. vertexShader: ShaderChunk.meshbasic_vert,
  13990. fragmentShader: ShaderChunk.meshbasic_frag
  13991. },
  13992. lambert: {
  13993. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  13994. emissive: {
  13995. value: new Color(0x000000)
  13996. }
  13997. }]),
  13998. vertexShader: ShaderChunk.meshlambert_vert,
  13999. fragmentShader: ShaderChunk.meshlambert_frag
  14000. },
  14001. phong: {
  14002. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  14003. emissive: {
  14004. value: new Color(0x000000)
  14005. },
  14006. specular: {
  14007. value: new Color(0x111111)
  14008. },
  14009. shininess: {
  14010. value: 30
  14011. }
  14012. }]),
  14013. vertexShader: ShaderChunk.meshphong_vert,
  14014. fragmentShader: ShaderChunk.meshphong_frag
  14015. },
  14016. standard: {
  14017. 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, {
  14018. emissive: {
  14019. value: new Color(0x000000)
  14020. },
  14021. roughness: {
  14022. value: 1.0
  14023. },
  14024. metalness: {
  14025. value: 0.0
  14026. },
  14027. envMapIntensity: {
  14028. value: 1
  14029. } // temporary
  14030. }]),
  14031. vertexShader: ShaderChunk.meshphysical_vert,
  14032. fragmentShader: ShaderChunk.meshphysical_frag
  14033. },
  14034. toon: {
  14035. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  14036. emissive: {
  14037. value: new Color(0x000000)
  14038. }
  14039. }]),
  14040. vertexShader: ShaderChunk.meshtoon_vert,
  14041. fragmentShader: ShaderChunk.meshtoon_frag
  14042. },
  14043. matcap: {
  14044. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  14045. matcap: {
  14046. value: null
  14047. }
  14048. }]),
  14049. vertexShader: ShaderChunk.meshmatcap_vert,
  14050. fragmentShader: ShaderChunk.meshmatcap_frag
  14051. },
  14052. points: {
  14053. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  14054. vertexShader: ShaderChunk.points_vert,
  14055. fragmentShader: ShaderChunk.points_frag
  14056. },
  14057. dashed: {
  14058. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  14059. scale: {
  14060. value: 1
  14061. },
  14062. dashSize: {
  14063. value: 1
  14064. },
  14065. totalSize: {
  14066. value: 2
  14067. }
  14068. }]),
  14069. vertexShader: ShaderChunk.linedashed_vert,
  14070. fragmentShader: ShaderChunk.linedashed_frag
  14071. },
  14072. depth: {
  14073. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  14074. vertexShader: ShaderChunk.depth_vert,
  14075. fragmentShader: ShaderChunk.depth_frag
  14076. },
  14077. normal: {
  14078. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  14079. opacity: {
  14080. value: 1.0
  14081. }
  14082. }]),
  14083. vertexShader: ShaderChunk.meshnormal_vert,
  14084. fragmentShader: ShaderChunk.meshnormal_frag
  14085. },
  14086. sprite: {
  14087. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  14088. vertexShader: ShaderChunk.sprite_vert,
  14089. fragmentShader: ShaderChunk.sprite_frag
  14090. },
  14091. background: {
  14092. uniforms: {
  14093. uvTransform: {
  14094. value: new Matrix3()
  14095. },
  14096. t2D: {
  14097. value: null
  14098. }
  14099. },
  14100. vertexShader: ShaderChunk.background_vert,
  14101. fragmentShader: ShaderChunk.background_frag
  14102. },
  14103. /* -------------------------------------------------------------------------
  14104. // Cube map shader
  14105. ------------------------------------------------------------------------- */
  14106. cube: {
  14107. uniforms: mergeUniforms([UniformsLib.envmap, {
  14108. opacity: {
  14109. value: 1.0
  14110. }
  14111. }]),
  14112. vertexShader: ShaderChunk.cube_vert,
  14113. fragmentShader: ShaderChunk.cube_frag
  14114. },
  14115. equirect: {
  14116. uniforms: {
  14117. tEquirect: {
  14118. value: null
  14119. }
  14120. },
  14121. vertexShader: ShaderChunk.equirect_vert,
  14122. fragmentShader: ShaderChunk.equirect_frag
  14123. },
  14124. distanceRGBA: {
  14125. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  14126. referencePosition: {
  14127. value: new Vector3()
  14128. },
  14129. nearDistance: {
  14130. value: 1
  14131. },
  14132. farDistance: {
  14133. value: 1000
  14134. }
  14135. }]),
  14136. vertexShader: ShaderChunk.distanceRGBA_vert,
  14137. fragmentShader: ShaderChunk.distanceRGBA_frag
  14138. },
  14139. shadow: {
  14140. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  14141. color: {
  14142. value: new Color(0x00000)
  14143. },
  14144. opacity: {
  14145. value: 1.0
  14146. }
  14147. }]),
  14148. vertexShader: ShaderChunk.shadow_vert,
  14149. fragmentShader: ShaderChunk.shadow_frag
  14150. }
  14151. };
  14152. ShaderLib.physical = {
  14153. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  14154. clearcoat: {
  14155. value: 0
  14156. },
  14157. clearcoatMap: {
  14158. value: null
  14159. },
  14160. clearcoatRoughness: {
  14161. value: 0
  14162. },
  14163. clearcoatRoughnessMap: {
  14164. value: null
  14165. },
  14166. clearcoatNormalScale: {
  14167. value: new Vector2(1, 1)
  14168. },
  14169. clearcoatNormalMap: {
  14170. value: null
  14171. },
  14172. sheen: {
  14173. value: 0
  14174. },
  14175. sheenTint: {
  14176. value: new Color(0x000000)
  14177. },
  14178. sheenRoughness: {
  14179. value: 0
  14180. },
  14181. transmission: {
  14182. value: 0
  14183. },
  14184. transmissionMap: {
  14185. value: null
  14186. },
  14187. transmissionSamplerSize: {
  14188. value: new Vector2()
  14189. },
  14190. transmissionSamplerMap: {
  14191. value: null
  14192. },
  14193. thickness: {
  14194. value: 0
  14195. },
  14196. thicknessMap: {
  14197. value: null
  14198. },
  14199. attenuationDistance: {
  14200. value: 0
  14201. },
  14202. attenuationTint: {
  14203. value: new Color(0x000000)
  14204. },
  14205. specularIntensity: {
  14206. value: 0
  14207. },
  14208. specularIntensityMap: {
  14209. value: null
  14210. },
  14211. specularTint: {
  14212. value: new Color(1, 1, 1)
  14213. },
  14214. specularTintMap: {
  14215. value: null
  14216. }
  14217. }]),
  14218. vertexShader: ShaderChunk.meshphysical_vert,
  14219. fragmentShader: ShaderChunk.meshphysical_frag
  14220. };
  14221. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  14222. const clearColor = new Color(0x000000);
  14223. let clearAlpha = 0;
  14224. let planeMesh;
  14225. let boxMesh;
  14226. let currentBackground = null;
  14227. let currentBackgroundVersion = 0;
  14228. let currentTonemapping = null;
  14229. function render(renderList, scene) {
  14230. let forceClear = false;
  14231. let background = scene.isScene === true ? scene.background : null;
  14232. if (background && background.isTexture) {
  14233. background = cubemaps.get(background);
  14234. } // Ignore background in AR
  14235. // TODO: Reconsider this.
  14236. const xr = renderer.xr;
  14237. const session = xr.getSession && xr.getSession();
  14238. if (session && session.environmentBlendMode === 'additive') {
  14239. background = null;
  14240. }
  14241. if (background === null) {
  14242. setClear(clearColor, clearAlpha);
  14243. } else if (background && background.isColor) {
  14244. setClear(background, 1);
  14245. forceClear = true;
  14246. }
  14247. if (renderer.autoClear || forceClear) {
  14248. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  14249. }
  14250. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  14251. if (boxMesh === undefined) {
  14252. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  14253. name: 'BackgroundCubeMaterial',
  14254. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  14255. vertexShader: ShaderLib.cube.vertexShader,
  14256. fragmentShader: ShaderLib.cube.fragmentShader,
  14257. side: BackSide,
  14258. depthTest: false,
  14259. depthWrite: false,
  14260. fog: false
  14261. }));
  14262. boxMesh.geometry.deleteAttribute('normal');
  14263. boxMesh.geometry.deleteAttribute('uv');
  14264. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  14265. this.matrixWorld.copyPosition(camera.matrixWorld);
  14266. }; // enable code injection for non-built-in material
  14267. Object.defineProperty(boxMesh.material, 'envMap', {
  14268. get: function () {
  14269. return this.uniforms.envMap.value;
  14270. }
  14271. });
  14272. objects.update(boxMesh);
  14273. }
  14274. boxMesh.material.uniforms.envMap.value = background;
  14275. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  14276. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  14277. boxMesh.material.needsUpdate = true;
  14278. currentBackground = background;
  14279. currentBackgroundVersion = background.version;
  14280. currentTonemapping = renderer.toneMapping;
  14281. } // push to the pre-sorted opaque render list
  14282. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  14283. } else if (background && background.isTexture) {
  14284. if (planeMesh === undefined) {
  14285. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  14286. name: 'BackgroundMaterial',
  14287. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  14288. vertexShader: ShaderLib.background.vertexShader,
  14289. fragmentShader: ShaderLib.background.fragmentShader,
  14290. side: FrontSide,
  14291. depthTest: false,
  14292. depthWrite: false,
  14293. fog: false
  14294. }));
  14295. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  14296. Object.defineProperty(planeMesh.material, 'map', {
  14297. get: function () {
  14298. return this.uniforms.t2D.value;
  14299. }
  14300. });
  14301. objects.update(planeMesh);
  14302. }
  14303. planeMesh.material.uniforms.t2D.value = background;
  14304. if (background.matrixAutoUpdate === true) {
  14305. background.updateMatrix();
  14306. }
  14307. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  14308. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  14309. planeMesh.material.needsUpdate = true;
  14310. currentBackground = background;
  14311. currentBackgroundVersion = background.version;
  14312. currentTonemapping = renderer.toneMapping;
  14313. } // push to the pre-sorted opaque render list
  14314. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  14315. }
  14316. }
  14317. function setClear(color, alpha) {
  14318. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  14319. }
  14320. return {
  14321. getClearColor: function () {
  14322. return clearColor;
  14323. },
  14324. setClearColor: function (color, alpha = 1) {
  14325. clearColor.set(color);
  14326. clearAlpha = alpha;
  14327. setClear(clearColor, clearAlpha);
  14328. },
  14329. getClearAlpha: function () {
  14330. return clearAlpha;
  14331. },
  14332. setClearAlpha: function (alpha) {
  14333. clearAlpha = alpha;
  14334. setClear(clearColor, clearAlpha);
  14335. },
  14336. render: render
  14337. };
  14338. }
  14339. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  14340. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  14341. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  14342. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  14343. const bindingStates = {};
  14344. const defaultState = createBindingState(null);
  14345. let currentState = defaultState;
  14346. function setup(object, material, program, geometry, index) {
  14347. let updateBuffers = false;
  14348. if (vaoAvailable) {
  14349. const state = getBindingState(geometry, program, material);
  14350. if (currentState !== state) {
  14351. currentState = state;
  14352. bindVertexArrayObject(currentState.object);
  14353. }
  14354. updateBuffers = needsUpdate(geometry, index);
  14355. if (updateBuffers) saveCache(geometry, index);
  14356. } else {
  14357. const wireframe = material.wireframe === true;
  14358. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  14359. currentState.geometry = geometry.id;
  14360. currentState.program = program.id;
  14361. currentState.wireframe = wireframe;
  14362. updateBuffers = true;
  14363. }
  14364. }
  14365. if (object.isInstancedMesh === true) {
  14366. updateBuffers = true;
  14367. }
  14368. if (index !== null) {
  14369. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  14370. }
  14371. if (updateBuffers) {
  14372. setupVertexAttributes(object, material, program, geometry);
  14373. if (index !== null) {
  14374. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  14375. }
  14376. }
  14377. }
  14378. function createVertexArrayObject() {
  14379. if (capabilities.isWebGL2) return gl.createVertexArray();
  14380. return extension.createVertexArrayOES();
  14381. }
  14382. function bindVertexArrayObject(vao) {
  14383. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  14384. return extension.bindVertexArrayOES(vao);
  14385. }
  14386. function deleteVertexArrayObject(vao) {
  14387. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  14388. return extension.deleteVertexArrayOES(vao);
  14389. }
  14390. function getBindingState(geometry, program, material) {
  14391. const wireframe = material.wireframe === true;
  14392. let programMap = bindingStates[geometry.id];
  14393. if (programMap === undefined) {
  14394. programMap = {};
  14395. bindingStates[geometry.id] = programMap;
  14396. }
  14397. let stateMap = programMap[program.id];
  14398. if (stateMap === undefined) {
  14399. stateMap = {};
  14400. programMap[program.id] = stateMap;
  14401. }
  14402. let state = stateMap[wireframe];
  14403. if (state === undefined) {
  14404. state = createBindingState(createVertexArrayObject());
  14405. stateMap[wireframe] = state;
  14406. }
  14407. return state;
  14408. }
  14409. function createBindingState(vao) {
  14410. const newAttributes = [];
  14411. const enabledAttributes = [];
  14412. const attributeDivisors = [];
  14413. for (let i = 0; i < maxVertexAttributes; i++) {
  14414. newAttributes[i] = 0;
  14415. enabledAttributes[i] = 0;
  14416. attributeDivisors[i] = 0;
  14417. }
  14418. return {
  14419. // for backward compatibility on non-VAO support browser
  14420. geometry: null,
  14421. program: null,
  14422. wireframe: false,
  14423. newAttributes: newAttributes,
  14424. enabledAttributes: enabledAttributes,
  14425. attributeDivisors: attributeDivisors,
  14426. object: vao,
  14427. attributes: {},
  14428. index: null
  14429. };
  14430. }
  14431. function needsUpdate(geometry, index) {
  14432. const cachedAttributes = currentState.attributes;
  14433. const geometryAttributes = geometry.attributes;
  14434. let attributesNum = 0;
  14435. for (const key in geometryAttributes) {
  14436. const cachedAttribute = cachedAttributes[key];
  14437. const geometryAttribute = geometryAttributes[key];
  14438. if (cachedAttribute === undefined) return true;
  14439. if (cachedAttribute.attribute !== geometryAttribute) return true;
  14440. if (cachedAttribute.data !== geometryAttribute.data) return true;
  14441. attributesNum++;
  14442. }
  14443. if (currentState.attributesNum !== attributesNum) return true;
  14444. if (currentState.index !== index) return true;
  14445. return false;
  14446. }
  14447. function saveCache(geometry, index) {
  14448. const cache = {};
  14449. const attributes = geometry.attributes;
  14450. let attributesNum = 0;
  14451. for (const key in attributes) {
  14452. const attribute = attributes[key];
  14453. const data = {};
  14454. data.attribute = attribute;
  14455. if (attribute.data) {
  14456. data.data = attribute.data;
  14457. }
  14458. cache[key] = data;
  14459. attributesNum++;
  14460. }
  14461. currentState.attributes = cache;
  14462. currentState.attributesNum = attributesNum;
  14463. currentState.index = index;
  14464. }
  14465. function initAttributes() {
  14466. const newAttributes = currentState.newAttributes;
  14467. for (let i = 0, il = newAttributes.length; i < il; i++) {
  14468. newAttributes[i] = 0;
  14469. }
  14470. }
  14471. function enableAttribute(attribute) {
  14472. enableAttributeAndDivisor(attribute, 0);
  14473. }
  14474. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  14475. const newAttributes = currentState.newAttributes;
  14476. const enabledAttributes = currentState.enabledAttributes;
  14477. const attributeDivisors = currentState.attributeDivisors;
  14478. newAttributes[attribute] = 1;
  14479. if (enabledAttributes[attribute] === 0) {
  14480. gl.enableVertexAttribArray(attribute);
  14481. enabledAttributes[attribute] = 1;
  14482. }
  14483. if (attributeDivisors[attribute] !== meshPerAttribute) {
  14484. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  14485. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  14486. attributeDivisors[attribute] = meshPerAttribute;
  14487. }
  14488. }
  14489. function disableUnusedAttributes() {
  14490. const newAttributes = currentState.newAttributes;
  14491. const enabledAttributes = currentState.enabledAttributes;
  14492. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  14493. if (enabledAttributes[i] !== newAttributes[i]) {
  14494. gl.disableVertexAttribArray(i);
  14495. enabledAttributes[i] = 0;
  14496. }
  14497. }
  14498. }
  14499. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  14500. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  14501. gl.vertexAttribIPointer(index, size, type, stride, offset);
  14502. } else {
  14503. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  14504. }
  14505. }
  14506. function setupVertexAttributes(object, material, program, geometry) {
  14507. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  14508. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  14509. }
  14510. initAttributes();
  14511. const geometryAttributes = geometry.attributes;
  14512. const programAttributes = program.getAttributes();
  14513. const materialDefaultAttributeValues = material.defaultAttributeValues;
  14514. for (const name in programAttributes) {
  14515. const programAttribute = programAttributes[name];
  14516. if (programAttribute.location >= 0) {
  14517. let geometryAttribute = geometryAttributes[name];
  14518. if (geometryAttribute === undefined) {
  14519. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  14520. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  14521. }
  14522. if (geometryAttribute !== undefined) {
  14523. const normalized = geometryAttribute.normalized;
  14524. const size = geometryAttribute.itemSize;
  14525. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  14526. if (attribute === undefined) continue;
  14527. const buffer = attribute.buffer;
  14528. const type = attribute.type;
  14529. const bytesPerElement = attribute.bytesPerElement;
  14530. if (geometryAttribute.isInterleavedBufferAttribute) {
  14531. const data = geometryAttribute.data;
  14532. const stride = data.stride;
  14533. const offset = geometryAttribute.offset;
  14534. if (data && data.isInstancedInterleavedBuffer) {
  14535. for (let i = 0; i < programAttribute.locationSize; i++) {
  14536. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  14537. }
  14538. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  14539. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  14540. }
  14541. } else {
  14542. for (let i = 0; i < programAttribute.locationSize; i++) {
  14543. enableAttribute(programAttribute.location + i);
  14544. }
  14545. }
  14546. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  14547. for (let i = 0; i < programAttribute.locationSize; i++) {
  14548. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  14549. }
  14550. } else {
  14551. if (geometryAttribute.isInstancedBufferAttribute) {
  14552. for (let i = 0; i < programAttribute.locationSize; i++) {
  14553. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  14554. }
  14555. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  14556. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  14557. }
  14558. } else {
  14559. for (let i = 0; i < programAttribute.locationSize; i++) {
  14560. enableAttribute(programAttribute.location + i);
  14561. }
  14562. }
  14563. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  14564. for (let i = 0; i < programAttribute.locationSize; i++) {
  14565. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  14566. }
  14567. }
  14568. } else if (materialDefaultAttributeValues !== undefined) {
  14569. const value = materialDefaultAttributeValues[name];
  14570. if (value !== undefined) {
  14571. switch (value.length) {
  14572. case 2:
  14573. gl.vertexAttrib2fv(programAttribute.location, value);
  14574. break;
  14575. case 3:
  14576. gl.vertexAttrib3fv(programAttribute.location, value);
  14577. break;
  14578. case 4:
  14579. gl.vertexAttrib4fv(programAttribute.location, value);
  14580. break;
  14581. default:
  14582. gl.vertexAttrib1fv(programAttribute.location, value);
  14583. }
  14584. }
  14585. }
  14586. }
  14587. }
  14588. disableUnusedAttributes();
  14589. }
  14590. function dispose() {
  14591. reset();
  14592. for (const geometryId in bindingStates) {
  14593. const programMap = bindingStates[geometryId];
  14594. for (const programId in programMap) {
  14595. const stateMap = programMap[programId];
  14596. for (const wireframe in stateMap) {
  14597. deleteVertexArrayObject(stateMap[wireframe].object);
  14598. delete stateMap[wireframe];
  14599. }
  14600. delete programMap[programId];
  14601. }
  14602. delete bindingStates[geometryId];
  14603. }
  14604. }
  14605. function releaseStatesOfGeometry(geometry) {
  14606. if (bindingStates[geometry.id] === undefined) return;
  14607. const programMap = bindingStates[geometry.id];
  14608. for (const programId in programMap) {
  14609. const stateMap = programMap[programId];
  14610. for (const wireframe in stateMap) {
  14611. deleteVertexArrayObject(stateMap[wireframe].object);
  14612. delete stateMap[wireframe];
  14613. }
  14614. delete programMap[programId];
  14615. }
  14616. delete bindingStates[geometry.id];
  14617. }
  14618. function releaseStatesOfProgram(program) {
  14619. for (const geometryId in bindingStates) {
  14620. const programMap = bindingStates[geometryId];
  14621. if (programMap[program.id] === undefined) continue;
  14622. const stateMap = programMap[program.id];
  14623. for (const wireframe in stateMap) {
  14624. deleteVertexArrayObject(stateMap[wireframe].object);
  14625. delete stateMap[wireframe];
  14626. }
  14627. delete programMap[program.id];
  14628. }
  14629. }
  14630. function reset() {
  14631. resetDefaultState();
  14632. if (currentState === defaultState) return;
  14633. currentState = defaultState;
  14634. bindVertexArrayObject(currentState.object);
  14635. } // for backward-compatilibity
  14636. function resetDefaultState() {
  14637. defaultState.geometry = null;
  14638. defaultState.program = null;
  14639. defaultState.wireframe = false;
  14640. }
  14641. return {
  14642. setup: setup,
  14643. reset: reset,
  14644. resetDefaultState: resetDefaultState,
  14645. dispose: dispose,
  14646. releaseStatesOfGeometry: releaseStatesOfGeometry,
  14647. releaseStatesOfProgram: releaseStatesOfProgram,
  14648. initAttributes: initAttributes,
  14649. enableAttribute: enableAttribute,
  14650. disableUnusedAttributes: disableUnusedAttributes
  14651. };
  14652. }
  14653. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  14654. const isWebGL2 = capabilities.isWebGL2;
  14655. let mode;
  14656. function setMode(value) {
  14657. mode = value;
  14658. }
  14659. function render(start, count) {
  14660. gl.drawArrays(mode, start, count);
  14661. info.update(count, mode, 1);
  14662. }
  14663. function renderInstances(start, count, primcount) {
  14664. if (primcount === 0) return;
  14665. let extension, methodName;
  14666. if (isWebGL2) {
  14667. extension = gl;
  14668. methodName = 'drawArraysInstanced';
  14669. } else {
  14670. extension = extensions.get('ANGLE_instanced_arrays');
  14671. methodName = 'drawArraysInstancedANGLE';
  14672. if (extension === null) {
  14673. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  14674. return;
  14675. }
  14676. }
  14677. extension[methodName](mode, start, count, primcount);
  14678. info.update(count, mode, primcount);
  14679. } //
  14680. this.setMode = setMode;
  14681. this.render = render;
  14682. this.renderInstances = renderInstances;
  14683. }
  14684. function WebGLCapabilities(gl, extensions, parameters) {
  14685. let maxAnisotropy;
  14686. function getMaxAnisotropy() {
  14687. if (maxAnisotropy !== undefined) return maxAnisotropy;
  14688. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  14689. const extension = extensions.get('EXT_texture_filter_anisotropic');
  14690. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  14691. } else {
  14692. maxAnisotropy = 0;
  14693. }
  14694. return maxAnisotropy;
  14695. }
  14696. function getMaxPrecision(precision) {
  14697. if (precision === 'highp') {
  14698. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  14699. return 'highp';
  14700. }
  14701. precision = 'mediump';
  14702. }
  14703. if (precision === 'mediump') {
  14704. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  14705. return 'mediump';
  14706. }
  14707. }
  14708. return 'lowp';
  14709. }
  14710. /* eslint-disable no-undef */
  14711. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  14712. /* eslint-enable no-undef */
  14713. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  14714. const maxPrecision = getMaxPrecision(precision);
  14715. if (maxPrecision !== precision) {
  14716. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  14717. precision = maxPrecision;
  14718. }
  14719. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  14720. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  14721. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  14722. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  14723. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  14724. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  14725. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  14726. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  14727. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  14728. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  14729. const vertexTextures = maxVertexTextures > 0;
  14730. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  14731. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  14732. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  14733. return {
  14734. isWebGL2: isWebGL2,
  14735. drawBuffers: drawBuffers,
  14736. getMaxAnisotropy: getMaxAnisotropy,
  14737. getMaxPrecision: getMaxPrecision,
  14738. precision: precision,
  14739. logarithmicDepthBuffer: logarithmicDepthBuffer,
  14740. maxTextures: maxTextures,
  14741. maxVertexTextures: maxVertexTextures,
  14742. maxTextureSize: maxTextureSize,
  14743. maxCubemapSize: maxCubemapSize,
  14744. maxAttributes: maxAttributes,
  14745. maxVertexUniforms: maxVertexUniforms,
  14746. maxVaryings: maxVaryings,
  14747. maxFragmentUniforms: maxFragmentUniforms,
  14748. vertexTextures: vertexTextures,
  14749. floatFragmentTextures: floatFragmentTextures,
  14750. floatVertexTextures: floatVertexTextures,
  14751. maxSamples: maxSamples
  14752. };
  14753. }
  14754. function WebGLClipping(properties) {
  14755. const scope = this;
  14756. let globalState = null,
  14757. numGlobalPlanes = 0,
  14758. localClippingEnabled = false,
  14759. renderingShadows = false;
  14760. const plane = new Plane(),
  14761. viewNormalMatrix = new Matrix3(),
  14762. uniform = {
  14763. value: null,
  14764. needsUpdate: false
  14765. };
  14766. this.uniform = uniform;
  14767. this.numPlanes = 0;
  14768. this.numIntersection = 0;
  14769. this.init = function (planes, enableLocalClipping, camera) {
  14770. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  14771. // run another frame in order to reset the state:
  14772. numGlobalPlanes !== 0 || localClippingEnabled;
  14773. localClippingEnabled = enableLocalClipping;
  14774. globalState = projectPlanes(planes, camera, 0);
  14775. numGlobalPlanes = planes.length;
  14776. return enabled;
  14777. };
  14778. this.beginShadows = function () {
  14779. renderingShadows = true;
  14780. projectPlanes(null);
  14781. };
  14782. this.endShadows = function () {
  14783. renderingShadows = false;
  14784. resetGlobalState();
  14785. };
  14786. this.setState = function (material, camera, useCache) {
  14787. const planes = material.clippingPlanes,
  14788. clipIntersection = material.clipIntersection,
  14789. clipShadows = material.clipShadows;
  14790. const materialProperties = properties.get(material);
  14791. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  14792. // there's no local clipping
  14793. if (renderingShadows) {
  14794. // there's no global clipping
  14795. projectPlanes(null);
  14796. } else {
  14797. resetGlobalState();
  14798. }
  14799. } else {
  14800. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  14801. lGlobal = nGlobal * 4;
  14802. let dstArray = materialProperties.clippingState || null;
  14803. uniform.value = dstArray; // ensure unique state
  14804. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  14805. for (let i = 0; i !== lGlobal; ++i) {
  14806. dstArray[i] = globalState[i];
  14807. }
  14808. materialProperties.clippingState = dstArray;
  14809. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  14810. this.numPlanes += nGlobal;
  14811. }
  14812. };
  14813. function resetGlobalState() {
  14814. if (uniform.value !== globalState) {
  14815. uniform.value = globalState;
  14816. uniform.needsUpdate = numGlobalPlanes > 0;
  14817. }
  14818. scope.numPlanes = numGlobalPlanes;
  14819. scope.numIntersection = 0;
  14820. }
  14821. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  14822. const nPlanes = planes !== null ? planes.length : 0;
  14823. let dstArray = null;
  14824. if (nPlanes !== 0) {
  14825. dstArray = uniform.value;
  14826. if (skipTransform !== true || dstArray === null) {
  14827. const flatSize = dstOffset + nPlanes * 4,
  14828. viewMatrix = camera.matrixWorldInverse;
  14829. viewNormalMatrix.getNormalMatrix(viewMatrix);
  14830. if (dstArray === null || dstArray.length < flatSize) {
  14831. dstArray = new Float32Array(flatSize);
  14832. }
  14833. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  14834. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  14835. plane.normal.toArray(dstArray, i4);
  14836. dstArray[i4 + 3] = plane.constant;
  14837. }
  14838. }
  14839. uniform.value = dstArray;
  14840. uniform.needsUpdate = true;
  14841. }
  14842. scope.numPlanes = nPlanes;
  14843. scope.numIntersection = 0;
  14844. return dstArray;
  14845. }
  14846. }
  14847. function WebGLCubeMaps(renderer) {
  14848. let cubemaps = new WeakMap();
  14849. function mapTextureMapping(texture, mapping) {
  14850. if (mapping === EquirectangularReflectionMapping) {
  14851. texture.mapping = CubeReflectionMapping;
  14852. } else if (mapping === EquirectangularRefractionMapping) {
  14853. texture.mapping = CubeRefractionMapping;
  14854. }
  14855. return texture;
  14856. }
  14857. function get(texture) {
  14858. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  14859. const mapping = texture.mapping;
  14860. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  14861. if (cubemaps.has(texture)) {
  14862. const cubemap = cubemaps.get(texture).texture;
  14863. return mapTextureMapping(cubemap, texture.mapping);
  14864. } else {
  14865. const image = texture.image;
  14866. if (image && image.height > 0) {
  14867. const currentRenderTarget = renderer.getRenderTarget();
  14868. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  14869. renderTarget.fromEquirectangularTexture(renderer, texture);
  14870. cubemaps.set(texture, renderTarget);
  14871. renderer.setRenderTarget(currentRenderTarget);
  14872. texture.addEventListener('dispose', onTextureDispose);
  14873. return mapTextureMapping(renderTarget.texture, texture.mapping);
  14874. } else {
  14875. // image not yet ready. try the conversion next frame
  14876. return null;
  14877. }
  14878. }
  14879. }
  14880. }
  14881. return texture;
  14882. }
  14883. function onTextureDispose(event) {
  14884. const texture = event.target;
  14885. texture.removeEventListener('dispose', onTextureDispose);
  14886. const cubemap = cubemaps.get(texture);
  14887. if (cubemap !== undefined) {
  14888. cubemaps.delete(texture);
  14889. cubemap.dispose();
  14890. }
  14891. }
  14892. function dispose() {
  14893. cubemaps = new WeakMap();
  14894. }
  14895. return {
  14896. get: get,
  14897. dispose: dispose
  14898. };
  14899. }
  14900. class OrthographicCamera extends Camera {
  14901. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  14902. super();
  14903. this.type = 'OrthographicCamera';
  14904. this.zoom = 1;
  14905. this.view = null;
  14906. this.left = left;
  14907. this.right = right;
  14908. this.top = top;
  14909. this.bottom = bottom;
  14910. this.near = near;
  14911. this.far = far;
  14912. this.updateProjectionMatrix();
  14913. }
  14914. copy(source, recursive) {
  14915. super.copy(source, recursive);
  14916. this.left = source.left;
  14917. this.right = source.right;
  14918. this.top = source.top;
  14919. this.bottom = source.bottom;
  14920. this.near = source.near;
  14921. this.far = source.far;
  14922. this.zoom = source.zoom;
  14923. this.view = source.view === null ? null : Object.assign({}, source.view);
  14924. return this;
  14925. }
  14926. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  14927. if (this.view === null) {
  14928. this.view = {
  14929. enabled: true,
  14930. fullWidth: 1,
  14931. fullHeight: 1,
  14932. offsetX: 0,
  14933. offsetY: 0,
  14934. width: 1,
  14935. height: 1
  14936. };
  14937. }
  14938. this.view.enabled = true;
  14939. this.view.fullWidth = fullWidth;
  14940. this.view.fullHeight = fullHeight;
  14941. this.view.offsetX = x;
  14942. this.view.offsetY = y;
  14943. this.view.width = width;
  14944. this.view.height = height;
  14945. this.updateProjectionMatrix();
  14946. }
  14947. clearViewOffset() {
  14948. if (this.view !== null) {
  14949. this.view.enabled = false;
  14950. }
  14951. this.updateProjectionMatrix();
  14952. }
  14953. updateProjectionMatrix() {
  14954. const dx = (this.right - this.left) / (2 * this.zoom);
  14955. const dy = (this.top - this.bottom) / (2 * this.zoom);
  14956. const cx = (this.right + this.left) / 2;
  14957. const cy = (this.top + this.bottom) / 2;
  14958. let left = cx - dx;
  14959. let right = cx + dx;
  14960. let top = cy + dy;
  14961. let bottom = cy - dy;
  14962. if (this.view !== null && this.view.enabled) {
  14963. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  14964. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  14965. left += scaleW * this.view.offsetX;
  14966. right = left + scaleW * this.view.width;
  14967. top -= scaleH * this.view.offsetY;
  14968. bottom = top - scaleH * this.view.height;
  14969. }
  14970. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  14971. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  14972. }
  14973. toJSON(meta) {
  14974. const data = super.toJSON(meta);
  14975. data.object.zoom = this.zoom;
  14976. data.object.left = this.left;
  14977. data.object.right = this.right;
  14978. data.object.top = this.top;
  14979. data.object.bottom = this.bottom;
  14980. data.object.near = this.near;
  14981. data.object.far = this.far;
  14982. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  14983. return data;
  14984. }
  14985. }
  14986. OrthographicCamera.prototype.isOrthographicCamera = true;
  14987. class RawShaderMaterial extends ShaderMaterial {
  14988. constructor(parameters) {
  14989. super(parameters);
  14990. this.type = 'RawShaderMaterial';
  14991. }
  14992. }
  14993. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  14994. const LOD_MIN = 4;
  14995. const LOD_MAX = 8;
  14996. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  14997. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14998. // geometric shadowing function. These sigma values squared must match the
  14999. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15000. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  15001. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15002. // samples and exit early, but not recompile the shader.
  15003. const MAX_SAMPLES = 20;
  15004. const ENCODINGS = {
  15005. [LinearEncoding]: 0,
  15006. [sRGBEncoding]: 1,
  15007. [RGBEEncoding]: 2,
  15008. [RGBM7Encoding]: 3,
  15009. [RGBM16Encoding]: 4,
  15010. [RGBDEncoding]: 5,
  15011. [GammaEncoding]: 6
  15012. };
  15013. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  15014. const {
  15015. _lodPlanes,
  15016. _sizeLods,
  15017. _sigmas
  15018. } = /*@__PURE__*/_createPlanes();
  15019. const _clearColor = /*@__PURE__*/new Color();
  15020. let _oldTarget = null; // Golden Ratio
  15021. const PHI = (1 + Math.sqrt(5)) / 2;
  15022. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  15023. // same axis), used as axis directions evenly spread on a sphere.
  15024. const _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)];
  15025. /**
  15026. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15027. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15028. * blur to be quickly accessed based on material roughness. It is packed into a
  15029. * special CubeUV format that allows us to perform custom interpolation so that
  15030. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15031. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15032. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15033. * higher roughness levels. In this way we maintain resolution to smoothly
  15034. * interpolate diffuse lighting while limiting sampling computation.
  15035. *
  15036. * Paper: Fast, Accurate Image-Based Lighting
  15037. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  15038. */
  15039. class PMREMGenerator {
  15040. constructor(renderer) {
  15041. this._renderer = renderer;
  15042. this._pingPongRenderTarget = null;
  15043. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  15044. this._equirectShader = null;
  15045. this._cubemapShader = null;
  15046. this._compileMaterial(this._blurMaterial);
  15047. }
  15048. /**
  15049. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15050. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15051. * in radians to be applied to the scene before PMREM generation. Optional near
  15052. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15053. * is placed at the origin).
  15054. */
  15055. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  15056. _oldTarget = this._renderer.getRenderTarget();
  15057. const cubeUVRenderTarget = this._allocateTargets();
  15058. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  15059. if (sigma > 0) {
  15060. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  15061. }
  15062. this._applyPMREM(cubeUVRenderTarget);
  15063. this._cleanup(cubeUVRenderTarget);
  15064. return cubeUVRenderTarget;
  15065. }
  15066. /**
  15067. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15068. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  15069. * as this matches best with the 256 x 256 cubemap output.
  15070. */
  15071. fromEquirectangular(equirectangular) {
  15072. return this._fromTexture(equirectangular);
  15073. }
  15074. /**
  15075. * Generates a PMREM from an cubemap texture, which can be either LDR
  15076. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  15077. * as this matches best with the 256 x 256 cubemap output.
  15078. */
  15079. fromCubemap(cubemap) {
  15080. return this._fromTexture(cubemap);
  15081. }
  15082. /**
  15083. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  15084. * your texture's network fetch for increased concurrency.
  15085. */
  15086. compileCubemapShader() {
  15087. if (this._cubemapShader === null) {
  15088. this._cubemapShader = _getCubemapShader();
  15089. this._compileMaterial(this._cubemapShader);
  15090. }
  15091. }
  15092. /**
  15093. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  15094. * your texture's network fetch for increased concurrency.
  15095. */
  15096. compileEquirectangularShader() {
  15097. if (this._equirectShader === null) {
  15098. this._equirectShader = _getEquirectShader();
  15099. this._compileMaterial(this._equirectShader);
  15100. }
  15101. }
  15102. /**
  15103. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  15104. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  15105. * one of them will cause any others to also become unusable.
  15106. */
  15107. dispose() {
  15108. this._blurMaterial.dispose();
  15109. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  15110. if (this._equirectShader !== null) this._equirectShader.dispose();
  15111. for (let i = 0; i < _lodPlanes.length; i++) {
  15112. _lodPlanes[i].dispose();
  15113. }
  15114. } // private interface
  15115. _cleanup(outputTarget) {
  15116. this._pingPongRenderTarget.dispose();
  15117. this._renderer.setRenderTarget(_oldTarget);
  15118. outputTarget.scissorTest = false;
  15119. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  15120. }
  15121. _fromTexture(texture) {
  15122. _oldTarget = this._renderer.getRenderTarget();
  15123. const cubeUVRenderTarget = this._allocateTargets(texture);
  15124. this._textureToCubeUV(texture, cubeUVRenderTarget);
  15125. this._applyPMREM(cubeUVRenderTarget);
  15126. this._cleanup(cubeUVRenderTarget);
  15127. return cubeUVRenderTarget;
  15128. }
  15129. _allocateTargets(texture) {
  15130. // warning: null texture is valid
  15131. const params = {
  15132. magFilter: NearestFilter,
  15133. minFilter: NearestFilter,
  15134. generateMipmaps: false,
  15135. type: UnsignedByteType,
  15136. format: RGBEFormat,
  15137. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  15138. depthBuffer: false
  15139. };
  15140. const cubeUVRenderTarget = _createRenderTarget(params);
  15141. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  15142. this._pingPongRenderTarget = _createRenderTarget(params);
  15143. return cubeUVRenderTarget;
  15144. }
  15145. _compileMaterial(material) {
  15146. const tmpMesh = new Mesh(_lodPlanes[0], material);
  15147. this._renderer.compile(tmpMesh, _flatCamera);
  15148. }
  15149. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  15150. const fov = 90;
  15151. const aspect = 1;
  15152. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  15153. const upSign = [1, -1, 1, 1, 1, 1];
  15154. const forwardSign = [1, 1, 1, -1, -1, -1];
  15155. const renderer = this._renderer;
  15156. const originalAutoClear = renderer.autoClear;
  15157. const outputEncoding = renderer.outputEncoding;
  15158. const toneMapping = renderer.toneMapping;
  15159. renderer.getClearColor(_clearColor);
  15160. renderer.toneMapping = NoToneMapping;
  15161. renderer.outputEncoding = LinearEncoding;
  15162. renderer.autoClear = false;
  15163. const backgroundMaterial = new MeshBasicMaterial({
  15164. name: 'PMREM.Background',
  15165. side: BackSide,
  15166. depthWrite: false,
  15167. depthTest: false
  15168. });
  15169. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  15170. let useSolidColor = false;
  15171. const background = scene.background;
  15172. if (background) {
  15173. if (background.isColor) {
  15174. backgroundMaterial.color.copy(background);
  15175. scene.background = null;
  15176. useSolidColor = true;
  15177. }
  15178. } else {
  15179. backgroundMaterial.color.copy(_clearColor);
  15180. useSolidColor = true;
  15181. }
  15182. for (let i = 0; i < 6; i++) {
  15183. const col = i % 3;
  15184. if (col == 0) {
  15185. cubeCamera.up.set(0, upSign[i], 0);
  15186. cubeCamera.lookAt(forwardSign[i], 0, 0);
  15187. } else if (col == 1) {
  15188. cubeCamera.up.set(0, 0, upSign[i]);
  15189. cubeCamera.lookAt(0, forwardSign[i], 0);
  15190. } else {
  15191. cubeCamera.up.set(0, upSign[i], 0);
  15192. cubeCamera.lookAt(0, 0, forwardSign[i]);
  15193. }
  15194. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  15195. renderer.setRenderTarget(cubeUVRenderTarget);
  15196. if (useSolidColor) {
  15197. renderer.render(backgroundBox, cubeCamera);
  15198. }
  15199. renderer.render(scene, cubeCamera);
  15200. }
  15201. backgroundBox.geometry.dispose();
  15202. backgroundBox.material.dispose();
  15203. renderer.toneMapping = toneMapping;
  15204. renderer.outputEncoding = outputEncoding;
  15205. renderer.autoClear = originalAutoClear;
  15206. scene.background = background;
  15207. }
  15208. _setEncoding(uniform, texture) {
  15209. if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
  15210. uniform.value = ENCODINGS[LinearEncoding];
  15211. } else {
  15212. uniform.value = ENCODINGS[texture.encoding];
  15213. }
  15214. }
  15215. _textureToCubeUV(texture, cubeUVRenderTarget) {
  15216. const renderer = this._renderer;
  15217. if (texture.isCubeTexture) {
  15218. if (this._cubemapShader == null) {
  15219. this._cubemapShader = _getCubemapShader();
  15220. }
  15221. } else {
  15222. if (this._equirectShader == null) {
  15223. this._equirectShader = _getEquirectShader();
  15224. }
  15225. }
  15226. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  15227. const mesh = new Mesh(_lodPlanes[0], material);
  15228. const uniforms = material.uniforms;
  15229. uniforms['envMap'].value = texture;
  15230. if (!texture.isCubeTexture) {
  15231. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  15232. }
  15233. this._setEncoding(uniforms['inputEncoding'], texture);
  15234. this._setEncoding(uniforms['outputEncoding'], cubeUVRenderTarget.texture);
  15235. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  15236. renderer.setRenderTarget(cubeUVRenderTarget);
  15237. renderer.render(mesh, _flatCamera);
  15238. }
  15239. _applyPMREM(cubeUVRenderTarget) {
  15240. const renderer = this._renderer;
  15241. const autoClear = renderer.autoClear;
  15242. renderer.autoClear = false;
  15243. for (let i = 1; i < TOTAL_LODS; i++) {
  15244. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  15245. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  15246. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  15247. }
  15248. renderer.autoClear = autoClear;
  15249. }
  15250. /**
  15251. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  15252. * vertically and horizontally, but this breaks down on a cube. Here we apply
  15253. * the blur latitudinally (around the poles), and then longitudinally (towards
  15254. * the poles) to approximate the orthogonally-separable blur. It is least
  15255. * accurate at the poles, but still does a decent job.
  15256. */
  15257. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  15258. const pingPongRenderTarget = this._pingPongRenderTarget;
  15259. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  15260. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  15261. }
  15262. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  15263. const renderer = this._renderer;
  15264. const blurMaterial = this._blurMaterial;
  15265. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  15266. console.error('blur direction must be either latitudinal or longitudinal!');
  15267. } // Number of standard deviations at which to cut off the discrete approximation.
  15268. const STANDARD_DEVIATIONS = 3;
  15269. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  15270. const blurUniforms = blurMaterial.uniforms;
  15271. const pixels = _sizeLods[lodIn] - 1;
  15272. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  15273. const sigmaPixels = sigmaRadians / radiansPerPixel;
  15274. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  15275. if (samples > MAX_SAMPLES) {
  15276. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  15277. }
  15278. const weights = [];
  15279. let sum = 0;
  15280. for (let i = 0; i < MAX_SAMPLES; ++i) {
  15281. const x = i / sigmaPixels;
  15282. const weight = Math.exp(-x * x / 2);
  15283. weights.push(weight);
  15284. if (i == 0) {
  15285. sum += weight;
  15286. } else if (i < samples) {
  15287. sum += 2 * weight;
  15288. }
  15289. }
  15290. for (let i = 0; i < weights.length; i++) {
  15291. weights[i] = weights[i] / sum;
  15292. }
  15293. blurUniforms['envMap'].value = targetIn.texture;
  15294. blurUniforms['samples'].value = samples;
  15295. blurUniforms['weights'].value = weights;
  15296. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  15297. if (poleAxis) {
  15298. blurUniforms['poleAxis'].value = poleAxis;
  15299. }
  15300. blurUniforms['dTheta'].value = radiansPerPixel;
  15301. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  15302. this._setEncoding(blurUniforms['inputEncoding'], targetIn.texture);
  15303. this._setEncoding(blurUniforms['outputEncoding'], targetIn.texture);
  15304. const outputSize = _sizeLods[lodOut];
  15305. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  15306. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  15307. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  15308. renderer.setRenderTarget(targetOut);
  15309. renderer.render(blurMesh, _flatCamera);
  15310. }
  15311. }
  15312. function _isLDR(texture) {
  15313. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  15314. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  15315. }
  15316. function _createPlanes() {
  15317. const _lodPlanes = [];
  15318. const _sizeLods = [];
  15319. const _sigmas = [];
  15320. let lod = LOD_MAX;
  15321. for (let i = 0; i < TOTAL_LODS; i++) {
  15322. const sizeLod = Math.pow(2, lod);
  15323. _sizeLods.push(sizeLod);
  15324. let sigma = 1.0 / sizeLod;
  15325. if (i > LOD_MAX - LOD_MIN) {
  15326. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  15327. } else if (i == 0) {
  15328. sigma = 0;
  15329. }
  15330. _sigmas.push(sigma);
  15331. const texelSize = 1.0 / (sizeLod - 1);
  15332. const min = -texelSize / 2;
  15333. const max = 1 + texelSize / 2;
  15334. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  15335. const cubeFaces = 6;
  15336. const vertices = 6;
  15337. const positionSize = 3;
  15338. const uvSize = 2;
  15339. const faceIndexSize = 1;
  15340. const position = new Float32Array(positionSize * vertices * cubeFaces);
  15341. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  15342. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  15343. for (let face = 0; face < cubeFaces; face++) {
  15344. const x = face % 3 * 2 / 3 - 1;
  15345. const y = face > 2 ? 0 : -1;
  15346. const 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];
  15347. position.set(coordinates, positionSize * vertices * face);
  15348. uv.set(uv1, uvSize * vertices * face);
  15349. const fill = [face, face, face, face, face, face];
  15350. faceIndex.set(fill, faceIndexSize * vertices * face);
  15351. }
  15352. const planes = new BufferGeometry();
  15353. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  15354. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  15355. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  15356. _lodPlanes.push(planes);
  15357. if (lod > LOD_MIN) {
  15358. lod--;
  15359. }
  15360. }
  15361. return {
  15362. _lodPlanes,
  15363. _sizeLods,
  15364. _sigmas
  15365. };
  15366. }
  15367. function _createRenderTarget(params) {
  15368. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  15369. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  15370. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  15371. cubeUVRenderTarget.scissorTest = true;
  15372. return cubeUVRenderTarget;
  15373. }
  15374. function _setViewport(target, x, y, width, height) {
  15375. target.viewport.set(x, y, width, height);
  15376. target.scissor.set(x, y, width, height);
  15377. }
  15378. function _getBlurShader(maxSamples) {
  15379. const weights = new Float32Array(maxSamples);
  15380. const poleAxis = new Vector3(0, 1, 0);
  15381. const shaderMaterial = new RawShaderMaterial({
  15382. name: 'SphericalGaussianBlur',
  15383. defines: {
  15384. 'n': maxSamples
  15385. },
  15386. uniforms: {
  15387. 'envMap': {
  15388. value: null
  15389. },
  15390. 'samples': {
  15391. value: 1
  15392. },
  15393. 'weights': {
  15394. value: weights
  15395. },
  15396. 'latitudinal': {
  15397. value: false
  15398. },
  15399. 'dTheta': {
  15400. value: 0
  15401. },
  15402. 'mipInt': {
  15403. value: 0
  15404. },
  15405. 'poleAxis': {
  15406. value: poleAxis
  15407. },
  15408. 'inputEncoding': {
  15409. value: ENCODINGS[LinearEncoding]
  15410. },
  15411. 'outputEncoding': {
  15412. value: ENCODINGS[LinearEncoding]
  15413. }
  15414. },
  15415. vertexShader: _getCommonVertexShader(),
  15416. fragmentShader:
  15417. /* glsl */
  15418. `
  15419. precision mediump float;
  15420. precision mediump int;
  15421. varying vec3 vOutputDirection;
  15422. uniform sampler2D envMap;
  15423. uniform int samples;
  15424. uniform float weights[ n ];
  15425. uniform bool latitudinal;
  15426. uniform float dTheta;
  15427. uniform float mipInt;
  15428. uniform vec3 poleAxis;
  15429. ${_getEncodings()}
  15430. #define ENVMAP_TYPE_CUBE_UV
  15431. #include <cube_uv_reflection_fragment>
  15432. vec3 getSample( float theta, vec3 axis ) {
  15433. float cosTheta = cos( theta );
  15434. // Rodrigues' axis-angle rotation
  15435. vec3 sampleDirection = vOutputDirection * cosTheta
  15436. + cross( axis, vOutputDirection ) * sin( theta )
  15437. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  15438. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  15439. }
  15440. void main() {
  15441. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  15442. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  15443. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  15444. }
  15445. axis = normalize( axis );
  15446. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  15447. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  15448. for ( int i = 1; i < n; i++ ) {
  15449. if ( i >= samples ) {
  15450. break;
  15451. }
  15452. float theta = dTheta * float( i );
  15453. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  15454. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  15455. }
  15456. gl_FragColor = linearToOutputTexel( gl_FragColor );
  15457. }
  15458. `,
  15459. blending: NoBlending,
  15460. depthTest: false,
  15461. depthWrite: false
  15462. });
  15463. return shaderMaterial;
  15464. }
  15465. function _getEquirectShader() {
  15466. const texelSize = new Vector2(1, 1);
  15467. const shaderMaterial = new RawShaderMaterial({
  15468. name: 'EquirectangularToCubeUV',
  15469. uniforms: {
  15470. 'envMap': {
  15471. value: null
  15472. },
  15473. 'texelSize': {
  15474. value: texelSize
  15475. },
  15476. 'inputEncoding': {
  15477. value: ENCODINGS[LinearEncoding]
  15478. },
  15479. 'outputEncoding': {
  15480. value: ENCODINGS[LinearEncoding]
  15481. }
  15482. },
  15483. vertexShader: _getCommonVertexShader(),
  15484. fragmentShader:
  15485. /* glsl */
  15486. `
  15487. precision mediump float;
  15488. precision mediump int;
  15489. varying vec3 vOutputDirection;
  15490. uniform sampler2D envMap;
  15491. uniform vec2 texelSize;
  15492. ${_getEncodings()}
  15493. #include <common>
  15494. void main() {
  15495. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  15496. vec3 outputDirection = normalize( vOutputDirection );
  15497. vec2 uv = equirectUv( outputDirection );
  15498. vec2 f = fract( uv / texelSize - 0.5 );
  15499. uv -= f * texelSize;
  15500. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  15501. uv.x += texelSize.x;
  15502. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  15503. uv.y += texelSize.y;
  15504. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  15505. uv.x -= texelSize.x;
  15506. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  15507. vec3 tm = mix( tl, tr, f.x );
  15508. vec3 bm = mix( bl, br, f.x );
  15509. gl_FragColor.rgb = mix( tm, bm, f.y );
  15510. gl_FragColor = linearToOutputTexel( gl_FragColor );
  15511. }
  15512. `,
  15513. blending: NoBlending,
  15514. depthTest: false,
  15515. depthWrite: false
  15516. });
  15517. return shaderMaterial;
  15518. }
  15519. function _getCubemapShader() {
  15520. const shaderMaterial = new RawShaderMaterial({
  15521. name: 'CubemapToCubeUV',
  15522. uniforms: {
  15523. 'envMap': {
  15524. value: null
  15525. },
  15526. 'inputEncoding': {
  15527. value: ENCODINGS[LinearEncoding]
  15528. },
  15529. 'outputEncoding': {
  15530. value: ENCODINGS[LinearEncoding]
  15531. }
  15532. },
  15533. vertexShader: _getCommonVertexShader(),
  15534. fragmentShader:
  15535. /* glsl */
  15536. `
  15537. precision mediump float;
  15538. precision mediump int;
  15539. varying vec3 vOutputDirection;
  15540. uniform samplerCube envMap;
  15541. ${_getEncodings()}
  15542. void main() {
  15543. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  15544. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  15545. gl_FragColor = linearToOutputTexel( gl_FragColor );
  15546. }
  15547. `,
  15548. blending: NoBlending,
  15549. depthTest: false,
  15550. depthWrite: false
  15551. });
  15552. return shaderMaterial;
  15553. }
  15554. function _getCommonVertexShader() {
  15555. return (
  15556. /* glsl */
  15557. `
  15558. precision mediump float;
  15559. precision mediump int;
  15560. attribute vec3 position;
  15561. attribute vec2 uv;
  15562. attribute float faceIndex;
  15563. varying vec3 vOutputDirection;
  15564. // RH coordinate system; PMREM face-indexing convention
  15565. vec3 getDirection( vec2 uv, float face ) {
  15566. uv = 2.0 * uv - 1.0;
  15567. vec3 direction = vec3( uv, 1.0 );
  15568. if ( face == 0.0 ) {
  15569. direction = direction.zyx; // ( 1, v, u ) pos x
  15570. } else if ( face == 1.0 ) {
  15571. direction = direction.xzy;
  15572. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  15573. } else if ( face == 2.0 ) {
  15574. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  15575. } else if ( face == 3.0 ) {
  15576. direction = direction.zyx;
  15577. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  15578. } else if ( face == 4.0 ) {
  15579. direction = direction.xzy;
  15580. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  15581. } else if ( face == 5.0 ) {
  15582. direction.z *= -1.0; // ( u, v, -1 ) neg z
  15583. }
  15584. return direction;
  15585. }
  15586. void main() {
  15587. vOutputDirection = getDirection( uv, faceIndex );
  15588. gl_Position = vec4( position, 1.0 );
  15589. }
  15590. `
  15591. );
  15592. }
  15593. function _getEncodings() {
  15594. return (
  15595. /* glsl */
  15596. `
  15597. uniform int inputEncoding;
  15598. uniform int outputEncoding;
  15599. #include <encodings_pars_fragment>
  15600. vec4 inputTexelToLinear( vec4 value ) {
  15601. if ( inputEncoding == 0 ) {
  15602. return value;
  15603. } else if ( inputEncoding == 1 ) {
  15604. return sRGBToLinear( value );
  15605. } else if ( inputEncoding == 2 ) {
  15606. return RGBEToLinear( value );
  15607. } else if ( inputEncoding == 3 ) {
  15608. return RGBMToLinear( value, 7.0 );
  15609. } else if ( inputEncoding == 4 ) {
  15610. return RGBMToLinear( value, 16.0 );
  15611. } else if ( inputEncoding == 5 ) {
  15612. return RGBDToLinear( value, 256.0 );
  15613. } else {
  15614. return GammaToLinear( value, 2.2 );
  15615. }
  15616. }
  15617. vec4 linearToOutputTexel( vec4 value ) {
  15618. if ( outputEncoding == 0 ) {
  15619. return value;
  15620. } else if ( outputEncoding == 1 ) {
  15621. return LinearTosRGB( value );
  15622. } else if ( outputEncoding == 2 ) {
  15623. return LinearToRGBE( value );
  15624. } else if ( outputEncoding == 3 ) {
  15625. return LinearToRGBM( value, 7.0 );
  15626. } else if ( outputEncoding == 4 ) {
  15627. return LinearToRGBM( value, 16.0 );
  15628. } else if ( outputEncoding == 5 ) {
  15629. return LinearToRGBD( value, 256.0 );
  15630. } else {
  15631. return LinearToGamma( value, 2.2 );
  15632. }
  15633. }
  15634. vec4 envMapTexelToLinear( vec4 color ) {
  15635. return inputTexelToLinear( color );
  15636. }
  15637. `
  15638. );
  15639. }
  15640. function WebGLCubeUVMaps(renderer) {
  15641. let cubeUVmaps = new WeakMap();
  15642. let pmremGenerator = null;
  15643. function get(texture) {
  15644. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  15645. const mapping = texture.mapping;
  15646. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  15647. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  15648. if (isEquirectMap || isCubeMap) {
  15649. // equirect/cube map to cubeUV conversion
  15650. if (cubeUVmaps.has(texture)) {
  15651. return cubeUVmaps.get(texture).texture;
  15652. } else {
  15653. const image = texture.image;
  15654. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  15655. const currentRenderTarget = renderer.getRenderTarget();
  15656. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  15657. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  15658. cubeUVmaps.set(texture, renderTarget);
  15659. renderer.setRenderTarget(currentRenderTarget);
  15660. texture.addEventListener('dispose', onTextureDispose);
  15661. return renderTarget.texture;
  15662. } else {
  15663. // image not yet ready. try the conversion next frame
  15664. return null;
  15665. }
  15666. }
  15667. }
  15668. }
  15669. return texture;
  15670. }
  15671. function isCubeTextureComplete(image) {
  15672. let count = 0;
  15673. const length = 6;
  15674. for (let i = 0; i < length; i++) {
  15675. if (image[i] !== undefined) count++;
  15676. }
  15677. return count === length;
  15678. }
  15679. function onTextureDispose(event) {
  15680. const texture = event.target;
  15681. texture.removeEventListener('dispose', onTextureDispose);
  15682. const cubemapUV = cubeUVmaps.get(texture);
  15683. if (cubemapUV !== undefined) {
  15684. cubeUVmaps.delete(texture);
  15685. cubemapUV.dispose();
  15686. }
  15687. }
  15688. function dispose() {
  15689. cubeUVmaps = new WeakMap();
  15690. if (pmremGenerator !== null) {
  15691. pmremGenerator.dispose();
  15692. pmremGenerator = null;
  15693. }
  15694. }
  15695. return {
  15696. get: get,
  15697. dispose: dispose
  15698. };
  15699. }
  15700. function WebGLExtensions(gl) {
  15701. const extensions = {};
  15702. function getExtension(name) {
  15703. if (extensions[name] !== undefined) {
  15704. return extensions[name];
  15705. }
  15706. let extension;
  15707. switch (name) {
  15708. case 'WEBGL_depth_texture':
  15709. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  15710. break;
  15711. case 'EXT_texture_filter_anisotropic':
  15712. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  15713. break;
  15714. case 'WEBGL_compressed_texture_s3tc':
  15715. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  15716. break;
  15717. case 'WEBGL_compressed_texture_pvrtc':
  15718. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  15719. break;
  15720. default:
  15721. extension = gl.getExtension(name);
  15722. }
  15723. extensions[name] = extension;
  15724. return extension;
  15725. }
  15726. return {
  15727. has: function (name) {
  15728. return getExtension(name) !== null;
  15729. },
  15730. init: function (capabilities) {
  15731. if (capabilities.isWebGL2) {
  15732. getExtension('EXT_color_buffer_float');
  15733. } else {
  15734. getExtension('WEBGL_depth_texture');
  15735. getExtension('OES_texture_float');
  15736. getExtension('OES_texture_half_float');
  15737. getExtension('OES_texture_half_float_linear');
  15738. getExtension('OES_standard_derivatives');
  15739. getExtension('OES_element_index_uint');
  15740. getExtension('OES_vertex_array_object');
  15741. getExtension('ANGLE_instanced_arrays');
  15742. }
  15743. getExtension('OES_texture_float_linear');
  15744. getExtension('EXT_color_buffer_half_float');
  15745. },
  15746. get: function (name) {
  15747. const extension = getExtension(name);
  15748. if (extension === null) {
  15749. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  15750. }
  15751. return extension;
  15752. }
  15753. };
  15754. }
  15755. function WebGLGeometries(gl, attributes, info, bindingStates) {
  15756. const geometries = {};
  15757. const wireframeAttributes = new WeakMap();
  15758. function onGeometryDispose(event) {
  15759. const geometry = event.target;
  15760. if (geometry.index !== null) {
  15761. attributes.remove(geometry.index);
  15762. }
  15763. for (const name in geometry.attributes) {
  15764. attributes.remove(geometry.attributes[name]);
  15765. }
  15766. geometry.removeEventListener('dispose', onGeometryDispose);
  15767. delete geometries[geometry.id];
  15768. const attribute = wireframeAttributes.get(geometry);
  15769. if (attribute) {
  15770. attributes.remove(attribute);
  15771. wireframeAttributes.delete(geometry);
  15772. }
  15773. bindingStates.releaseStatesOfGeometry(geometry);
  15774. if (geometry.isInstancedBufferGeometry === true) {
  15775. delete geometry._maxInstanceCount;
  15776. } //
  15777. info.memory.geometries--;
  15778. }
  15779. function get(object, geometry) {
  15780. if (geometries[geometry.id] === true) return geometry;
  15781. geometry.addEventListener('dispose', onGeometryDispose);
  15782. geometries[geometry.id] = true;
  15783. info.memory.geometries++;
  15784. return geometry;
  15785. }
  15786. function update(geometry) {
  15787. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  15788. for (const name in geometryAttributes) {
  15789. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  15790. } // morph targets
  15791. const morphAttributes = geometry.morphAttributes;
  15792. for (const name in morphAttributes) {
  15793. const array = morphAttributes[name];
  15794. for (let i = 0, l = array.length; i < l; i++) {
  15795. attributes.update(array[i], gl.ARRAY_BUFFER);
  15796. }
  15797. }
  15798. }
  15799. function updateWireframeAttribute(geometry) {
  15800. const indices = [];
  15801. const geometryIndex = geometry.index;
  15802. const geometryPosition = geometry.attributes.position;
  15803. let version = 0;
  15804. if (geometryIndex !== null) {
  15805. const array = geometryIndex.array;
  15806. version = geometryIndex.version;
  15807. for (let i = 0, l = array.length; i < l; i += 3) {
  15808. const a = array[i + 0];
  15809. const b = array[i + 1];
  15810. const c = array[i + 2];
  15811. indices.push(a, b, b, c, c, a);
  15812. }
  15813. } else {
  15814. const array = geometryPosition.array;
  15815. version = geometryPosition.version;
  15816. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  15817. const a = i + 0;
  15818. const b = i + 1;
  15819. const c = i + 2;
  15820. indices.push(a, b, b, c, c, a);
  15821. }
  15822. }
  15823. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  15824. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  15825. //
  15826. const previousAttribute = wireframeAttributes.get(geometry);
  15827. if (previousAttribute) attributes.remove(previousAttribute); //
  15828. wireframeAttributes.set(geometry, attribute);
  15829. }
  15830. function getWireframeAttribute(geometry) {
  15831. const currentAttribute = wireframeAttributes.get(geometry);
  15832. if (currentAttribute) {
  15833. const geometryIndex = geometry.index;
  15834. if (geometryIndex !== null) {
  15835. // if the attribute is obsolete, create a new one
  15836. if (currentAttribute.version < geometryIndex.version) {
  15837. updateWireframeAttribute(geometry);
  15838. }
  15839. }
  15840. } else {
  15841. updateWireframeAttribute(geometry);
  15842. }
  15843. return wireframeAttributes.get(geometry);
  15844. }
  15845. return {
  15846. get: get,
  15847. update: update,
  15848. getWireframeAttribute: getWireframeAttribute
  15849. };
  15850. }
  15851. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  15852. const isWebGL2 = capabilities.isWebGL2;
  15853. let mode;
  15854. function setMode(value) {
  15855. mode = value;
  15856. }
  15857. let type, bytesPerElement;
  15858. function setIndex(value) {
  15859. type = value.type;
  15860. bytesPerElement = value.bytesPerElement;
  15861. }
  15862. function render(start, count) {
  15863. gl.drawElements(mode, count, type, start * bytesPerElement);
  15864. info.update(count, mode, 1);
  15865. }
  15866. function renderInstances(start, count, primcount) {
  15867. if (primcount === 0) return;
  15868. let extension, methodName;
  15869. if (isWebGL2) {
  15870. extension = gl;
  15871. methodName = 'drawElementsInstanced';
  15872. } else {
  15873. extension = extensions.get('ANGLE_instanced_arrays');
  15874. methodName = 'drawElementsInstancedANGLE';
  15875. if (extension === null) {
  15876. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  15877. return;
  15878. }
  15879. }
  15880. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  15881. info.update(count, mode, primcount);
  15882. } //
  15883. this.setMode = setMode;
  15884. this.setIndex = setIndex;
  15885. this.render = render;
  15886. this.renderInstances = renderInstances;
  15887. }
  15888. function WebGLInfo(gl) {
  15889. const memory = {
  15890. geometries: 0,
  15891. textures: 0
  15892. };
  15893. const render = {
  15894. frame: 0,
  15895. calls: 0,
  15896. triangles: 0,
  15897. points: 0,
  15898. lines: 0
  15899. };
  15900. function update(count, mode, instanceCount) {
  15901. render.calls++;
  15902. switch (mode) {
  15903. case gl.TRIANGLES:
  15904. render.triangles += instanceCount * (count / 3);
  15905. break;
  15906. case gl.LINES:
  15907. render.lines += instanceCount * (count / 2);
  15908. break;
  15909. case gl.LINE_STRIP:
  15910. render.lines += instanceCount * (count - 1);
  15911. break;
  15912. case gl.LINE_LOOP:
  15913. render.lines += instanceCount * count;
  15914. break;
  15915. case gl.POINTS:
  15916. render.points += instanceCount * count;
  15917. break;
  15918. default:
  15919. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  15920. break;
  15921. }
  15922. }
  15923. function reset() {
  15924. render.frame++;
  15925. render.calls = 0;
  15926. render.triangles = 0;
  15927. render.points = 0;
  15928. render.lines = 0;
  15929. }
  15930. return {
  15931. memory: memory,
  15932. render: render,
  15933. programs: null,
  15934. autoReset: true,
  15935. reset: reset,
  15936. update: update
  15937. };
  15938. }
  15939. class DataTexture2DArray extends Texture {
  15940. constructor(data = null, width = 1, height = 1, depth = 1) {
  15941. super(null);
  15942. this.image = {
  15943. data,
  15944. width,
  15945. height,
  15946. depth
  15947. };
  15948. this.magFilter = NearestFilter;
  15949. this.minFilter = NearestFilter;
  15950. this.wrapR = ClampToEdgeWrapping;
  15951. this.generateMipmaps = false;
  15952. this.flipY = false;
  15953. this.unpackAlignment = 1;
  15954. this.needsUpdate = true;
  15955. }
  15956. }
  15957. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  15958. function numericalSort(a, b) {
  15959. return a[0] - b[0];
  15960. }
  15961. function absNumericalSort(a, b) {
  15962. return Math.abs(b[1]) - Math.abs(a[1]);
  15963. }
  15964. function denormalize(morph, attribute) {
  15965. let denominator = 1;
  15966. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  15967. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  15968. morph.divideScalar(denominator);
  15969. }
  15970. function WebGLMorphtargets(gl, capabilities, textures) {
  15971. const influencesList = {};
  15972. const morphInfluences = new Float32Array(8);
  15973. const morphTextures = new WeakMap();
  15974. const morph = new Vector3();
  15975. const workInfluences = [];
  15976. for (let i = 0; i < 8; i++) {
  15977. workInfluences[i] = [i, 0];
  15978. }
  15979. function update(object, geometry, material, program) {
  15980. const objectInfluences = object.morphTargetInfluences;
  15981. if (capabilities.isWebGL2 === true) {
  15982. // instead of using attributes, the WebGL 2 code path encodes morph targets
  15983. // into an array of data textures. Each layer represents a single morph target.
  15984. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  15985. let entry = morphTextures.get(geometry);
  15986. if (entry === undefined || entry.count !== numberOfMorphTargets) {
  15987. if (entry !== undefined) entry.texture.dispose();
  15988. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  15989. const morphTargets = geometry.morphAttributes.position;
  15990. const morphNormals = geometry.morphAttributes.normal || [];
  15991. const numberOfVertices = geometry.attributes.position.count;
  15992. const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
  15993. let width = numberOfVertices * numberOfVertexData;
  15994. let height = 1;
  15995. if (width > capabilities.maxTextureSize) {
  15996. height = Math.ceil(width / capabilities.maxTextureSize);
  15997. width = capabilities.maxTextureSize;
  15998. }
  15999. const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
  16000. const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
  16001. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  16002. texture.type = FloatType; // fill buffer
  16003. const vertexDataStride = numberOfVertexData * 4;
  16004. for (let i = 0; i < numberOfMorphTargets; i++) {
  16005. const morphTarget = morphTargets[i];
  16006. const morphNormal = morphNormals[i];
  16007. const offset = width * height * 4 * i;
  16008. for (let j = 0; j < morphTarget.count; j++) {
  16009. morph.fromBufferAttribute(morphTarget, j);
  16010. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  16011. const stride = j * vertexDataStride;
  16012. buffer[offset + stride + 0] = morph.x;
  16013. buffer[offset + stride + 1] = morph.y;
  16014. buffer[offset + stride + 2] = morph.z;
  16015. buffer[offset + stride + 3] = 0;
  16016. if (hasMorphNormals === true) {
  16017. morph.fromBufferAttribute(morphNormal, j);
  16018. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  16019. buffer[offset + stride + 4] = morph.x;
  16020. buffer[offset + stride + 5] = morph.y;
  16021. buffer[offset + stride + 6] = morph.z;
  16022. buffer[offset + stride + 7] = 0;
  16023. }
  16024. }
  16025. }
  16026. entry = {
  16027. count: numberOfMorphTargets,
  16028. texture: texture,
  16029. size: new Vector2(width, height)
  16030. };
  16031. morphTextures.set(geometry, entry);
  16032. } //
  16033. let morphInfluencesSum = 0;
  16034. for (let i = 0; i < objectInfluences.length; i++) {
  16035. morphInfluencesSum += objectInfluences[i];
  16036. }
  16037. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  16038. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  16039. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  16040. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  16041. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  16042. } else {
  16043. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  16044. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  16045. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  16046. let influences = influencesList[geometry.id];
  16047. if (influences === undefined || influences.length !== length) {
  16048. // initialise list
  16049. influences = [];
  16050. for (let i = 0; i < length; i++) {
  16051. influences[i] = [i, 0];
  16052. }
  16053. influencesList[geometry.id] = influences;
  16054. } // Collect influences
  16055. for (let i = 0; i < length; i++) {
  16056. const influence = influences[i];
  16057. influence[0] = i;
  16058. influence[1] = objectInfluences[i];
  16059. }
  16060. influences.sort(absNumericalSort);
  16061. for (let i = 0; i < 8; i++) {
  16062. if (i < length && influences[i][1]) {
  16063. workInfluences[i][0] = influences[i][0];
  16064. workInfluences[i][1] = influences[i][1];
  16065. } else {
  16066. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  16067. workInfluences[i][1] = 0;
  16068. }
  16069. }
  16070. workInfluences.sort(numericalSort);
  16071. const morphTargets = geometry.morphAttributes.position;
  16072. const morphNormals = geometry.morphAttributes.normal;
  16073. let morphInfluencesSum = 0;
  16074. for (let i = 0; i < 8; i++) {
  16075. const influence = workInfluences[i];
  16076. const index = influence[0];
  16077. const value = influence[1];
  16078. if (index !== Number.MAX_SAFE_INTEGER && value) {
  16079. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  16080. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  16081. }
  16082. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  16083. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  16084. }
  16085. morphInfluences[i] = value;
  16086. morphInfluencesSum += value;
  16087. } else {
  16088. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  16089. geometry.deleteAttribute('morphTarget' + i);
  16090. }
  16091. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  16092. geometry.deleteAttribute('morphNormal' + i);
  16093. }
  16094. morphInfluences[i] = 0;
  16095. }
  16096. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  16097. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  16098. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  16099. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  16100. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  16101. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  16102. }
  16103. }
  16104. return {
  16105. update: update
  16106. };
  16107. }
  16108. function WebGLObjects(gl, geometries, attributes, info) {
  16109. let updateMap = new WeakMap();
  16110. function update(object) {
  16111. const frame = info.render.frame;
  16112. const geometry = object.geometry;
  16113. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  16114. if (updateMap.get(buffergeometry) !== frame) {
  16115. geometries.update(buffergeometry);
  16116. updateMap.set(buffergeometry, frame);
  16117. }
  16118. if (object.isInstancedMesh) {
  16119. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  16120. object.addEventListener('dispose', onInstancedMeshDispose);
  16121. }
  16122. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  16123. if (object.instanceColor !== null) {
  16124. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  16125. }
  16126. }
  16127. return buffergeometry;
  16128. }
  16129. function dispose() {
  16130. updateMap = new WeakMap();
  16131. }
  16132. function onInstancedMeshDispose(event) {
  16133. const instancedMesh = event.target;
  16134. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  16135. attributes.remove(instancedMesh.instanceMatrix);
  16136. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  16137. }
  16138. return {
  16139. update: update,
  16140. dispose: dispose
  16141. };
  16142. }
  16143. class DataTexture3D extends Texture {
  16144. constructor(data = null, width = 1, height = 1, depth = 1) {
  16145. // We're going to add .setXXX() methods for setting properties later.
  16146. // Users can still set in DataTexture3D directly.
  16147. //
  16148. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  16149. // texture.anisotropy = 16;
  16150. //
  16151. // See #14839
  16152. super(null);
  16153. this.image = {
  16154. data,
  16155. width,
  16156. height,
  16157. depth
  16158. };
  16159. this.magFilter = NearestFilter;
  16160. this.minFilter = NearestFilter;
  16161. this.wrapR = ClampToEdgeWrapping;
  16162. this.generateMipmaps = false;
  16163. this.flipY = false;
  16164. this.unpackAlignment = 1;
  16165. this.needsUpdate = true;
  16166. }
  16167. }
  16168. DataTexture3D.prototype.isDataTexture3D = true;
  16169. /**
  16170. * Uniforms of a program.
  16171. * Those form a tree structure with a special top-level container for the root,
  16172. * which you get by calling 'new WebGLUniforms( gl, program )'.
  16173. *
  16174. *
  16175. * Properties of inner nodes including the top-level container:
  16176. *
  16177. * .seq - array of nested uniforms
  16178. * .map - nested uniforms by name
  16179. *
  16180. *
  16181. * Methods of all nodes except the top-level container:
  16182. *
  16183. * .setValue( gl, value, [textures] )
  16184. *
  16185. * uploads a uniform value(s)
  16186. * the 'textures' parameter is needed for sampler uniforms
  16187. *
  16188. *
  16189. * Static methods of the top-level container (textures factorizations):
  16190. *
  16191. * .upload( gl, seq, values, textures )
  16192. *
  16193. * sets uniforms in 'seq' to 'values[id].value'
  16194. *
  16195. * .seqWithValue( seq, values ) : filteredSeq
  16196. *
  16197. * filters 'seq' entries with corresponding entry in values
  16198. *
  16199. *
  16200. * Methods of the top-level container (textures factorizations):
  16201. *
  16202. * .setValue( gl, name, value, textures )
  16203. *
  16204. * sets uniform with name 'name' to 'value'
  16205. *
  16206. * .setOptional( gl, obj, prop )
  16207. *
  16208. * like .set for an optional property of the object
  16209. *
  16210. */
  16211. const emptyTexture = new Texture();
  16212. const emptyTexture2dArray = new DataTexture2DArray();
  16213. const emptyTexture3d = new DataTexture3D();
  16214. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  16215. // Array Caches (provide typed arrays for temporary by size)
  16216. const arrayCacheF32 = [];
  16217. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  16218. const mat4array = new Float32Array(16);
  16219. const mat3array = new Float32Array(9);
  16220. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  16221. function flatten(array, nBlocks, blockSize) {
  16222. const firstElem = array[0];
  16223. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  16224. // see http://jacksondunstan.com/articles/983
  16225. const n = nBlocks * blockSize;
  16226. let r = arrayCacheF32[n];
  16227. if (r === undefined) {
  16228. r = new Float32Array(n);
  16229. arrayCacheF32[n] = r;
  16230. }
  16231. if (nBlocks !== 0) {
  16232. firstElem.toArray(r, 0);
  16233. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  16234. offset += blockSize;
  16235. array[i].toArray(r, offset);
  16236. }
  16237. }
  16238. return r;
  16239. }
  16240. function arraysEqual(a, b) {
  16241. if (a.length !== b.length) return false;
  16242. for (let i = 0, l = a.length; i < l; i++) {
  16243. if (a[i] !== b[i]) return false;
  16244. }
  16245. return true;
  16246. }
  16247. function copyArray(a, b) {
  16248. for (let i = 0, l = b.length; i < l; i++) {
  16249. a[i] = b[i];
  16250. }
  16251. } // Texture unit allocation
  16252. function allocTexUnits(textures, n) {
  16253. let r = arrayCacheI32[n];
  16254. if (r === undefined) {
  16255. r = new Int32Array(n);
  16256. arrayCacheI32[n] = r;
  16257. }
  16258. for (let i = 0; i !== n; ++i) {
  16259. r[i] = textures.allocateTextureUnit();
  16260. }
  16261. return r;
  16262. } // --- Setters ---
  16263. // Note: Defining these methods externally, because they come in a bunch
  16264. // and this way their names minify.
  16265. // Single scalar
  16266. function setValueV1f(gl, v) {
  16267. const cache = this.cache;
  16268. if (cache[0] === v) return;
  16269. gl.uniform1f(this.addr, v);
  16270. cache[0] = v;
  16271. } // Single float vector (from flat array or THREE.VectorN)
  16272. function setValueV2f(gl, v) {
  16273. const cache = this.cache;
  16274. if (v.x !== undefined) {
  16275. if (cache[0] !== v.x || cache[1] !== v.y) {
  16276. gl.uniform2f(this.addr, v.x, v.y);
  16277. cache[0] = v.x;
  16278. cache[1] = v.y;
  16279. }
  16280. } else {
  16281. if (arraysEqual(cache, v)) return;
  16282. gl.uniform2fv(this.addr, v);
  16283. copyArray(cache, v);
  16284. }
  16285. }
  16286. function setValueV3f(gl, v) {
  16287. const cache = this.cache;
  16288. if (v.x !== undefined) {
  16289. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  16290. gl.uniform3f(this.addr, v.x, v.y, v.z);
  16291. cache[0] = v.x;
  16292. cache[1] = v.y;
  16293. cache[2] = v.z;
  16294. }
  16295. } else if (v.r !== undefined) {
  16296. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  16297. gl.uniform3f(this.addr, v.r, v.g, v.b);
  16298. cache[0] = v.r;
  16299. cache[1] = v.g;
  16300. cache[2] = v.b;
  16301. }
  16302. } else {
  16303. if (arraysEqual(cache, v)) return;
  16304. gl.uniform3fv(this.addr, v);
  16305. copyArray(cache, v);
  16306. }
  16307. }
  16308. function setValueV4f(gl, v) {
  16309. const cache = this.cache;
  16310. if (v.x !== undefined) {
  16311. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  16312. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  16313. cache[0] = v.x;
  16314. cache[1] = v.y;
  16315. cache[2] = v.z;
  16316. cache[3] = v.w;
  16317. }
  16318. } else {
  16319. if (arraysEqual(cache, v)) return;
  16320. gl.uniform4fv(this.addr, v);
  16321. copyArray(cache, v);
  16322. }
  16323. } // Single matrix (from flat array or THREE.MatrixN)
  16324. function setValueM2(gl, v) {
  16325. const cache = this.cache;
  16326. const elements = v.elements;
  16327. if (elements === undefined) {
  16328. if (arraysEqual(cache, v)) return;
  16329. gl.uniformMatrix2fv(this.addr, false, v);
  16330. copyArray(cache, v);
  16331. } else {
  16332. if (arraysEqual(cache, elements)) return;
  16333. mat2array.set(elements);
  16334. gl.uniformMatrix2fv(this.addr, false, mat2array);
  16335. copyArray(cache, elements);
  16336. }
  16337. }
  16338. function setValueM3(gl, v) {
  16339. const cache = this.cache;
  16340. const elements = v.elements;
  16341. if (elements === undefined) {
  16342. if (arraysEqual(cache, v)) return;
  16343. gl.uniformMatrix3fv(this.addr, false, v);
  16344. copyArray(cache, v);
  16345. } else {
  16346. if (arraysEqual(cache, elements)) return;
  16347. mat3array.set(elements);
  16348. gl.uniformMatrix3fv(this.addr, false, mat3array);
  16349. copyArray(cache, elements);
  16350. }
  16351. }
  16352. function setValueM4(gl, v) {
  16353. const cache = this.cache;
  16354. const elements = v.elements;
  16355. if (elements === undefined) {
  16356. if (arraysEqual(cache, v)) return;
  16357. gl.uniformMatrix4fv(this.addr, false, v);
  16358. copyArray(cache, v);
  16359. } else {
  16360. if (arraysEqual(cache, elements)) return;
  16361. mat4array.set(elements);
  16362. gl.uniformMatrix4fv(this.addr, false, mat4array);
  16363. copyArray(cache, elements);
  16364. }
  16365. } // Single integer / boolean
  16366. function setValueV1i(gl, v) {
  16367. const cache = this.cache;
  16368. if (cache[0] === v) return;
  16369. gl.uniform1i(this.addr, v);
  16370. cache[0] = v;
  16371. } // Single integer / boolean vector (from flat array)
  16372. function setValueV2i(gl, v) {
  16373. const cache = this.cache;
  16374. if (arraysEqual(cache, v)) return;
  16375. gl.uniform2iv(this.addr, v);
  16376. copyArray(cache, v);
  16377. }
  16378. function setValueV3i(gl, v) {
  16379. const cache = this.cache;
  16380. if (arraysEqual(cache, v)) return;
  16381. gl.uniform3iv(this.addr, v);
  16382. copyArray(cache, v);
  16383. }
  16384. function setValueV4i(gl, v) {
  16385. const cache = this.cache;
  16386. if (arraysEqual(cache, v)) return;
  16387. gl.uniform4iv(this.addr, v);
  16388. copyArray(cache, v);
  16389. } // Single unsigned integer
  16390. function setValueV1ui(gl, v) {
  16391. const cache = this.cache;
  16392. if (cache[0] === v) return;
  16393. gl.uniform1ui(this.addr, v);
  16394. cache[0] = v;
  16395. } // Single unsigned integer vector (from flat array)
  16396. function setValueV2ui(gl, v) {
  16397. const cache = this.cache;
  16398. if (arraysEqual(cache, v)) return;
  16399. gl.uniform2uiv(this.addr, v);
  16400. copyArray(cache, v);
  16401. }
  16402. function setValueV3ui(gl, v) {
  16403. const cache = this.cache;
  16404. if (arraysEqual(cache, v)) return;
  16405. gl.uniform3uiv(this.addr, v);
  16406. copyArray(cache, v);
  16407. }
  16408. function setValueV4ui(gl, v) {
  16409. const cache = this.cache;
  16410. if (arraysEqual(cache, v)) return;
  16411. gl.uniform4uiv(this.addr, v);
  16412. copyArray(cache, v);
  16413. } // Single texture (2D / Cube)
  16414. function setValueT1(gl, v, textures) {
  16415. const cache = this.cache;
  16416. const unit = textures.allocateTextureUnit();
  16417. if (cache[0] !== unit) {
  16418. gl.uniform1i(this.addr, unit);
  16419. cache[0] = unit;
  16420. }
  16421. textures.safeSetTexture2D(v || emptyTexture, unit);
  16422. }
  16423. function setValueT3D1(gl, v, textures) {
  16424. const cache = this.cache;
  16425. const unit = textures.allocateTextureUnit();
  16426. if (cache[0] !== unit) {
  16427. gl.uniform1i(this.addr, unit);
  16428. cache[0] = unit;
  16429. }
  16430. textures.setTexture3D(v || emptyTexture3d, unit);
  16431. }
  16432. function setValueT6(gl, v, textures) {
  16433. const cache = this.cache;
  16434. const unit = textures.allocateTextureUnit();
  16435. if (cache[0] !== unit) {
  16436. gl.uniform1i(this.addr, unit);
  16437. cache[0] = unit;
  16438. }
  16439. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  16440. }
  16441. function setValueT2DArray1(gl, v, textures) {
  16442. const cache = this.cache;
  16443. const unit = textures.allocateTextureUnit();
  16444. if (cache[0] !== unit) {
  16445. gl.uniform1i(this.addr, unit);
  16446. cache[0] = unit;
  16447. }
  16448. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  16449. } // Helper to pick the right setter for the singular case
  16450. function getSingularSetter(type) {
  16451. switch (type) {
  16452. case 0x1406:
  16453. return setValueV1f;
  16454. // FLOAT
  16455. case 0x8b50:
  16456. return setValueV2f;
  16457. // _VEC2
  16458. case 0x8b51:
  16459. return setValueV3f;
  16460. // _VEC3
  16461. case 0x8b52:
  16462. return setValueV4f;
  16463. // _VEC4
  16464. case 0x8b5a:
  16465. return setValueM2;
  16466. // _MAT2
  16467. case 0x8b5b:
  16468. return setValueM3;
  16469. // _MAT3
  16470. case 0x8b5c:
  16471. return setValueM4;
  16472. // _MAT4
  16473. case 0x1404:
  16474. case 0x8b56:
  16475. return setValueV1i;
  16476. // INT, BOOL
  16477. case 0x8b53:
  16478. case 0x8b57:
  16479. return setValueV2i;
  16480. // _VEC2
  16481. case 0x8b54:
  16482. case 0x8b58:
  16483. return setValueV3i;
  16484. // _VEC3
  16485. case 0x8b55:
  16486. case 0x8b59:
  16487. return setValueV4i;
  16488. // _VEC4
  16489. case 0x1405:
  16490. return setValueV1ui;
  16491. // UINT
  16492. case 0x8dc6:
  16493. return setValueV2ui;
  16494. // _VEC2
  16495. case 0x8dc7:
  16496. return setValueV3ui;
  16497. // _VEC3
  16498. case 0x8dc8:
  16499. return setValueV4ui;
  16500. // _VEC4
  16501. case 0x8b5e: // SAMPLER_2D
  16502. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16503. case 0x8dca: // INT_SAMPLER_2D
  16504. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16505. case 0x8b62:
  16506. // SAMPLER_2D_SHADOW
  16507. return setValueT1;
  16508. case 0x8b5f: // SAMPLER_3D
  16509. case 0x8dcb: // INT_SAMPLER_3D
  16510. case 0x8dd3:
  16511. // UNSIGNED_INT_SAMPLER_3D
  16512. return setValueT3D1;
  16513. case 0x8b60: // SAMPLER_CUBE
  16514. case 0x8dcc: // INT_SAMPLER_CUBE
  16515. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16516. case 0x8dc5:
  16517. // SAMPLER_CUBE_SHADOW
  16518. return setValueT6;
  16519. case 0x8dc1: // SAMPLER_2D_ARRAY
  16520. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  16521. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  16522. case 0x8dc4:
  16523. // SAMPLER_2D_ARRAY_SHADOW
  16524. return setValueT2DArray1;
  16525. }
  16526. } // Array of scalars
  16527. function setValueV1fArray(gl, v) {
  16528. gl.uniform1fv(this.addr, v);
  16529. } // Array of vectors (from flat array or array of THREE.VectorN)
  16530. function setValueV2fArray(gl, v) {
  16531. const data = flatten(v, this.size, 2);
  16532. gl.uniform2fv(this.addr, data);
  16533. }
  16534. function setValueV3fArray(gl, v) {
  16535. const data = flatten(v, this.size, 3);
  16536. gl.uniform3fv(this.addr, data);
  16537. }
  16538. function setValueV4fArray(gl, v) {
  16539. const data = flatten(v, this.size, 4);
  16540. gl.uniform4fv(this.addr, data);
  16541. } // Array of matrices (from flat array or array of THREE.MatrixN)
  16542. function setValueM2Array(gl, v) {
  16543. const data = flatten(v, this.size, 4);
  16544. gl.uniformMatrix2fv(this.addr, false, data);
  16545. }
  16546. function setValueM3Array(gl, v) {
  16547. const data = flatten(v, this.size, 9);
  16548. gl.uniformMatrix3fv(this.addr, false, data);
  16549. }
  16550. function setValueM4Array(gl, v) {
  16551. const data = flatten(v, this.size, 16);
  16552. gl.uniformMatrix4fv(this.addr, false, data);
  16553. } // Array of integer / boolean
  16554. function setValueV1iArray(gl, v) {
  16555. gl.uniform1iv(this.addr, v);
  16556. } // Array of integer / boolean vectors (from flat array)
  16557. function setValueV2iArray(gl, v) {
  16558. gl.uniform2iv(this.addr, v);
  16559. }
  16560. function setValueV3iArray(gl, v) {
  16561. gl.uniform3iv(this.addr, v);
  16562. }
  16563. function setValueV4iArray(gl, v) {
  16564. gl.uniform4iv(this.addr, v);
  16565. } // Array of unsigned integer
  16566. function setValueV1uiArray(gl, v) {
  16567. gl.uniform1uiv(this.addr, v);
  16568. } // Array of unsigned integer vectors (from flat array)
  16569. function setValueV2uiArray(gl, v) {
  16570. gl.uniform2uiv(this.addr, v);
  16571. }
  16572. function setValueV3uiArray(gl, v) {
  16573. gl.uniform3uiv(this.addr, v);
  16574. }
  16575. function setValueV4uiArray(gl, v) {
  16576. gl.uniform4uiv(this.addr, v);
  16577. } // Array of textures (2D / Cube)
  16578. function setValueT1Array(gl, v, textures) {
  16579. const n = v.length;
  16580. const units = allocTexUnits(textures, n);
  16581. gl.uniform1iv(this.addr, units);
  16582. for (let i = 0; i !== n; ++i) {
  16583. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  16584. }
  16585. }
  16586. function setValueT6Array(gl, v, textures) {
  16587. const n = v.length;
  16588. const units = allocTexUnits(textures, n);
  16589. gl.uniform1iv(this.addr, units);
  16590. for (let i = 0; i !== n; ++i) {
  16591. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  16592. }
  16593. } // Helper to pick the right setter for a pure (bottom-level) array
  16594. function getPureArraySetter(type) {
  16595. switch (type) {
  16596. case 0x1406:
  16597. return setValueV1fArray;
  16598. // FLOAT
  16599. case 0x8b50:
  16600. return setValueV2fArray;
  16601. // _VEC2
  16602. case 0x8b51:
  16603. return setValueV3fArray;
  16604. // _VEC3
  16605. case 0x8b52:
  16606. return setValueV4fArray;
  16607. // _VEC4
  16608. case 0x8b5a:
  16609. return setValueM2Array;
  16610. // _MAT2
  16611. case 0x8b5b:
  16612. return setValueM3Array;
  16613. // _MAT3
  16614. case 0x8b5c:
  16615. return setValueM4Array;
  16616. // _MAT4
  16617. case 0x1404:
  16618. case 0x8b56:
  16619. return setValueV1iArray;
  16620. // INT, BOOL
  16621. case 0x8b53:
  16622. case 0x8b57:
  16623. return setValueV2iArray;
  16624. // _VEC2
  16625. case 0x8b54:
  16626. case 0x8b58:
  16627. return setValueV3iArray;
  16628. // _VEC3
  16629. case 0x8b55:
  16630. case 0x8b59:
  16631. return setValueV4iArray;
  16632. // _VEC4
  16633. case 0x1405:
  16634. return setValueV1uiArray;
  16635. // UINT
  16636. case 0x8dc6:
  16637. return setValueV2uiArray;
  16638. // _VEC2
  16639. case 0x8dc7:
  16640. return setValueV3uiArray;
  16641. // _VEC3
  16642. case 0x8dc8:
  16643. return setValueV4uiArray;
  16644. // _VEC4
  16645. case 0x8b5e: // SAMPLER_2D
  16646. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16647. case 0x8dca: // INT_SAMPLER_2D
  16648. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16649. case 0x8b62:
  16650. // SAMPLER_2D_SHADOW
  16651. return setValueT1Array;
  16652. case 0x8b60: // SAMPLER_CUBE
  16653. case 0x8dcc: // INT_SAMPLER_CUBE
  16654. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16655. case 0x8dc5:
  16656. // SAMPLER_CUBE_SHADOW
  16657. return setValueT6Array;
  16658. }
  16659. } // --- Uniform Classes ---
  16660. function SingleUniform(id, activeInfo, addr) {
  16661. this.id = id;
  16662. this.addr = addr;
  16663. this.cache = [];
  16664. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16665. }
  16666. function PureArrayUniform(id, activeInfo, addr) {
  16667. this.id = id;
  16668. this.addr = addr;
  16669. this.cache = [];
  16670. this.size = activeInfo.size;
  16671. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16672. }
  16673. PureArrayUniform.prototype.updateCache = function (data) {
  16674. const cache = this.cache;
  16675. if (data instanceof Float32Array && cache.length !== data.length) {
  16676. this.cache = new Float32Array(data.length);
  16677. }
  16678. copyArray(cache, data);
  16679. };
  16680. function StructuredUniform(id) {
  16681. this.id = id;
  16682. this.seq = [];
  16683. this.map = {};
  16684. }
  16685. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  16686. const seq = this.seq;
  16687. for (let i = 0, n = seq.length; i !== n; ++i) {
  16688. const u = seq[i];
  16689. u.setValue(gl, value[u.id], textures);
  16690. }
  16691. }; // --- Top-level ---
  16692. // Parser - builds up the property tree from the path strings
  16693. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  16694. // - the identifier (member name or array index)
  16695. // - followed by an optional right bracket (found when array index)
  16696. // - followed by an optional left bracket or dot (type of subscript)
  16697. //
  16698. // Note: These portions can be read in a non-overlapping fashion and
  16699. // allow straightforward parsing of the hierarchy that WebGL encodes
  16700. // in the uniform names.
  16701. function addUniform(container, uniformObject) {
  16702. container.seq.push(uniformObject);
  16703. container.map[uniformObject.id] = uniformObject;
  16704. }
  16705. function parseUniform(activeInfo, addr, container) {
  16706. const path = activeInfo.name,
  16707. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  16708. RePathPart.lastIndex = 0;
  16709. while (true) {
  16710. const match = RePathPart.exec(path),
  16711. matchEnd = RePathPart.lastIndex;
  16712. let id = match[1];
  16713. const idIsIndex = match[2] === ']',
  16714. subscript = match[3];
  16715. if (idIsIndex) id = id | 0; // convert to integer
  16716. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  16717. // bare name or "pure" bottom-level array "[0]" suffix
  16718. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  16719. break;
  16720. } else {
  16721. // step into inner node / create it in case it doesn't exist
  16722. const map = container.map;
  16723. let next = map[id];
  16724. if (next === undefined) {
  16725. next = new StructuredUniform(id);
  16726. addUniform(container, next);
  16727. }
  16728. container = next;
  16729. }
  16730. }
  16731. } // Root Container
  16732. function WebGLUniforms(gl, program) {
  16733. this.seq = [];
  16734. this.map = {};
  16735. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  16736. for (let i = 0; i < n; ++i) {
  16737. const info = gl.getActiveUniform(program, i),
  16738. addr = gl.getUniformLocation(program, info.name);
  16739. parseUniform(info, addr, this);
  16740. }
  16741. }
  16742. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  16743. const u = this.map[name];
  16744. if (u !== undefined) u.setValue(gl, value, textures);
  16745. };
  16746. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  16747. const v = object[name];
  16748. if (v !== undefined) this.setValue(gl, name, v);
  16749. }; // Static interface
  16750. WebGLUniforms.upload = function (gl, seq, values, textures) {
  16751. for (let i = 0, n = seq.length; i !== n; ++i) {
  16752. const u = seq[i],
  16753. v = values[u.id];
  16754. if (v.needsUpdate !== false) {
  16755. // note: always updating when .needsUpdate is undefined
  16756. u.setValue(gl, v.value, textures);
  16757. }
  16758. }
  16759. };
  16760. WebGLUniforms.seqWithValue = function (seq, values) {
  16761. const r = [];
  16762. for (let i = 0, n = seq.length; i !== n; ++i) {
  16763. const u = seq[i];
  16764. if (u.id in values) r.push(u);
  16765. }
  16766. return r;
  16767. };
  16768. function WebGLShader(gl, type, string) {
  16769. const shader = gl.createShader(type);
  16770. gl.shaderSource(shader, string);
  16771. gl.compileShader(shader);
  16772. return shader;
  16773. }
  16774. let programIdCount = 0;
  16775. function addLineNumbers(string) {
  16776. const lines = string.split('\n');
  16777. for (let i = 0; i < lines.length; i++) {
  16778. lines[i] = i + 1 + ': ' + lines[i];
  16779. }
  16780. return lines.join('\n');
  16781. }
  16782. function getEncodingComponents(encoding) {
  16783. switch (encoding) {
  16784. case LinearEncoding:
  16785. return ['Linear', '( value )'];
  16786. case sRGBEncoding:
  16787. return ['sRGB', '( value )'];
  16788. case RGBEEncoding:
  16789. return ['RGBE', '( value )'];
  16790. case RGBM7Encoding:
  16791. return ['RGBM', '( value, 7.0 )'];
  16792. case RGBM16Encoding:
  16793. return ['RGBM', '( value, 16.0 )'];
  16794. case RGBDEncoding:
  16795. return ['RGBD', '( value, 256.0 )'];
  16796. case GammaEncoding:
  16797. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  16798. case LogLuvEncoding:
  16799. return ['LogLuv', '( value )'];
  16800. default:
  16801. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  16802. return ['Linear', '( value )'];
  16803. }
  16804. }
  16805. function getShaderErrors(gl, shader, type) {
  16806. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  16807. const errors = gl.getShaderInfoLog(shader).trim();
  16808. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  16809. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16810. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  16811. }
  16812. function getTexelDecodingFunction(functionName, encoding) {
  16813. const components = getEncodingComponents(encoding);
  16814. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  16815. }
  16816. function getTexelEncodingFunction(functionName, encoding) {
  16817. const components = getEncodingComponents(encoding);
  16818. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  16819. }
  16820. function getToneMappingFunction(functionName, toneMapping) {
  16821. let toneMappingName;
  16822. switch (toneMapping) {
  16823. case LinearToneMapping:
  16824. toneMappingName = 'Linear';
  16825. break;
  16826. case ReinhardToneMapping:
  16827. toneMappingName = 'Reinhard';
  16828. break;
  16829. case CineonToneMapping:
  16830. toneMappingName = 'OptimizedCineon';
  16831. break;
  16832. case ACESFilmicToneMapping:
  16833. toneMappingName = 'ACESFilmic';
  16834. break;
  16835. case CustomToneMapping:
  16836. toneMappingName = 'Custom';
  16837. break;
  16838. default:
  16839. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  16840. toneMappingName = 'Linear';
  16841. }
  16842. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16843. }
  16844. function generateExtensions(parameters) {
  16845. const 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.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  16846. return chunks.filter(filterEmptyLine).join('\n');
  16847. }
  16848. function generateDefines(defines) {
  16849. const chunks = [];
  16850. for (const name in defines) {
  16851. const value = defines[name];
  16852. if (value === false) continue;
  16853. chunks.push('#define ' + name + ' ' + value);
  16854. }
  16855. return chunks.join('\n');
  16856. }
  16857. function fetchAttributeLocations(gl, program) {
  16858. const attributes = {};
  16859. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  16860. for (let i = 0; i < n; i++) {
  16861. const info = gl.getActiveAttrib(program, i);
  16862. const name = info.name;
  16863. let locationSize = 1;
  16864. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  16865. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  16866. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16867. attributes[name] = {
  16868. type: info.type,
  16869. location: gl.getAttribLocation(program, name),
  16870. locationSize: locationSize
  16871. };
  16872. }
  16873. return attributes;
  16874. }
  16875. function filterEmptyLine(string) {
  16876. return string !== '';
  16877. }
  16878. function replaceLightNums(string, parameters) {
  16879. 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);
  16880. }
  16881. function replaceClippingPlaneNums(string, parameters) {
  16882. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  16883. } // Resolve Includes
  16884. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16885. function resolveIncludes(string) {
  16886. return string.replace(includePattern, includeReplacer);
  16887. }
  16888. function includeReplacer(match, include) {
  16889. const string = ShaderChunk[include];
  16890. if (string === undefined) {
  16891. throw new Error('Can not resolve #include <' + include + '>');
  16892. }
  16893. return resolveIncludes(string);
  16894. } // Unroll Loops
  16895. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16896. const 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;
  16897. function unrollLoops(string) {
  16898. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  16899. }
  16900. function deprecatedLoopReplacer(match, start, end, snippet) {
  16901. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  16902. return loopReplacer(match, start, end, snippet);
  16903. }
  16904. function loopReplacer(match, start, end, snippet) {
  16905. let string = '';
  16906. for (let i = parseInt(start); i < parseInt(end); i++) {
  16907. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  16908. }
  16909. return string;
  16910. } //
  16911. function generatePrecision(parameters) {
  16912. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  16913. if (parameters.precision === 'highp') {
  16914. precisionstring += '\n#define HIGH_PRECISION';
  16915. } else if (parameters.precision === 'mediump') {
  16916. precisionstring += '\n#define MEDIUM_PRECISION';
  16917. } else if (parameters.precision === 'lowp') {
  16918. precisionstring += '\n#define LOW_PRECISION';
  16919. }
  16920. return precisionstring;
  16921. }
  16922. function generateShadowMapTypeDefine(parameters) {
  16923. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16924. if (parameters.shadowMapType === PCFShadowMap) {
  16925. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16926. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  16927. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16928. } else if (parameters.shadowMapType === VSMShadowMap) {
  16929. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16930. }
  16931. return shadowMapTypeDefine;
  16932. }
  16933. function generateEnvMapTypeDefine(parameters) {
  16934. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16935. if (parameters.envMap) {
  16936. switch (parameters.envMapMode) {
  16937. case CubeReflectionMapping:
  16938. case CubeRefractionMapping:
  16939. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16940. break;
  16941. case CubeUVReflectionMapping:
  16942. case CubeUVRefractionMapping:
  16943. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16944. break;
  16945. }
  16946. }
  16947. return envMapTypeDefine;
  16948. }
  16949. function generateEnvMapModeDefine(parameters) {
  16950. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16951. if (parameters.envMap) {
  16952. switch (parameters.envMapMode) {
  16953. case CubeRefractionMapping:
  16954. case CubeUVRefractionMapping:
  16955. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16956. break;
  16957. }
  16958. }
  16959. return envMapModeDefine;
  16960. }
  16961. function generateEnvMapBlendingDefine(parameters) {
  16962. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16963. if (parameters.envMap) {
  16964. switch (parameters.combine) {
  16965. case MultiplyOperation:
  16966. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16967. break;
  16968. case MixOperation:
  16969. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16970. break;
  16971. case AddOperation:
  16972. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16973. break;
  16974. }
  16975. }
  16976. return envMapBlendingDefine;
  16977. }
  16978. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  16979. // TODO Send this event to Three.js DevTools
  16980. // console.log( 'WebGLProgram', cacheKey );
  16981. const gl = renderer.getContext();
  16982. const defines = parameters.defines;
  16983. let vertexShader = parameters.vertexShader;
  16984. let fragmentShader = parameters.fragmentShader;
  16985. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  16986. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  16987. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  16988. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  16989. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  16990. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  16991. const customDefines = generateDefines(defines);
  16992. const program = gl.createProgram();
  16993. let prefixVertex, prefixFragment;
  16994. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  16995. if (parameters.isRawShaderMaterial) {
  16996. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  16997. if (prefixVertex.length > 0) {
  16998. prefixVertex += '\n';
  16999. }
  17000. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  17001. if (prefixFragment.length > 0) {
  17002. prefixFragment += '\n';
  17003. }
  17004. } else {
  17005. 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.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', 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.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', 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', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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');
  17006. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#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.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', 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
  17007. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  17008. 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.specularTintMap ? getTexelDecodingFunction('specularTintMapTexelToLinear', parameters.specularTintMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  17009. }
  17010. vertexShader = resolveIncludes(vertexShader);
  17011. vertexShader = replaceLightNums(vertexShader, parameters);
  17012. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  17013. fragmentShader = resolveIncludes(fragmentShader);
  17014. fragmentShader = replaceLightNums(fragmentShader, parameters);
  17015. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  17016. vertexShader = unrollLoops(vertexShader);
  17017. fragmentShader = unrollLoops(fragmentShader);
  17018. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  17019. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  17020. versionString = '#version 300 es\n';
  17021. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  17022. 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;
  17023. }
  17024. const vertexGlsl = versionString + prefixVertex + vertexShader;
  17025. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  17026. // console.log( '*FRAGMENT*', fragmentGlsl );
  17027. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  17028. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  17029. gl.attachShader(program, glVertexShader);
  17030. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  17031. if (parameters.index0AttributeName !== undefined) {
  17032. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  17033. } else if (parameters.morphTargets === true) {
  17034. // programs with morphTargets displace position out of attribute 0
  17035. gl.bindAttribLocation(program, 0, 'position');
  17036. }
  17037. gl.linkProgram(program); // check for link errors
  17038. if (renderer.debug.checkShaderErrors) {
  17039. const programLog = gl.getProgramInfoLog(program).trim();
  17040. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  17041. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  17042. let runnable = true;
  17043. let haveDiagnostics = true;
  17044. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  17045. runnable = false;
  17046. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  17047. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  17048. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  17049. } else if (programLog !== '') {
  17050. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  17051. } else if (vertexLog === '' || fragmentLog === '') {
  17052. haveDiagnostics = false;
  17053. }
  17054. if (haveDiagnostics) {
  17055. this.diagnostics = {
  17056. runnable: runnable,
  17057. programLog: programLog,
  17058. vertexShader: {
  17059. log: vertexLog,
  17060. prefix: prefixVertex
  17061. },
  17062. fragmentShader: {
  17063. log: fragmentLog,
  17064. prefix: prefixFragment
  17065. }
  17066. };
  17067. }
  17068. } // Clean up
  17069. // Crashes in iOS9 and iOS10. #18402
  17070. // gl.detachShader( program, glVertexShader );
  17071. // gl.detachShader( program, glFragmentShader );
  17072. gl.deleteShader(glVertexShader);
  17073. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  17074. let cachedUniforms;
  17075. this.getUniforms = function () {
  17076. if (cachedUniforms === undefined) {
  17077. cachedUniforms = new WebGLUniforms(gl, program);
  17078. }
  17079. return cachedUniforms;
  17080. }; // set up caching for attribute locations
  17081. let cachedAttributes;
  17082. this.getAttributes = function () {
  17083. if (cachedAttributes === undefined) {
  17084. cachedAttributes = fetchAttributeLocations(gl, program);
  17085. }
  17086. return cachedAttributes;
  17087. }; // free resource
  17088. this.destroy = function () {
  17089. bindingStates.releaseStatesOfProgram(this);
  17090. gl.deleteProgram(program);
  17091. this.program = undefined;
  17092. }; //
  17093. this.name = parameters.shaderName;
  17094. this.id = programIdCount++;
  17095. this.cacheKey = cacheKey;
  17096. this.usedTimes = 1;
  17097. this.program = program;
  17098. this.vertexShader = glVertexShader;
  17099. this.fragmentShader = glFragmentShader;
  17100. return this;
  17101. }
  17102. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  17103. const programs = [];
  17104. const isWebGL2 = capabilities.isWebGL2;
  17105. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  17106. const floatVertexTextures = capabilities.floatVertexTextures;
  17107. const maxVertexUniforms = capabilities.maxVertexUniforms;
  17108. const vertexTextures = capabilities.vertexTextures;
  17109. let precision = capabilities.precision;
  17110. const shaderIDs = {
  17111. MeshDepthMaterial: 'depth',
  17112. MeshDistanceMaterial: 'distanceRGBA',
  17113. MeshNormalMaterial: 'normal',
  17114. MeshBasicMaterial: 'basic',
  17115. MeshLambertMaterial: 'lambert',
  17116. MeshPhongMaterial: 'phong',
  17117. MeshToonMaterial: 'toon',
  17118. MeshStandardMaterial: 'physical',
  17119. MeshPhysicalMaterial: 'physical',
  17120. MeshMatcapMaterial: 'matcap',
  17121. LineBasicMaterial: 'basic',
  17122. LineDashedMaterial: 'dashed',
  17123. PointsMaterial: 'points',
  17124. ShadowMaterial: 'shadow',
  17125. SpriteMaterial: 'sprite'
  17126. };
  17127. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'morphTargetsCount', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  17128. function getMaxBones(object) {
  17129. const skeleton = object.skeleton;
  17130. const bones = skeleton.bones;
  17131. if (floatVertexTextures) {
  17132. return 1024;
  17133. } else {
  17134. // default for when object is not specified
  17135. // ( for example when prebuilding shader to be used with multiple objects )
  17136. //
  17137. // - leave some extra space for other uniforms
  17138. // - limit here is ANGLE's 254 max uniform vectors
  17139. // (up to 54 should be safe)
  17140. const nVertexUniforms = maxVertexUniforms;
  17141. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  17142. const maxBones = Math.min(nVertexMatrices, bones.length);
  17143. if (maxBones < bones.length) {
  17144. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  17145. return 0;
  17146. }
  17147. return maxBones;
  17148. }
  17149. }
  17150. function getTextureEncodingFromMap(map) {
  17151. let encoding;
  17152. if (map && map.isTexture) {
  17153. encoding = map.encoding;
  17154. } else if (map && map.isWebGLRenderTarget) {
  17155. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  17156. encoding = map.texture.encoding;
  17157. } else {
  17158. encoding = LinearEncoding;
  17159. }
  17160. if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
  17161. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  17162. }
  17163. return encoding;
  17164. }
  17165. function getParameters(material, lights, shadows, scene, object) {
  17166. const fog = scene.fog;
  17167. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17168. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  17169. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  17170. // (not to blow over maxLights budget)
  17171. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  17172. if (material.precision !== null) {
  17173. precision = capabilities.getMaxPrecision(material.precision);
  17174. if (precision !== material.precision) {
  17175. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  17176. }
  17177. }
  17178. let vertexShader, fragmentShader;
  17179. if (shaderID) {
  17180. const shader = ShaderLib[shaderID];
  17181. vertexShader = shader.vertexShader;
  17182. fragmentShader = shader.fragmentShader;
  17183. } else {
  17184. vertexShader = material.vertexShader;
  17185. fragmentShader = material.fragmentShader;
  17186. }
  17187. const currentRenderTarget = renderer.getRenderTarget();
  17188. const useAlphaTest = material.alphaTest > 0;
  17189. const useClearcoat = material.clearcoat > 0;
  17190. const parameters = {
  17191. isWebGL2: isWebGL2,
  17192. shaderID: shaderID,
  17193. shaderName: material.type,
  17194. vertexShader: vertexShader,
  17195. fragmentShader: fragmentShader,
  17196. defines: material.defines,
  17197. isRawShaderMaterial: material.isRawShaderMaterial === true,
  17198. glslVersion: material.glslVersion,
  17199. precision: precision,
  17200. instancing: object.isInstancedMesh === true,
  17201. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  17202. supportsVertexTextures: vertexTextures,
  17203. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  17204. map: !!material.map,
  17205. mapEncoding: getTextureEncodingFromMap(material.map),
  17206. matcap: !!material.matcap,
  17207. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  17208. envMap: !!envMap,
  17209. envMapMode: envMap && envMap.mapping,
  17210. envMapEncoding: getTextureEncodingFromMap(envMap),
  17211. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  17212. lightMap: !!material.lightMap,
  17213. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  17214. aoMap: !!material.aoMap,
  17215. emissiveMap: !!material.emissiveMap,
  17216. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  17217. bumpMap: !!material.bumpMap,
  17218. normalMap: !!material.normalMap,
  17219. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  17220. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  17221. clearcoat: useClearcoat,
  17222. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  17223. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  17224. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  17225. displacementMap: !!material.displacementMap,
  17226. roughnessMap: !!material.roughnessMap,
  17227. metalnessMap: !!material.metalnessMap,
  17228. specularMap: !!material.specularMap,
  17229. specularIntensityMap: !!material.specularIntensityMap,
  17230. specularTintMap: !!material.specularTintMap,
  17231. specularTintMapEncoding: getTextureEncodingFromMap(material.specularTintMap),
  17232. alphaMap: !!material.alphaMap,
  17233. alphaTest: useAlphaTest,
  17234. gradientMap: !!material.gradientMap,
  17235. sheen: material.sheen > 0,
  17236. transmission: material.transmission > 0,
  17237. transmissionMap: !!material.transmissionMap,
  17238. thicknessMap: !!material.thicknessMap,
  17239. combine: material.combine,
  17240. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  17241. vertexColors: material.vertexColors,
  17242. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  17243. 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 || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap,
  17244. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap) && !!material.displacementMap,
  17245. fog: !!fog,
  17246. useFog: material.fog,
  17247. fogExp2: fog && fog.isFogExp2,
  17248. flatShading: !!material.flatShading,
  17249. sizeAttenuation: material.sizeAttenuation,
  17250. logarithmicDepthBuffer: logarithmicDepthBuffer,
  17251. skinning: object.isSkinnedMesh === true && maxBones > 0,
  17252. maxBones: maxBones,
  17253. useVertexTexture: floatVertexTextures,
  17254. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  17255. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  17256. morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
  17257. numDirLights: lights.directional.length,
  17258. numPointLights: lights.point.length,
  17259. numSpotLights: lights.spot.length,
  17260. numRectAreaLights: lights.rectArea.length,
  17261. numHemiLights: lights.hemi.length,
  17262. numDirLightShadows: lights.directionalShadowMap.length,
  17263. numPointLightShadows: lights.pointShadowMap.length,
  17264. numSpotLightShadows: lights.spotShadowMap.length,
  17265. numClippingPlanes: clipping.numPlanes,
  17266. numClipIntersection: clipping.numIntersection,
  17267. format: material.format,
  17268. dithering: material.dithering,
  17269. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  17270. shadowMapType: renderer.shadowMap.type,
  17271. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  17272. physicallyCorrectLights: renderer.physicallyCorrectLights,
  17273. premultipliedAlpha: material.premultipliedAlpha,
  17274. doubleSided: material.side === DoubleSide,
  17275. flipSided: material.side === BackSide,
  17276. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  17277. index0AttributeName: material.index0AttributeName,
  17278. extensionDerivatives: material.extensions && material.extensions.derivatives,
  17279. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  17280. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  17281. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  17282. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  17283. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  17284. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  17285. customProgramCacheKey: material.customProgramCacheKey()
  17286. };
  17287. return parameters;
  17288. }
  17289. function getProgramCacheKey(parameters) {
  17290. const array = [];
  17291. if (parameters.shaderID) {
  17292. array.push(parameters.shaderID);
  17293. } else {
  17294. array.push(parameters.fragmentShader);
  17295. array.push(parameters.vertexShader);
  17296. }
  17297. if (parameters.defines !== undefined) {
  17298. for (const name in parameters.defines) {
  17299. array.push(name);
  17300. array.push(parameters.defines[name]);
  17301. }
  17302. }
  17303. if (parameters.isRawShaderMaterial === false) {
  17304. for (let i = 0; i < parameterNames.length; i++) {
  17305. array.push(parameters[parameterNames[i]]);
  17306. }
  17307. array.push(renderer.outputEncoding);
  17308. array.push(renderer.gammaFactor);
  17309. }
  17310. array.push(parameters.customProgramCacheKey);
  17311. return array.join();
  17312. }
  17313. function getUniforms(material) {
  17314. const shaderID = shaderIDs[material.type];
  17315. let uniforms;
  17316. if (shaderID) {
  17317. const shader = ShaderLib[shaderID];
  17318. uniforms = UniformsUtils.clone(shader.uniforms);
  17319. } else {
  17320. uniforms = material.uniforms;
  17321. }
  17322. return uniforms;
  17323. }
  17324. function acquireProgram(parameters, cacheKey) {
  17325. let program; // Check if code has been already compiled
  17326. for (let p = 0, pl = programs.length; p < pl; p++) {
  17327. const preexistingProgram = programs[p];
  17328. if (preexistingProgram.cacheKey === cacheKey) {
  17329. program = preexistingProgram;
  17330. ++program.usedTimes;
  17331. break;
  17332. }
  17333. }
  17334. if (program === undefined) {
  17335. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  17336. programs.push(program);
  17337. }
  17338. return program;
  17339. }
  17340. function releaseProgram(program) {
  17341. if (--program.usedTimes === 0) {
  17342. // Remove from unordered set
  17343. const i = programs.indexOf(program);
  17344. programs[i] = programs[programs.length - 1];
  17345. programs.pop(); // Free WebGL resources
  17346. program.destroy();
  17347. }
  17348. }
  17349. return {
  17350. getParameters: getParameters,
  17351. getProgramCacheKey: getProgramCacheKey,
  17352. getUniforms: getUniforms,
  17353. acquireProgram: acquireProgram,
  17354. releaseProgram: releaseProgram,
  17355. // Exposed for resource monitoring & error feedback via renderer.info:
  17356. programs: programs
  17357. };
  17358. }
  17359. function WebGLProperties() {
  17360. let properties = new WeakMap();
  17361. function get(object) {
  17362. let map = properties.get(object);
  17363. if (map === undefined) {
  17364. map = {};
  17365. properties.set(object, map);
  17366. }
  17367. return map;
  17368. }
  17369. function remove(object) {
  17370. properties.delete(object);
  17371. }
  17372. function update(object, key, value) {
  17373. properties.get(object)[key] = value;
  17374. }
  17375. function dispose() {
  17376. properties = new WeakMap();
  17377. }
  17378. return {
  17379. get: get,
  17380. remove: remove,
  17381. update: update,
  17382. dispose: dispose
  17383. };
  17384. }
  17385. function painterSortStable(a, b) {
  17386. if (a.groupOrder !== b.groupOrder) {
  17387. return a.groupOrder - b.groupOrder;
  17388. } else if (a.renderOrder !== b.renderOrder) {
  17389. return a.renderOrder - b.renderOrder;
  17390. } else if (a.program !== b.program) {
  17391. return a.program.id - b.program.id;
  17392. } else if (a.material.id !== b.material.id) {
  17393. return a.material.id - b.material.id;
  17394. } else if (a.z !== b.z) {
  17395. return a.z - b.z;
  17396. } else {
  17397. return a.id - b.id;
  17398. }
  17399. }
  17400. function reversePainterSortStable(a, b) {
  17401. if (a.groupOrder !== b.groupOrder) {
  17402. return a.groupOrder - b.groupOrder;
  17403. } else if (a.renderOrder !== b.renderOrder) {
  17404. return a.renderOrder - b.renderOrder;
  17405. } else if (a.z !== b.z) {
  17406. return b.z - a.z;
  17407. } else {
  17408. return a.id - b.id;
  17409. }
  17410. }
  17411. function WebGLRenderList(properties) {
  17412. const renderItems = [];
  17413. let renderItemsIndex = 0;
  17414. const opaque = [];
  17415. const transmissive = [];
  17416. const transparent = [];
  17417. const defaultProgram = {
  17418. id: -1
  17419. };
  17420. function init() {
  17421. renderItemsIndex = 0;
  17422. opaque.length = 0;
  17423. transmissive.length = 0;
  17424. transparent.length = 0;
  17425. }
  17426. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  17427. let renderItem = renderItems[renderItemsIndex];
  17428. const materialProperties = properties.get(material);
  17429. if (renderItem === undefined) {
  17430. renderItem = {
  17431. id: object.id,
  17432. object: object,
  17433. geometry: geometry,
  17434. material: material,
  17435. program: materialProperties.program || defaultProgram,
  17436. groupOrder: groupOrder,
  17437. renderOrder: object.renderOrder,
  17438. z: z,
  17439. group: group
  17440. };
  17441. renderItems[renderItemsIndex] = renderItem;
  17442. } else {
  17443. renderItem.id = object.id;
  17444. renderItem.object = object;
  17445. renderItem.geometry = geometry;
  17446. renderItem.material = material;
  17447. renderItem.program = materialProperties.program || defaultProgram;
  17448. renderItem.groupOrder = groupOrder;
  17449. renderItem.renderOrder = object.renderOrder;
  17450. renderItem.z = z;
  17451. renderItem.group = group;
  17452. }
  17453. renderItemsIndex++;
  17454. return renderItem;
  17455. }
  17456. function push(object, geometry, material, groupOrder, z, group) {
  17457. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17458. if (material.transmission > 0.0) {
  17459. transmissive.push(renderItem);
  17460. } else if (material.transparent === true) {
  17461. transparent.push(renderItem);
  17462. } else {
  17463. opaque.push(renderItem);
  17464. }
  17465. }
  17466. function unshift(object, geometry, material, groupOrder, z, group) {
  17467. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17468. if (material.transmission > 0.0) {
  17469. transmissive.unshift(renderItem);
  17470. } else if (material.transparent === true) {
  17471. transparent.unshift(renderItem);
  17472. } else {
  17473. opaque.unshift(renderItem);
  17474. }
  17475. }
  17476. function sort(customOpaqueSort, customTransparentSort) {
  17477. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  17478. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  17479. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  17480. }
  17481. function finish() {
  17482. // Clear references from inactive renderItems in the list
  17483. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  17484. const renderItem = renderItems[i];
  17485. if (renderItem.id === null) break;
  17486. renderItem.id = null;
  17487. renderItem.object = null;
  17488. renderItem.geometry = null;
  17489. renderItem.material = null;
  17490. renderItem.program = null;
  17491. renderItem.group = null;
  17492. }
  17493. }
  17494. return {
  17495. opaque: opaque,
  17496. transmissive: transmissive,
  17497. transparent: transparent,
  17498. init: init,
  17499. push: push,
  17500. unshift: unshift,
  17501. finish: finish,
  17502. sort: sort
  17503. };
  17504. }
  17505. function WebGLRenderLists(properties) {
  17506. let lists = new WeakMap();
  17507. function get(scene, renderCallDepth) {
  17508. let list;
  17509. if (lists.has(scene) === false) {
  17510. list = new WebGLRenderList(properties);
  17511. lists.set(scene, [list]);
  17512. } else {
  17513. if (renderCallDepth >= lists.get(scene).length) {
  17514. list = new WebGLRenderList(properties);
  17515. lists.get(scene).push(list);
  17516. } else {
  17517. list = lists.get(scene)[renderCallDepth];
  17518. }
  17519. }
  17520. return list;
  17521. }
  17522. function dispose() {
  17523. lists = new WeakMap();
  17524. }
  17525. return {
  17526. get: get,
  17527. dispose: dispose
  17528. };
  17529. }
  17530. function UniformsCache() {
  17531. const lights = {};
  17532. return {
  17533. get: function (light) {
  17534. if (lights[light.id] !== undefined) {
  17535. return lights[light.id];
  17536. }
  17537. let uniforms;
  17538. switch (light.type) {
  17539. case 'DirectionalLight':
  17540. uniforms = {
  17541. direction: new Vector3(),
  17542. color: new Color()
  17543. };
  17544. break;
  17545. case 'SpotLight':
  17546. uniforms = {
  17547. position: new Vector3(),
  17548. direction: new Vector3(),
  17549. color: new Color(),
  17550. distance: 0,
  17551. coneCos: 0,
  17552. penumbraCos: 0,
  17553. decay: 0
  17554. };
  17555. break;
  17556. case 'PointLight':
  17557. uniforms = {
  17558. position: new Vector3(),
  17559. color: new Color(),
  17560. distance: 0,
  17561. decay: 0
  17562. };
  17563. break;
  17564. case 'HemisphereLight':
  17565. uniforms = {
  17566. direction: new Vector3(),
  17567. skyColor: new Color(),
  17568. groundColor: new Color()
  17569. };
  17570. break;
  17571. case 'RectAreaLight':
  17572. uniforms = {
  17573. color: new Color(),
  17574. position: new Vector3(),
  17575. halfWidth: new Vector3(),
  17576. halfHeight: new Vector3()
  17577. };
  17578. break;
  17579. }
  17580. lights[light.id] = uniforms;
  17581. return uniforms;
  17582. }
  17583. };
  17584. }
  17585. function ShadowUniformsCache() {
  17586. const lights = {};
  17587. return {
  17588. get: function (light) {
  17589. if (lights[light.id] !== undefined) {
  17590. return lights[light.id];
  17591. }
  17592. let uniforms;
  17593. switch (light.type) {
  17594. case 'DirectionalLight':
  17595. uniforms = {
  17596. shadowBias: 0,
  17597. shadowNormalBias: 0,
  17598. shadowRadius: 1,
  17599. shadowMapSize: new Vector2()
  17600. };
  17601. break;
  17602. case 'SpotLight':
  17603. uniforms = {
  17604. shadowBias: 0,
  17605. shadowNormalBias: 0,
  17606. shadowRadius: 1,
  17607. shadowMapSize: new Vector2()
  17608. };
  17609. break;
  17610. case 'PointLight':
  17611. uniforms = {
  17612. shadowBias: 0,
  17613. shadowNormalBias: 0,
  17614. shadowRadius: 1,
  17615. shadowMapSize: new Vector2(),
  17616. shadowCameraNear: 1,
  17617. shadowCameraFar: 1000
  17618. };
  17619. break;
  17620. // TODO (abelnation): set RectAreaLight shadow uniforms
  17621. }
  17622. lights[light.id] = uniforms;
  17623. return uniforms;
  17624. }
  17625. };
  17626. }
  17627. let nextVersion = 0;
  17628. function shadowCastingLightsFirst(lightA, lightB) {
  17629. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  17630. }
  17631. function WebGLLights(extensions, capabilities) {
  17632. const cache = new UniformsCache();
  17633. const shadowCache = ShadowUniformsCache();
  17634. const state = {
  17635. version: 0,
  17636. hash: {
  17637. directionalLength: -1,
  17638. pointLength: -1,
  17639. spotLength: -1,
  17640. rectAreaLength: -1,
  17641. hemiLength: -1,
  17642. numDirectionalShadows: -1,
  17643. numPointShadows: -1,
  17644. numSpotShadows: -1
  17645. },
  17646. ambient: [0, 0, 0],
  17647. probe: [],
  17648. directional: [],
  17649. directionalShadow: [],
  17650. directionalShadowMap: [],
  17651. directionalShadowMatrix: [],
  17652. spot: [],
  17653. spotShadow: [],
  17654. spotShadowMap: [],
  17655. spotShadowMatrix: [],
  17656. rectArea: [],
  17657. rectAreaLTC1: null,
  17658. rectAreaLTC2: null,
  17659. point: [],
  17660. pointShadow: [],
  17661. pointShadowMap: [],
  17662. pointShadowMatrix: [],
  17663. hemi: []
  17664. };
  17665. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  17666. const vector3 = new Vector3();
  17667. const matrix4 = new Matrix4();
  17668. const matrix42 = new Matrix4();
  17669. function setup(lights, physicallyCorrectLights) {
  17670. let r = 0,
  17671. g = 0,
  17672. b = 0;
  17673. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  17674. let directionalLength = 0;
  17675. let pointLength = 0;
  17676. let spotLength = 0;
  17677. let rectAreaLength = 0;
  17678. let hemiLength = 0;
  17679. let numDirectionalShadows = 0;
  17680. let numPointShadows = 0;
  17681. let numSpotShadows = 0;
  17682. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  17683. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  17684. for (let i = 0, l = lights.length; i < l; i++) {
  17685. const light = lights[i];
  17686. const color = light.color;
  17687. const intensity = light.intensity;
  17688. const distance = light.distance;
  17689. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  17690. if (light.isAmbientLight) {
  17691. r += color.r * intensity * scaleFactor;
  17692. g += color.g * intensity * scaleFactor;
  17693. b += color.b * intensity * scaleFactor;
  17694. } else if (light.isLightProbe) {
  17695. for (let j = 0; j < 9; j++) {
  17696. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  17697. }
  17698. } else if (light.isDirectionalLight) {
  17699. const uniforms = cache.get(light);
  17700. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  17701. if (light.castShadow) {
  17702. const shadow = light.shadow;
  17703. const shadowUniforms = shadowCache.get(light);
  17704. shadowUniforms.shadowBias = shadow.bias;
  17705. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17706. shadowUniforms.shadowRadius = shadow.radius;
  17707. shadowUniforms.shadowMapSize = shadow.mapSize;
  17708. state.directionalShadow[directionalLength] = shadowUniforms;
  17709. state.directionalShadowMap[directionalLength] = shadowMap;
  17710. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  17711. numDirectionalShadows++;
  17712. }
  17713. state.directional[directionalLength] = uniforms;
  17714. directionalLength++;
  17715. } else if (light.isSpotLight) {
  17716. const uniforms = cache.get(light);
  17717. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17718. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  17719. uniforms.distance = distance;
  17720. uniforms.coneCos = Math.cos(light.angle);
  17721. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  17722. uniforms.decay = light.decay;
  17723. if (light.castShadow) {
  17724. const shadow = light.shadow;
  17725. const shadowUniforms = shadowCache.get(light);
  17726. shadowUniforms.shadowBias = shadow.bias;
  17727. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17728. shadowUniforms.shadowRadius = shadow.radius;
  17729. shadowUniforms.shadowMapSize = shadow.mapSize;
  17730. state.spotShadow[spotLength] = shadowUniforms;
  17731. state.spotShadowMap[spotLength] = shadowMap;
  17732. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  17733. numSpotShadows++;
  17734. }
  17735. state.spot[spotLength] = uniforms;
  17736. spotLength++;
  17737. } else if (light.isRectAreaLight) {
  17738. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  17739. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17740. // (b) intensity is the brightness of the light
  17741. uniforms.color.copy(color).multiplyScalar(intensity);
  17742. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17743. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17744. state.rectArea[rectAreaLength] = uniforms;
  17745. rectAreaLength++;
  17746. } else if (light.isPointLight) {
  17747. const uniforms = cache.get(light);
  17748. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  17749. uniforms.distance = light.distance;
  17750. uniforms.decay = light.decay;
  17751. if (light.castShadow) {
  17752. const shadow = light.shadow;
  17753. const shadowUniforms = shadowCache.get(light);
  17754. shadowUniforms.shadowBias = shadow.bias;
  17755. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17756. shadowUniforms.shadowRadius = shadow.radius;
  17757. shadowUniforms.shadowMapSize = shadow.mapSize;
  17758. shadowUniforms.shadowCameraNear = shadow.camera.near;
  17759. shadowUniforms.shadowCameraFar = shadow.camera.far;
  17760. state.pointShadow[pointLength] = shadowUniforms;
  17761. state.pointShadowMap[pointLength] = shadowMap;
  17762. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  17763. numPointShadows++;
  17764. }
  17765. state.point[pointLength] = uniforms;
  17766. pointLength++;
  17767. } else if (light.isHemisphereLight) {
  17768. const uniforms = cache.get(light);
  17769. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  17770. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  17771. state.hemi[hemiLength] = uniforms;
  17772. hemiLength++;
  17773. }
  17774. }
  17775. if (rectAreaLength > 0) {
  17776. if (capabilities.isWebGL2) {
  17777. // WebGL 2
  17778. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17779. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17780. } else {
  17781. // WebGL 1
  17782. if (extensions.has('OES_texture_float_linear') === true) {
  17783. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17784. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17785. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  17786. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  17787. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  17788. } else {
  17789. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  17790. }
  17791. }
  17792. }
  17793. state.ambient[0] = r;
  17794. state.ambient[1] = g;
  17795. state.ambient[2] = b;
  17796. const hash = state.hash;
  17797. 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) {
  17798. state.directional.length = directionalLength;
  17799. state.spot.length = spotLength;
  17800. state.rectArea.length = rectAreaLength;
  17801. state.point.length = pointLength;
  17802. state.hemi.length = hemiLength;
  17803. state.directionalShadow.length = numDirectionalShadows;
  17804. state.directionalShadowMap.length = numDirectionalShadows;
  17805. state.pointShadow.length = numPointShadows;
  17806. state.pointShadowMap.length = numPointShadows;
  17807. state.spotShadow.length = numSpotShadows;
  17808. state.spotShadowMap.length = numSpotShadows;
  17809. state.directionalShadowMatrix.length = numDirectionalShadows;
  17810. state.pointShadowMatrix.length = numPointShadows;
  17811. state.spotShadowMatrix.length = numSpotShadows;
  17812. hash.directionalLength = directionalLength;
  17813. hash.pointLength = pointLength;
  17814. hash.spotLength = spotLength;
  17815. hash.rectAreaLength = rectAreaLength;
  17816. hash.hemiLength = hemiLength;
  17817. hash.numDirectionalShadows = numDirectionalShadows;
  17818. hash.numPointShadows = numPointShadows;
  17819. hash.numSpotShadows = numSpotShadows;
  17820. state.version = nextVersion++;
  17821. }
  17822. }
  17823. function setupView(lights, camera) {
  17824. let directionalLength = 0;
  17825. let pointLength = 0;
  17826. let spotLength = 0;
  17827. let rectAreaLength = 0;
  17828. let hemiLength = 0;
  17829. const viewMatrix = camera.matrixWorldInverse;
  17830. for (let i = 0, l = lights.length; i < l; i++) {
  17831. const light = lights[i];
  17832. if (light.isDirectionalLight) {
  17833. const uniforms = state.directional[directionalLength];
  17834. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17835. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17836. uniforms.direction.sub(vector3);
  17837. uniforms.direction.transformDirection(viewMatrix);
  17838. directionalLength++;
  17839. } else if (light.isSpotLight) {
  17840. const uniforms = state.spot[spotLength];
  17841. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17842. uniforms.position.applyMatrix4(viewMatrix);
  17843. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17844. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17845. uniforms.direction.sub(vector3);
  17846. uniforms.direction.transformDirection(viewMatrix);
  17847. spotLength++;
  17848. } else if (light.isRectAreaLight) {
  17849. const uniforms = state.rectArea[rectAreaLength];
  17850. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17851. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  17852. matrix42.identity();
  17853. matrix4.copy(light.matrixWorld);
  17854. matrix4.premultiply(viewMatrix);
  17855. matrix42.extractRotation(matrix4);
  17856. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17857. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17858. uniforms.halfWidth.applyMatrix4(matrix42);
  17859. uniforms.halfHeight.applyMatrix4(matrix42);
  17860. rectAreaLength++;
  17861. } else if (light.isPointLight) {
  17862. const uniforms = state.point[pointLength];
  17863. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17864. uniforms.position.applyMatrix4(viewMatrix);
  17865. pointLength++;
  17866. } else if (light.isHemisphereLight) {
  17867. const uniforms = state.hemi[hemiLength];
  17868. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17869. uniforms.direction.transformDirection(viewMatrix);
  17870. uniforms.direction.normalize();
  17871. hemiLength++;
  17872. }
  17873. }
  17874. }
  17875. return {
  17876. setup: setup,
  17877. setupView: setupView,
  17878. state: state
  17879. };
  17880. }
  17881. function WebGLRenderState(extensions, capabilities) {
  17882. const lights = new WebGLLights(extensions, capabilities);
  17883. const lightsArray = [];
  17884. const shadowsArray = [];
  17885. function init() {
  17886. lightsArray.length = 0;
  17887. shadowsArray.length = 0;
  17888. }
  17889. function pushLight(light) {
  17890. lightsArray.push(light);
  17891. }
  17892. function pushShadow(shadowLight) {
  17893. shadowsArray.push(shadowLight);
  17894. }
  17895. function setupLights(physicallyCorrectLights) {
  17896. lights.setup(lightsArray, physicallyCorrectLights);
  17897. }
  17898. function setupLightsView(camera) {
  17899. lights.setupView(lightsArray, camera);
  17900. }
  17901. const state = {
  17902. lightsArray: lightsArray,
  17903. shadowsArray: shadowsArray,
  17904. lights: lights
  17905. };
  17906. return {
  17907. init: init,
  17908. state: state,
  17909. setupLights: setupLights,
  17910. setupLightsView: setupLightsView,
  17911. pushLight: pushLight,
  17912. pushShadow: pushShadow
  17913. };
  17914. }
  17915. function WebGLRenderStates(extensions, capabilities) {
  17916. let renderStates = new WeakMap();
  17917. function get(scene, renderCallDepth = 0) {
  17918. let renderState;
  17919. if (renderStates.has(scene) === false) {
  17920. renderState = new WebGLRenderState(extensions, capabilities);
  17921. renderStates.set(scene, [renderState]);
  17922. } else {
  17923. if (renderCallDepth >= renderStates.get(scene).length) {
  17924. renderState = new WebGLRenderState(extensions, capabilities);
  17925. renderStates.get(scene).push(renderState);
  17926. } else {
  17927. renderState = renderStates.get(scene)[renderCallDepth];
  17928. }
  17929. }
  17930. return renderState;
  17931. }
  17932. function dispose() {
  17933. renderStates = new WeakMap();
  17934. }
  17935. return {
  17936. get: get,
  17937. dispose: dispose
  17938. };
  17939. }
  17940. /**
  17941. * parameters = {
  17942. *
  17943. * opacity: <float>,
  17944. *
  17945. * map: new THREE.Texture( <Image> ),
  17946. *
  17947. * alphaMap: new THREE.Texture( <Image> ),
  17948. *
  17949. * displacementMap: new THREE.Texture( <Image> ),
  17950. * displacementScale: <float>,
  17951. * displacementBias: <float>,
  17952. *
  17953. * wireframe: <boolean>,
  17954. * wireframeLinewidth: <float>
  17955. * }
  17956. */
  17957. class MeshDepthMaterial extends Material {
  17958. constructor(parameters) {
  17959. super();
  17960. this.type = 'MeshDepthMaterial';
  17961. this.depthPacking = BasicDepthPacking;
  17962. this.map = null;
  17963. this.alphaMap = null;
  17964. this.displacementMap = null;
  17965. this.displacementScale = 1;
  17966. this.displacementBias = 0;
  17967. this.wireframe = false;
  17968. this.wireframeLinewidth = 1;
  17969. this.fog = false;
  17970. this.setValues(parameters);
  17971. }
  17972. copy(source) {
  17973. super.copy(source);
  17974. this.depthPacking = source.depthPacking;
  17975. this.map = source.map;
  17976. this.alphaMap = source.alphaMap;
  17977. this.displacementMap = source.displacementMap;
  17978. this.displacementScale = source.displacementScale;
  17979. this.displacementBias = source.displacementBias;
  17980. this.wireframe = source.wireframe;
  17981. this.wireframeLinewidth = source.wireframeLinewidth;
  17982. return this;
  17983. }
  17984. }
  17985. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17986. /**
  17987. * parameters = {
  17988. *
  17989. * referencePosition: <float>,
  17990. * nearDistance: <float>,
  17991. * farDistance: <float>,
  17992. *
  17993. * map: new THREE.Texture( <Image> ),
  17994. *
  17995. * alphaMap: new THREE.Texture( <Image> ),
  17996. *
  17997. * displacementMap: new THREE.Texture( <Image> ),
  17998. * displacementScale: <float>,
  17999. * displacementBias: <float>
  18000. *
  18001. * }
  18002. */
  18003. class MeshDistanceMaterial extends Material {
  18004. constructor(parameters) {
  18005. super();
  18006. this.type = 'MeshDistanceMaterial';
  18007. this.referencePosition = new Vector3();
  18008. this.nearDistance = 1;
  18009. this.farDistance = 1000;
  18010. this.map = null;
  18011. this.alphaMap = null;
  18012. this.displacementMap = null;
  18013. this.displacementScale = 1;
  18014. this.displacementBias = 0;
  18015. this.fog = false;
  18016. this.setValues(parameters);
  18017. }
  18018. copy(source) {
  18019. super.copy(source);
  18020. this.referencePosition.copy(source.referencePosition);
  18021. this.nearDistance = source.nearDistance;
  18022. this.farDistance = source.farDistance;
  18023. this.map = source.map;
  18024. this.alphaMap = source.alphaMap;
  18025. this.displacementMap = source.displacementMap;
  18026. this.displacementScale = source.displacementScale;
  18027. this.displacementBias = source.displacementBias;
  18028. return this;
  18029. }
  18030. }
  18031. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  18032. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  18033. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 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, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  18034. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  18035. let _frustum = new Frustum();
  18036. const _shadowMapSize = new Vector2(),
  18037. _viewportSize = new Vector2(),
  18038. _viewport = new Vector4(),
  18039. _depthMaterial = new MeshDepthMaterial({
  18040. depthPacking: RGBADepthPacking
  18041. }),
  18042. _distanceMaterial = new MeshDistanceMaterial(),
  18043. _materialCache = {},
  18044. _maxTextureSize = _capabilities.maxTextureSize;
  18045. const shadowSide = {
  18046. 0: BackSide,
  18047. 1: FrontSide,
  18048. 2: DoubleSide
  18049. };
  18050. const shadowMaterialVertical = new ShaderMaterial({
  18051. uniforms: {
  18052. shadow_pass: {
  18053. value: null
  18054. },
  18055. resolution: {
  18056. value: new Vector2()
  18057. },
  18058. radius: {
  18059. value: 4.0
  18060. },
  18061. samples: {
  18062. value: 8.0
  18063. }
  18064. },
  18065. vertexShader: vertex,
  18066. fragmentShader: fragment
  18067. });
  18068. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  18069. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  18070. const fullScreenTri = new BufferGeometry();
  18071. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  18072. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  18073. const scope = this;
  18074. this.enabled = false;
  18075. this.autoUpdate = true;
  18076. this.needsUpdate = false;
  18077. this.type = PCFShadowMap;
  18078. this.render = function (lights, scene, camera) {
  18079. if (scope.enabled === false) return;
  18080. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  18081. if (lights.length === 0) return;
  18082. const currentRenderTarget = _renderer.getRenderTarget();
  18083. const activeCubeFace = _renderer.getActiveCubeFace();
  18084. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  18085. const _state = _renderer.state; // Set GL state for depth map.
  18086. _state.setBlending(NoBlending);
  18087. _state.buffers.color.setClear(1, 1, 1, 1);
  18088. _state.buffers.depth.setTest(true);
  18089. _state.setScissorTest(false); // render depth map
  18090. for (let i = 0, il = lights.length; i < il; i++) {
  18091. const light = lights[i];
  18092. const shadow = light.shadow;
  18093. if (shadow === undefined) {
  18094. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  18095. continue;
  18096. }
  18097. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  18098. _shadowMapSize.copy(shadow.mapSize);
  18099. const shadowFrameExtents = shadow.getFrameExtents();
  18100. _shadowMapSize.multiply(shadowFrameExtents);
  18101. _viewportSize.copy(shadow.mapSize);
  18102. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  18103. if (_shadowMapSize.x > _maxTextureSize) {
  18104. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  18105. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  18106. shadow.mapSize.x = _viewportSize.x;
  18107. }
  18108. if (_shadowMapSize.y > _maxTextureSize) {
  18109. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  18110. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  18111. shadow.mapSize.y = _viewportSize.y;
  18112. }
  18113. }
  18114. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18115. const pars = {
  18116. minFilter: LinearFilter,
  18117. magFilter: LinearFilter,
  18118. format: RGBAFormat
  18119. };
  18120. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18121. shadow.map.texture.name = light.name + '.shadowMap';
  18122. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18123. shadow.camera.updateProjectionMatrix();
  18124. }
  18125. if (shadow.map === null) {
  18126. const pars = {
  18127. minFilter: NearestFilter,
  18128. magFilter: NearestFilter,
  18129. format: RGBAFormat
  18130. };
  18131. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18132. shadow.map.texture.name = light.name + '.shadowMap';
  18133. shadow.camera.updateProjectionMatrix();
  18134. }
  18135. _renderer.setRenderTarget(shadow.map);
  18136. _renderer.clear();
  18137. const viewportCount = shadow.getViewportCount();
  18138. for (let vp = 0; vp < viewportCount; vp++) {
  18139. const viewport = shadow.getViewport(vp);
  18140. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  18141. _state.viewport(_viewport);
  18142. shadow.updateMatrices(light, vp);
  18143. _frustum = shadow.getFrustum();
  18144. renderObject(scene, camera, shadow.camera, light, this.type);
  18145. } // do blur pass for VSM
  18146. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18147. VSMPass(shadow, camera);
  18148. }
  18149. shadow.needsUpdate = false;
  18150. }
  18151. scope.needsUpdate = false;
  18152. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  18153. };
  18154. function VSMPass(shadow, camera) {
  18155. const geometry = _objects.update(fullScreenMesh); // vertical pass
  18156. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  18157. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  18158. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  18159. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  18160. _renderer.setRenderTarget(shadow.mapPass);
  18161. _renderer.clear();
  18162. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  18163. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  18164. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  18165. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  18166. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  18167. _renderer.setRenderTarget(shadow.map);
  18168. _renderer.clear();
  18169. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  18170. }
  18171. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  18172. let result = null;
  18173. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  18174. if (customMaterial !== undefined) {
  18175. result = customMaterial;
  18176. } else {
  18177. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  18178. }
  18179. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  18180. // in this case we need a unique material instance reflecting the
  18181. // appropriate state
  18182. const keyA = result.uuid,
  18183. keyB = material.uuid;
  18184. let materialsForVariant = _materialCache[keyA];
  18185. if (materialsForVariant === undefined) {
  18186. materialsForVariant = {};
  18187. _materialCache[keyA] = materialsForVariant;
  18188. }
  18189. let cachedMaterial = materialsForVariant[keyB];
  18190. if (cachedMaterial === undefined) {
  18191. cachedMaterial = result.clone();
  18192. materialsForVariant[keyB] = cachedMaterial;
  18193. }
  18194. result = cachedMaterial;
  18195. }
  18196. result.visible = material.visible;
  18197. result.wireframe = material.wireframe;
  18198. if (type === VSMShadowMap) {
  18199. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  18200. } else {
  18201. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  18202. }
  18203. result.alphaMap = material.alphaMap;
  18204. result.alphaTest = material.alphaTest;
  18205. result.clipShadows = material.clipShadows;
  18206. result.clippingPlanes = material.clippingPlanes;
  18207. result.clipIntersection = material.clipIntersection;
  18208. result.displacementMap = material.displacementMap;
  18209. result.displacementScale = material.displacementScale;
  18210. result.displacementBias = material.displacementBias;
  18211. result.wireframeLinewidth = material.wireframeLinewidth;
  18212. result.linewidth = material.linewidth;
  18213. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  18214. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  18215. result.nearDistance = shadowCameraNear;
  18216. result.farDistance = shadowCameraFar;
  18217. }
  18218. return result;
  18219. }
  18220. function renderObject(object, camera, shadowCamera, light, type) {
  18221. if (object.visible === false) return;
  18222. const visible = object.layers.test(camera.layers);
  18223. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  18224. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  18225. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  18226. const geometry = _objects.update(object);
  18227. const material = object.material;
  18228. if (Array.isArray(material)) {
  18229. const groups = geometry.groups;
  18230. for (let k = 0, kl = groups.length; k < kl; k++) {
  18231. const group = groups[k];
  18232. const groupMaterial = material[group.materialIndex];
  18233. if (groupMaterial && groupMaterial.visible) {
  18234. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  18235. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  18236. }
  18237. }
  18238. } else if (material.visible) {
  18239. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  18240. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  18241. }
  18242. }
  18243. }
  18244. const children = object.children;
  18245. for (let i = 0, l = children.length; i < l; i++) {
  18246. renderObject(children[i], camera, shadowCamera, light, type);
  18247. }
  18248. }
  18249. }
  18250. function WebGLState(gl, extensions, capabilities) {
  18251. const isWebGL2 = capabilities.isWebGL2;
  18252. function ColorBuffer() {
  18253. let locked = false;
  18254. const color = new Vector4();
  18255. let currentColorMask = null;
  18256. const currentColorClear = new Vector4(0, 0, 0, 0);
  18257. return {
  18258. setMask: function (colorMask) {
  18259. if (currentColorMask !== colorMask && !locked) {
  18260. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  18261. currentColorMask = colorMask;
  18262. }
  18263. },
  18264. setLocked: function (lock) {
  18265. locked = lock;
  18266. },
  18267. setClear: function (r, g, b, a, premultipliedAlpha) {
  18268. if (premultipliedAlpha === true) {
  18269. r *= a;
  18270. g *= a;
  18271. b *= a;
  18272. }
  18273. color.set(r, g, b, a);
  18274. if (currentColorClear.equals(color) === false) {
  18275. gl.clearColor(r, g, b, a);
  18276. currentColorClear.copy(color);
  18277. }
  18278. },
  18279. reset: function () {
  18280. locked = false;
  18281. currentColorMask = null;
  18282. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  18283. }
  18284. };
  18285. }
  18286. function DepthBuffer() {
  18287. let locked = false;
  18288. let currentDepthMask = null;
  18289. let currentDepthFunc = null;
  18290. let currentDepthClear = null;
  18291. return {
  18292. setTest: function (depthTest) {
  18293. if (depthTest) {
  18294. enable(gl.DEPTH_TEST);
  18295. } else {
  18296. disable(gl.DEPTH_TEST);
  18297. }
  18298. },
  18299. setMask: function (depthMask) {
  18300. if (currentDepthMask !== depthMask && !locked) {
  18301. gl.depthMask(depthMask);
  18302. currentDepthMask = depthMask;
  18303. }
  18304. },
  18305. setFunc: function (depthFunc) {
  18306. if (currentDepthFunc !== depthFunc) {
  18307. if (depthFunc) {
  18308. switch (depthFunc) {
  18309. case NeverDepth:
  18310. gl.depthFunc(gl.NEVER);
  18311. break;
  18312. case AlwaysDepth:
  18313. gl.depthFunc(gl.ALWAYS);
  18314. break;
  18315. case LessDepth:
  18316. gl.depthFunc(gl.LESS);
  18317. break;
  18318. case LessEqualDepth:
  18319. gl.depthFunc(gl.LEQUAL);
  18320. break;
  18321. case EqualDepth:
  18322. gl.depthFunc(gl.EQUAL);
  18323. break;
  18324. case GreaterEqualDepth:
  18325. gl.depthFunc(gl.GEQUAL);
  18326. break;
  18327. case GreaterDepth:
  18328. gl.depthFunc(gl.GREATER);
  18329. break;
  18330. case NotEqualDepth:
  18331. gl.depthFunc(gl.NOTEQUAL);
  18332. break;
  18333. default:
  18334. gl.depthFunc(gl.LEQUAL);
  18335. }
  18336. } else {
  18337. gl.depthFunc(gl.LEQUAL);
  18338. }
  18339. currentDepthFunc = depthFunc;
  18340. }
  18341. },
  18342. setLocked: function (lock) {
  18343. locked = lock;
  18344. },
  18345. setClear: function (depth) {
  18346. if (currentDepthClear !== depth) {
  18347. gl.clearDepth(depth);
  18348. currentDepthClear = depth;
  18349. }
  18350. },
  18351. reset: function () {
  18352. locked = false;
  18353. currentDepthMask = null;
  18354. currentDepthFunc = null;
  18355. currentDepthClear = null;
  18356. }
  18357. };
  18358. }
  18359. function StencilBuffer() {
  18360. let locked = false;
  18361. let currentStencilMask = null;
  18362. let currentStencilFunc = null;
  18363. let currentStencilRef = null;
  18364. let currentStencilFuncMask = null;
  18365. let currentStencilFail = null;
  18366. let currentStencilZFail = null;
  18367. let currentStencilZPass = null;
  18368. let currentStencilClear = null;
  18369. return {
  18370. setTest: function (stencilTest) {
  18371. if (!locked) {
  18372. if (stencilTest) {
  18373. enable(gl.STENCIL_TEST);
  18374. } else {
  18375. disable(gl.STENCIL_TEST);
  18376. }
  18377. }
  18378. },
  18379. setMask: function (stencilMask) {
  18380. if (currentStencilMask !== stencilMask && !locked) {
  18381. gl.stencilMask(stencilMask);
  18382. currentStencilMask = stencilMask;
  18383. }
  18384. },
  18385. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  18386. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  18387. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  18388. currentStencilFunc = stencilFunc;
  18389. currentStencilRef = stencilRef;
  18390. currentStencilFuncMask = stencilMask;
  18391. }
  18392. },
  18393. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  18394. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  18395. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  18396. currentStencilFail = stencilFail;
  18397. currentStencilZFail = stencilZFail;
  18398. currentStencilZPass = stencilZPass;
  18399. }
  18400. },
  18401. setLocked: function (lock) {
  18402. locked = lock;
  18403. },
  18404. setClear: function (stencil) {
  18405. if (currentStencilClear !== stencil) {
  18406. gl.clearStencil(stencil);
  18407. currentStencilClear = stencil;
  18408. }
  18409. },
  18410. reset: function () {
  18411. locked = false;
  18412. currentStencilMask = null;
  18413. currentStencilFunc = null;
  18414. currentStencilRef = null;
  18415. currentStencilFuncMask = null;
  18416. currentStencilFail = null;
  18417. currentStencilZFail = null;
  18418. currentStencilZPass = null;
  18419. currentStencilClear = null;
  18420. }
  18421. };
  18422. } //
  18423. const colorBuffer = new ColorBuffer();
  18424. const depthBuffer = new DepthBuffer();
  18425. const stencilBuffer = new StencilBuffer();
  18426. let enabledCapabilities = {};
  18427. let xrFramebuffer = null;
  18428. let currentBoundFramebuffers = {};
  18429. let currentProgram = null;
  18430. let currentBlendingEnabled = false;
  18431. let currentBlending = null;
  18432. let currentBlendEquation = null;
  18433. let currentBlendSrc = null;
  18434. let currentBlendDst = null;
  18435. let currentBlendEquationAlpha = null;
  18436. let currentBlendSrcAlpha = null;
  18437. let currentBlendDstAlpha = null;
  18438. let currentPremultipledAlpha = false;
  18439. let currentFlipSided = null;
  18440. let currentCullFace = null;
  18441. let currentLineWidth = null;
  18442. let currentPolygonOffsetFactor = null;
  18443. let currentPolygonOffsetUnits = null;
  18444. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  18445. let lineWidthAvailable = false;
  18446. let version = 0;
  18447. const glVersion = gl.getParameter(gl.VERSION);
  18448. if (glVersion.indexOf('WebGL') !== -1) {
  18449. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  18450. lineWidthAvailable = version >= 1.0;
  18451. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  18452. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  18453. lineWidthAvailable = version >= 2.0;
  18454. }
  18455. let currentTextureSlot = null;
  18456. let currentBoundTextures = {};
  18457. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  18458. const viewportParam = gl.getParameter(gl.VIEWPORT);
  18459. const currentScissor = new Vector4().fromArray(scissorParam);
  18460. const currentViewport = new Vector4().fromArray(viewportParam);
  18461. function createTexture(type, target, count) {
  18462. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  18463. const texture = gl.createTexture();
  18464. gl.bindTexture(type, texture);
  18465. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  18466. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  18467. for (let i = 0; i < count; i++) {
  18468. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  18469. }
  18470. return texture;
  18471. }
  18472. const emptyTextures = {};
  18473. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  18474. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  18475. colorBuffer.setClear(0, 0, 0, 1);
  18476. depthBuffer.setClear(1);
  18477. stencilBuffer.setClear(0);
  18478. enable(gl.DEPTH_TEST);
  18479. depthBuffer.setFunc(LessEqualDepth);
  18480. setFlipSided(false);
  18481. setCullFace(CullFaceBack);
  18482. enable(gl.CULL_FACE);
  18483. setBlending(NoBlending); //
  18484. function enable(id) {
  18485. if (enabledCapabilities[id] !== true) {
  18486. gl.enable(id);
  18487. enabledCapabilities[id] = true;
  18488. }
  18489. }
  18490. function disable(id) {
  18491. if (enabledCapabilities[id] !== false) {
  18492. gl.disable(id);
  18493. enabledCapabilities[id] = false;
  18494. }
  18495. }
  18496. function bindXRFramebuffer(framebuffer) {
  18497. if (framebuffer !== xrFramebuffer) {
  18498. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  18499. xrFramebuffer = framebuffer;
  18500. }
  18501. }
  18502. function bindFramebuffer(target, framebuffer) {
  18503. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  18504. if (currentBoundFramebuffers[target] !== framebuffer) {
  18505. gl.bindFramebuffer(target, framebuffer);
  18506. currentBoundFramebuffers[target] = framebuffer;
  18507. if (isWebGL2) {
  18508. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  18509. if (target === gl.DRAW_FRAMEBUFFER) {
  18510. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  18511. }
  18512. if (target === gl.FRAMEBUFFER) {
  18513. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  18514. }
  18515. }
  18516. return true;
  18517. }
  18518. return false;
  18519. }
  18520. function useProgram(program) {
  18521. if (currentProgram !== program) {
  18522. gl.useProgram(program);
  18523. currentProgram = program;
  18524. return true;
  18525. }
  18526. return false;
  18527. }
  18528. const equationToGL = {
  18529. [AddEquation]: gl.FUNC_ADD,
  18530. [SubtractEquation]: gl.FUNC_SUBTRACT,
  18531. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  18532. };
  18533. if (isWebGL2) {
  18534. equationToGL[MinEquation] = gl.MIN;
  18535. equationToGL[MaxEquation] = gl.MAX;
  18536. } else {
  18537. const extension = extensions.get('EXT_blend_minmax');
  18538. if (extension !== null) {
  18539. equationToGL[MinEquation] = extension.MIN_EXT;
  18540. equationToGL[MaxEquation] = extension.MAX_EXT;
  18541. }
  18542. }
  18543. const factorToGL = {
  18544. [ZeroFactor]: gl.ZERO,
  18545. [OneFactor]: gl.ONE,
  18546. [SrcColorFactor]: gl.SRC_COLOR,
  18547. [SrcAlphaFactor]: gl.SRC_ALPHA,
  18548. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  18549. [DstColorFactor]: gl.DST_COLOR,
  18550. [DstAlphaFactor]: gl.DST_ALPHA,
  18551. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  18552. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  18553. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  18554. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  18555. };
  18556. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  18557. if (blending === NoBlending) {
  18558. if (currentBlendingEnabled === true) {
  18559. disable(gl.BLEND);
  18560. currentBlendingEnabled = false;
  18561. }
  18562. return;
  18563. }
  18564. if (currentBlendingEnabled === false) {
  18565. enable(gl.BLEND);
  18566. currentBlendingEnabled = true;
  18567. }
  18568. if (blending !== CustomBlending) {
  18569. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  18570. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  18571. gl.blendEquation(gl.FUNC_ADD);
  18572. currentBlendEquation = AddEquation;
  18573. currentBlendEquationAlpha = AddEquation;
  18574. }
  18575. if (premultipliedAlpha) {
  18576. switch (blending) {
  18577. case NormalBlending:
  18578. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  18579. break;
  18580. case AdditiveBlending:
  18581. gl.blendFunc(gl.ONE, gl.ONE);
  18582. break;
  18583. case SubtractiveBlending:
  18584. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  18585. break;
  18586. case MultiplyBlending:
  18587. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  18588. break;
  18589. default:
  18590. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18591. break;
  18592. }
  18593. } else {
  18594. switch (blending) {
  18595. case NormalBlending:
  18596. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  18597. break;
  18598. case AdditiveBlending:
  18599. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  18600. break;
  18601. case SubtractiveBlending:
  18602. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  18603. break;
  18604. case MultiplyBlending:
  18605. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  18606. break;
  18607. default:
  18608. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18609. break;
  18610. }
  18611. }
  18612. currentBlendSrc = null;
  18613. currentBlendDst = null;
  18614. currentBlendSrcAlpha = null;
  18615. currentBlendDstAlpha = null;
  18616. currentBlending = blending;
  18617. currentPremultipledAlpha = premultipliedAlpha;
  18618. }
  18619. return;
  18620. } // custom blending
  18621. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18622. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18623. blendDstAlpha = blendDstAlpha || blendDst;
  18624. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  18625. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  18626. currentBlendEquation = blendEquation;
  18627. currentBlendEquationAlpha = blendEquationAlpha;
  18628. }
  18629. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  18630. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  18631. currentBlendSrc = blendSrc;
  18632. currentBlendDst = blendDst;
  18633. currentBlendSrcAlpha = blendSrcAlpha;
  18634. currentBlendDstAlpha = blendDstAlpha;
  18635. }
  18636. currentBlending = blending;
  18637. currentPremultipledAlpha = null;
  18638. }
  18639. function setMaterial(material, frontFaceCW) {
  18640. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  18641. let flipSided = material.side === BackSide;
  18642. if (frontFaceCW) flipSided = !flipSided;
  18643. setFlipSided(flipSided);
  18644. 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);
  18645. depthBuffer.setFunc(material.depthFunc);
  18646. depthBuffer.setTest(material.depthTest);
  18647. depthBuffer.setMask(material.depthWrite);
  18648. colorBuffer.setMask(material.colorWrite);
  18649. const stencilWrite = material.stencilWrite;
  18650. stencilBuffer.setTest(stencilWrite);
  18651. if (stencilWrite) {
  18652. stencilBuffer.setMask(material.stencilWriteMask);
  18653. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  18654. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  18655. }
  18656. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  18657. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  18658. } //
  18659. function setFlipSided(flipSided) {
  18660. if (currentFlipSided !== flipSided) {
  18661. if (flipSided) {
  18662. gl.frontFace(gl.CW);
  18663. } else {
  18664. gl.frontFace(gl.CCW);
  18665. }
  18666. currentFlipSided = flipSided;
  18667. }
  18668. }
  18669. function setCullFace(cullFace) {
  18670. if (cullFace !== CullFaceNone) {
  18671. enable(gl.CULL_FACE);
  18672. if (cullFace !== currentCullFace) {
  18673. if (cullFace === CullFaceBack) {
  18674. gl.cullFace(gl.BACK);
  18675. } else if (cullFace === CullFaceFront) {
  18676. gl.cullFace(gl.FRONT);
  18677. } else {
  18678. gl.cullFace(gl.FRONT_AND_BACK);
  18679. }
  18680. }
  18681. } else {
  18682. disable(gl.CULL_FACE);
  18683. }
  18684. currentCullFace = cullFace;
  18685. }
  18686. function setLineWidth(width) {
  18687. if (width !== currentLineWidth) {
  18688. if (lineWidthAvailable) gl.lineWidth(width);
  18689. currentLineWidth = width;
  18690. }
  18691. }
  18692. function setPolygonOffset(polygonOffset, factor, units) {
  18693. if (polygonOffset) {
  18694. enable(gl.POLYGON_OFFSET_FILL);
  18695. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  18696. gl.polygonOffset(factor, units);
  18697. currentPolygonOffsetFactor = factor;
  18698. currentPolygonOffsetUnits = units;
  18699. }
  18700. } else {
  18701. disable(gl.POLYGON_OFFSET_FILL);
  18702. }
  18703. }
  18704. function setScissorTest(scissorTest) {
  18705. if (scissorTest) {
  18706. enable(gl.SCISSOR_TEST);
  18707. } else {
  18708. disable(gl.SCISSOR_TEST);
  18709. }
  18710. } // texture
  18711. function activeTexture(webglSlot) {
  18712. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18713. if (currentTextureSlot !== webglSlot) {
  18714. gl.activeTexture(webglSlot);
  18715. currentTextureSlot = webglSlot;
  18716. }
  18717. }
  18718. function bindTexture(webglType, webglTexture) {
  18719. if (currentTextureSlot === null) {
  18720. activeTexture();
  18721. }
  18722. let boundTexture = currentBoundTextures[currentTextureSlot];
  18723. if (boundTexture === undefined) {
  18724. boundTexture = {
  18725. type: undefined,
  18726. texture: undefined
  18727. };
  18728. currentBoundTextures[currentTextureSlot] = boundTexture;
  18729. }
  18730. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  18731. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  18732. boundTexture.type = webglType;
  18733. boundTexture.texture = webglTexture;
  18734. }
  18735. }
  18736. function unbindTexture() {
  18737. const boundTexture = currentBoundTextures[currentTextureSlot];
  18738. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  18739. gl.bindTexture(boundTexture.type, null);
  18740. boundTexture.type = undefined;
  18741. boundTexture.texture = undefined;
  18742. }
  18743. }
  18744. function compressedTexImage2D() {
  18745. try {
  18746. gl.compressedTexImage2D.apply(gl, arguments);
  18747. } catch (error) {
  18748. console.error('THREE.WebGLState:', error);
  18749. }
  18750. }
  18751. function texImage2D() {
  18752. try {
  18753. gl.texImage2D.apply(gl, arguments);
  18754. } catch (error) {
  18755. console.error('THREE.WebGLState:', error);
  18756. }
  18757. }
  18758. function texImage3D() {
  18759. try {
  18760. gl.texImage3D.apply(gl, arguments);
  18761. } catch (error) {
  18762. console.error('THREE.WebGLState:', error);
  18763. }
  18764. } //
  18765. function scissor(scissor) {
  18766. if (currentScissor.equals(scissor) === false) {
  18767. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  18768. currentScissor.copy(scissor);
  18769. }
  18770. }
  18771. function viewport(viewport) {
  18772. if (currentViewport.equals(viewport) === false) {
  18773. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  18774. currentViewport.copy(viewport);
  18775. }
  18776. } //
  18777. function reset() {
  18778. // reset state
  18779. gl.disable(gl.BLEND);
  18780. gl.disable(gl.CULL_FACE);
  18781. gl.disable(gl.DEPTH_TEST);
  18782. gl.disable(gl.POLYGON_OFFSET_FILL);
  18783. gl.disable(gl.SCISSOR_TEST);
  18784. gl.disable(gl.STENCIL_TEST);
  18785. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  18786. gl.blendEquation(gl.FUNC_ADD);
  18787. gl.blendFunc(gl.ONE, gl.ZERO);
  18788. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  18789. gl.colorMask(true, true, true, true);
  18790. gl.clearColor(0, 0, 0, 0);
  18791. gl.depthMask(true);
  18792. gl.depthFunc(gl.LESS);
  18793. gl.clearDepth(1);
  18794. gl.stencilMask(0xffffffff);
  18795. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  18796. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  18797. gl.clearStencil(0);
  18798. gl.cullFace(gl.BACK);
  18799. gl.frontFace(gl.CCW);
  18800. gl.polygonOffset(0, 0);
  18801. gl.activeTexture(gl.TEXTURE0);
  18802. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18803. if (isWebGL2 === true) {
  18804. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  18805. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  18806. }
  18807. gl.useProgram(null);
  18808. gl.lineWidth(1);
  18809. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  18810. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  18811. enabledCapabilities = {};
  18812. currentTextureSlot = null;
  18813. currentBoundTextures = {};
  18814. xrFramebuffer = null;
  18815. currentBoundFramebuffers = {};
  18816. currentProgram = null;
  18817. currentBlendingEnabled = false;
  18818. currentBlending = null;
  18819. currentBlendEquation = null;
  18820. currentBlendSrc = null;
  18821. currentBlendDst = null;
  18822. currentBlendEquationAlpha = null;
  18823. currentBlendSrcAlpha = null;
  18824. currentBlendDstAlpha = null;
  18825. currentPremultipledAlpha = false;
  18826. currentFlipSided = null;
  18827. currentCullFace = null;
  18828. currentLineWidth = null;
  18829. currentPolygonOffsetFactor = null;
  18830. currentPolygonOffsetUnits = null;
  18831. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  18832. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  18833. colorBuffer.reset();
  18834. depthBuffer.reset();
  18835. stencilBuffer.reset();
  18836. }
  18837. return {
  18838. buffers: {
  18839. color: colorBuffer,
  18840. depth: depthBuffer,
  18841. stencil: stencilBuffer
  18842. },
  18843. enable: enable,
  18844. disable: disable,
  18845. bindFramebuffer: bindFramebuffer,
  18846. bindXRFramebuffer: bindXRFramebuffer,
  18847. useProgram: useProgram,
  18848. setBlending: setBlending,
  18849. setMaterial: setMaterial,
  18850. setFlipSided: setFlipSided,
  18851. setCullFace: setCullFace,
  18852. setLineWidth: setLineWidth,
  18853. setPolygonOffset: setPolygonOffset,
  18854. setScissorTest: setScissorTest,
  18855. activeTexture: activeTexture,
  18856. bindTexture: bindTexture,
  18857. unbindTexture: unbindTexture,
  18858. compressedTexImage2D: compressedTexImage2D,
  18859. texImage2D: texImage2D,
  18860. texImage3D: texImage3D,
  18861. scissor: scissor,
  18862. viewport: viewport,
  18863. reset: reset
  18864. };
  18865. }
  18866. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  18867. const isWebGL2 = capabilities.isWebGL2;
  18868. const maxTextures = capabilities.maxTextures;
  18869. const maxCubemapSize = capabilities.maxCubemapSize;
  18870. const maxTextureSize = capabilities.maxTextureSize;
  18871. const maxSamples = capabilities.maxSamples;
  18872. const _videoTextures = new WeakMap();
  18873. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18874. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18875. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18876. let useOffscreenCanvas = false;
  18877. try {
  18878. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  18879. } catch (err) {// Ignore any errors
  18880. }
  18881. function createCanvas(width, height) {
  18882. // Use OffscreenCanvas when available. Specially needed in web workers
  18883. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
  18884. }
  18885. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  18886. let scale = 1; // handle case if texture exceeds max size
  18887. if (image.width > maxSize || image.height > maxSize) {
  18888. scale = maxSize / Math.max(image.width, image.height);
  18889. } // only perform resize if necessary
  18890. if (scale < 1 || needsPowerOfTwo === true) {
  18891. // only perform resize for certain image types
  18892. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  18893. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  18894. const width = floor(scale * image.width);
  18895. const height = floor(scale * image.height);
  18896. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  18897. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  18898. canvas.width = width;
  18899. canvas.height = height;
  18900. const context = canvas.getContext('2d');
  18901. context.drawImage(image, 0, 0, width, height);
  18902. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  18903. return canvas;
  18904. } else {
  18905. if ('data' in image) {
  18906. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  18907. }
  18908. return image;
  18909. }
  18910. }
  18911. return image;
  18912. }
  18913. function isPowerOfTwo$1(image) {
  18914. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  18915. }
  18916. function textureNeedsPowerOfTwo(texture) {
  18917. if (isWebGL2) return false;
  18918. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18919. }
  18920. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  18921. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18922. }
  18923. function generateMipmap(target, texture, width, height, depth = 1) {
  18924. _gl.generateMipmap(target);
  18925. const textureProperties = properties.get(texture);
  18926. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  18927. }
  18928. function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
  18929. if (isWebGL2 === false) return glFormat;
  18930. if (internalFormatName !== null) {
  18931. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  18932. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  18933. }
  18934. let internalFormat = glFormat;
  18935. if (glFormat === _gl.RED) {
  18936. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  18937. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  18938. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  18939. }
  18940. if (glFormat === _gl.RGB) {
  18941. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  18942. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  18943. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  18944. }
  18945. if (glFormat === _gl.RGBA) {
  18946. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  18947. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  18948. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  18949. }
  18950. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  18951. extensions.get('EXT_color_buffer_float');
  18952. }
  18953. return internalFormat;
  18954. } // Fallback filters for non-power-of-2 textures
  18955. function filterFallback(f) {
  18956. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  18957. return _gl.NEAREST;
  18958. }
  18959. return _gl.LINEAR;
  18960. } //
  18961. function onTextureDispose(event) {
  18962. const texture = event.target;
  18963. texture.removeEventListener('dispose', onTextureDispose);
  18964. deallocateTexture(texture);
  18965. if (texture.isVideoTexture) {
  18966. _videoTextures.delete(texture);
  18967. }
  18968. info.memory.textures--;
  18969. }
  18970. function onRenderTargetDispose(event) {
  18971. const renderTarget = event.target;
  18972. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  18973. deallocateRenderTarget(renderTarget);
  18974. } //
  18975. function deallocateTexture(texture) {
  18976. const textureProperties = properties.get(texture);
  18977. if (textureProperties.__webglInit === undefined) return;
  18978. _gl.deleteTexture(textureProperties.__webglTexture);
  18979. properties.remove(texture);
  18980. }
  18981. function deallocateRenderTarget(renderTarget) {
  18982. const texture = renderTarget.texture;
  18983. const renderTargetProperties = properties.get(renderTarget);
  18984. const textureProperties = properties.get(texture);
  18985. if (!renderTarget) return;
  18986. if (textureProperties.__webglTexture !== undefined) {
  18987. _gl.deleteTexture(textureProperties.__webglTexture);
  18988. info.memory.textures--;
  18989. }
  18990. if (renderTarget.depthTexture) {
  18991. renderTarget.depthTexture.dispose();
  18992. }
  18993. if (renderTarget.isWebGLCubeRenderTarget) {
  18994. for (let i = 0; i < 6; i++) {
  18995. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  18996. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  18997. }
  18998. } else {
  18999. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  19000. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  19001. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  19002. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  19003. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  19004. }
  19005. if (renderTarget.isWebGLMultipleRenderTargets) {
  19006. for (let i = 0, il = texture.length; i < il; i++) {
  19007. const attachmentProperties = properties.get(texture[i]);
  19008. if (attachmentProperties.__webglTexture) {
  19009. _gl.deleteTexture(attachmentProperties.__webglTexture);
  19010. info.memory.textures--;
  19011. }
  19012. properties.remove(texture[i]);
  19013. }
  19014. }
  19015. properties.remove(texture);
  19016. properties.remove(renderTarget);
  19017. } //
  19018. let textureUnits = 0;
  19019. function resetTextureUnits() {
  19020. textureUnits = 0;
  19021. }
  19022. function allocateTextureUnit() {
  19023. const textureUnit = textureUnits;
  19024. if (textureUnit >= maxTextures) {
  19025. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  19026. }
  19027. textureUnits += 1;
  19028. return textureUnit;
  19029. } //
  19030. function setTexture2D(texture, slot) {
  19031. const textureProperties = properties.get(texture);
  19032. if (texture.isVideoTexture) updateVideoTexture(texture);
  19033. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19034. const image = texture.image;
  19035. if (image === undefined) {
  19036. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  19037. } else if (image.complete === false) {
  19038. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  19039. } else {
  19040. uploadTexture(textureProperties, texture, slot);
  19041. return;
  19042. }
  19043. }
  19044. state.activeTexture(_gl.TEXTURE0 + slot);
  19045. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  19046. }
  19047. function setTexture2DArray(texture, slot) {
  19048. const textureProperties = properties.get(texture);
  19049. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19050. uploadTexture(textureProperties, texture, slot);
  19051. return;
  19052. }
  19053. state.activeTexture(_gl.TEXTURE0 + slot);
  19054. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  19055. }
  19056. function setTexture3D(texture, slot) {
  19057. const textureProperties = properties.get(texture);
  19058. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19059. uploadTexture(textureProperties, texture, slot);
  19060. return;
  19061. }
  19062. state.activeTexture(_gl.TEXTURE0 + slot);
  19063. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  19064. }
  19065. function setTextureCube(texture, slot) {
  19066. const textureProperties = properties.get(texture);
  19067. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19068. uploadCubeTexture(textureProperties, texture, slot);
  19069. return;
  19070. }
  19071. state.activeTexture(_gl.TEXTURE0 + slot);
  19072. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  19073. }
  19074. const wrappingToGL = {
  19075. [RepeatWrapping]: _gl.REPEAT,
  19076. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  19077. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  19078. };
  19079. const filterToGL = {
  19080. [NearestFilter]: _gl.NEAREST,
  19081. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  19082. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  19083. [LinearFilter]: _gl.LINEAR,
  19084. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  19085. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  19086. };
  19087. function setTextureParameters(textureType, texture, supportsMips) {
  19088. if (supportsMips) {
  19089. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  19090. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  19091. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  19092. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  19093. }
  19094. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  19095. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  19096. } else {
  19097. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  19098. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  19099. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  19100. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  19101. }
  19102. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  19103. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  19104. }
  19105. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  19106. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  19107. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  19108. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  19109. }
  19110. }
  19111. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  19112. const extension = extensions.get('EXT_texture_filter_anisotropic');
  19113. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  19114. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  19115. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  19116. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  19117. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  19118. }
  19119. }
  19120. }
  19121. function initTexture(textureProperties, texture) {
  19122. if (textureProperties.__webglInit === undefined) {
  19123. textureProperties.__webglInit = true;
  19124. texture.addEventListener('dispose', onTextureDispose);
  19125. textureProperties.__webglTexture = _gl.createTexture();
  19126. info.memory.textures++;
  19127. }
  19128. }
  19129. function uploadTexture(textureProperties, texture, slot) {
  19130. let textureType = _gl.TEXTURE_2D;
  19131. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  19132. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  19133. initTexture(textureProperties, texture);
  19134. state.activeTexture(_gl.TEXTURE0 + slot);
  19135. state.bindTexture(textureType, textureProperties.__webglTexture);
  19136. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  19137. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  19138. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  19139. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  19140. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  19141. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  19142. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  19143. glFormat = utils.convert(texture.format);
  19144. let glType = utils.convert(texture.type),
  19145. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  19146. setTextureParameters(textureType, texture, supportsMips);
  19147. let mipmap;
  19148. const mipmaps = texture.mipmaps;
  19149. if (texture.isDepthTexture) {
  19150. // populate depth texture with dummy data
  19151. glInternalFormat = _gl.DEPTH_COMPONENT;
  19152. if (isWebGL2) {
  19153. if (texture.type === FloatType) {
  19154. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  19155. } else if (texture.type === UnsignedIntType) {
  19156. glInternalFormat = _gl.DEPTH_COMPONENT24;
  19157. } else if (texture.type === UnsignedInt248Type) {
  19158. glInternalFormat = _gl.DEPTH24_STENCIL8;
  19159. } else {
  19160. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  19161. }
  19162. } else {
  19163. if (texture.type === FloatType) {
  19164. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  19165. }
  19166. } // validation checks for WebGL 1
  19167. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  19168. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19169. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  19170. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19171. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  19172. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  19173. texture.type = UnsignedShortType;
  19174. glType = utils.convert(texture.type);
  19175. }
  19176. }
  19177. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  19178. // Depth stencil textures need the DEPTH_STENCIL internal format
  19179. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19180. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19181. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  19182. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19183. if (texture.type !== UnsignedInt248Type) {
  19184. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  19185. texture.type = UnsignedInt248Type;
  19186. glType = utils.convert(texture.type);
  19187. }
  19188. } //
  19189. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  19190. } else if (texture.isDataTexture) {
  19191. // use manually created mipmaps if available
  19192. // if there are no manual mipmaps
  19193. // set 0 level mipmap and then use GL to generate other mipmap levels
  19194. if (mipmaps.length > 0 && supportsMips) {
  19195. for (let i = 0, il = mipmaps.length; i < il; i++) {
  19196. mipmap = mipmaps[i];
  19197. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19198. }
  19199. texture.generateMipmaps = false;
  19200. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19201. } else {
  19202. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  19203. textureProperties.__maxMipLevel = 0;
  19204. }
  19205. } else if (texture.isCompressedTexture) {
  19206. for (let i = 0, il = mipmaps.length; i < il; i++) {
  19207. mipmap = mipmaps[i];
  19208. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19209. if (glFormat !== null) {
  19210. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19211. } else {
  19212. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  19213. }
  19214. } else {
  19215. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19216. }
  19217. }
  19218. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19219. } else if (texture.isDataTexture2DArray) {
  19220. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19221. textureProperties.__maxMipLevel = 0;
  19222. } else if (texture.isDataTexture3D) {
  19223. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19224. textureProperties.__maxMipLevel = 0;
  19225. } else {
  19226. // regular Texture (image, video, canvas)
  19227. // use manually created mipmaps if available
  19228. // if there are no manual mipmaps
  19229. // set 0 level mipmap and then use GL to generate other mipmap levels
  19230. if (mipmaps.length > 0 && supportsMips) {
  19231. for (let i = 0, il = mipmaps.length; i < il; i++) {
  19232. mipmap = mipmaps[i];
  19233. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  19234. }
  19235. texture.generateMipmaps = false;
  19236. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19237. } else {
  19238. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  19239. textureProperties.__maxMipLevel = 0;
  19240. }
  19241. }
  19242. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19243. generateMipmap(textureType, texture, image.width, image.height);
  19244. }
  19245. textureProperties.__version = texture.version;
  19246. if (texture.onUpdate) texture.onUpdate(texture);
  19247. }
  19248. function uploadCubeTexture(textureProperties, texture, slot) {
  19249. if (texture.image.length !== 6) return;
  19250. initTexture(textureProperties, texture);
  19251. state.activeTexture(_gl.TEXTURE0 + slot);
  19252. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  19253. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  19254. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  19255. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  19256. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  19257. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  19258. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  19259. const cubeImage = [];
  19260. for (let i = 0; i < 6; i++) {
  19261. if (!isCompressed && !isDataTexture) {
  19262. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  19263. } else {
  19264. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  19265. }
  19266. }
  19267. const image = cubeImage[0],
  19268. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  19269. glFormat = utils.convert(texture.format),
  19270. glType = utils.convert(texture.type),
  19271. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  19272. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  19273. let mipmaps;
  19274. if (isCompressed) {
  19275. for (let i = 0; i < 6; i++) {
  19276. mipmaps = cubeImage[i].mipmaps;
  19277. for (let j = 0; j < mipmaps.length; j++) {
  19278. const mipmap = mipmaps[j];
  19279. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19280. if (glFormat !== null) {
  19281. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19282. } else {
  19283. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  19284. }
  19285. } else {
  19286. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19287. }
  19288. }
  19289. }
  19290. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19291. } else {
  19292. mipmaps = texture.mipmaps;
  19293. for (let i = 0; i < 6; i++) {
  19294. if (isDataTexture) {
  19295. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  19296. for (let j = 0; j < mipmaps.length; j++) {
  19297. const mipmap = mipmaps[j];
  19298. const mipmapImage = mipmap.image[i].image;
  19299. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  19300. }
  19301. } else {
  19302. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  19303. for (let j = 0; j < mipmaps.length; j++) {
  19304. const mipmap = mipmaps[j];
  19305. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  19306. }
  19307. }
  19308. }
  19309. textureProperties.__maxMipLevel = mipmaps.length;
  19310. }
  19311. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19312. // We assume images for cube map have the same size.
  19313. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  19314. }
  19315. textureProperties.__version = texture.version;
  19316. if (texture.onUpdate) texture.onUpdate(texture);
  19317. } // Render targets
  19318. // Setup storage for target texture and bind it to correct framebuffer
  19319. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  19320. const glFormat = utils.convert(texture.format);
  19321. const glType = utils.convert(texture.type);
  19322. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  19323. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  19324. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  19325. } else {
  19326. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  19327. }
  19328. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  19329. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  19330. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  19331. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19332. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  19333. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  19334. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  19335. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  19336. if (isMultisample) {
  19337. const depthTexture = renderTarget.depthTexture;
  19338. if (depthTexture && depthTexture.isDepthTexture) {
  19339. if (depthTexture.type === FloatType) {
  19340. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  19341. } else if (depthTexture.type === UnsignedIntType) {
  19342. glInternalFormat = _gl.DEPTH_COMPONENT24;
  19343. }
  19344. }
  19345. const samples = getRenderTargetSamples(renderTarget);
  19346. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19347. } else {
  19348. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  19349. }
  19350. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  19351. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  19352. if (isMultisample) {
  19353. const samples = getRenderTargetSamples(renderTarget);
  19354. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  19355. } else {
  19356. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  19357. }
  19358. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  19359. } else {
  19360. // Use the first texture for MRT so far
  19361. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  19362. const glFormat = utils.convert(texture.format);
  19363. const glType = utils.convert(texture.type);
  19364. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  19365. if (isMultisample) {
  19366. const samples = getRenderTargetSamples(renderTarget);
  19367. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19368. } else {
  19369. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  19370. }
  19371. }
  19372. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  19373. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  19374. function setupDepthTexture(framebuffer, renderTarget) {
  19375. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  19376. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  19377. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  19378. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  19379. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  19380. } // upload an empty depth texture with framebuffer size
  19381. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  19382. renderTarget.depthTexture.image.width = renderTarget.width;
  19383. renderTarget.depthTexture.image.height = renderTarget.height;
  19384. renderTarget.depthTexture.needsUpdate = true;
  19385. }
  19386. setTexture2D(renderTarget.depthTexture, 0);
  19387. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  19388. if (renderTarget.depthTexture.format === DepthFormat) {
  19389. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  19390. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  19391. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  19392. } else {
  19393. throw new Error('Unknown depthTexture format');
  19394. }
  19395. } // Setup GL resources for a non-texture depth buffer
  19396. function setupDepthRenderbuffer(renderTarget) {
  19397. const renderTargetProperties = properties.get(renderTarget);
  19398. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19399. if (renderTarget.depthTexture) {
  19400. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  19401. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  19402. } else {
  19403. if (isCube) {
  19404. renderTargetProperties.__webglDepthbuffer = [];
  19405. for (let i = 0; i < 6; i++) {
  19406. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  19407. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  19408. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  19409. }
  19410. } else {
  19411. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  19412. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  19413. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  19414. }
  19415. }
  19416. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  19417. } // Set up GL resources for the render target
  19418. function setupRenderTarget(renderTarget) {
  19419. const texture = renderTarget.texture;
  19420. const renderTargetProperties = properties.get(renderTarget);
  19421. const textureProperties = properties.get(texture);
  19422. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  19423. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  19424. textureProperties.__webglTexture = _gl.createTexture();
  19425. textureProperties.__version = texture.version;
  19426. info.memory.textures++;
  19427. }
  19428. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19429. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  19430. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  19431. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  19432. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  19433. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  19434. texture.format = RGBAFormat;
  19435. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  19436. } // Setup framebuffer
  19437. if (isCube) {
  19438. renderTargetProperties.__webglFramebuffer = [];
  19439. for (let i = 0; i < 6; i++) {
  19440. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  19441. }
  19442. } else {
  19443. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  19444. if (isMultipleRenderTargets) {
  19445. if (capabilities.drawBuffers) {
  19446. const textures = renderTarget.texture;
  19447. for (let i = 0, il = textures.length; i < il; i++) {
  19448. const attachmentProperties = properties.get(textures[i]);
  19449. if (attachmentProperties.__webglTexture === undefined) {
  19450. attachmentProperties.__webglTexture = _gl.createTexture();
  19451. info.memory.textures++;
  19452. }
  19453. }
  19454. } else {
  19455. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  19456. }
  19457. } else if (isMultisample) {
  19458. if (isWebGL2) {
  19459. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  19460. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  19461. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  19462. const glFormat = utils.convert(texture.format);
  19463. const glType = utils.convert(texture.type);
  19464. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  19465. const samples = getRenderTargetSamples(renderTarget);
  19466. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19467. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  19468. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  19469. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  19470. if (renderTarget.depthBuffer) {
  19471. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  19472. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  19473. }
  19474. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  19475. } else {
  19476. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19477. }
  19478. }
  19479. } // Setup color buffer
  19480. if (isCube) {
  19481. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  19482. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  19483. for (let i = 0; i < 6; i++) {
  19484. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  19485. }
  19486. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19487. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  19488. }
  19489. state.unbindTexture();
  19490. } else if (isMultipleRenderTargets) {
  19491. const textures = renderTarget.texture;
  19492. for (let i = 0, il = textures.length; i < il; i++) {
  19493. const attachment = textures[i];
  19494. const attachmentProperties = properties.get(attachment);
  19495. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  19496. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  19497. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  19498. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  19499. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  19500. }
  19501. }
  19502. state.unbindTexture();
  19503. } else {
  19504. let glTextureType = _gl.TEXTURE_2D;
  19505. if (isRenderTarget3D) {
  19506. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  19507. if (isWebGL2) {
  19508. const isTexture3D = texture.isDataTexture3D;
  19509. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  19510. } else {
  19511. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  19512. }
  19513. }
  19514. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  19515. setTextureParameters(glTextureType, texture, supportsMips);
  19516. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  19517. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19518. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  19519. }
  19520. state.unbindTexture();
  19521. } // Setup depth and stencil buffers
  19522. if (renderTarget.depthBuffer) {
  19523. setupDepthRenderbuffer(renderTarget);
  19524. }
  19525. }
  19526. function updateRenderTargetMipmap(renderTarget) {
  19527. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  19528. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  19529. for (let i = 0, il = textures.length; i < il; i++) {
  19530. const texture = textures[i];
  19531. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19532. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  19533. const webglTexture = properties.get(texture).__webglTexture;
  19534. state.bindTexture(target, webglTexture);
  19535. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  19536. state.unbindTexture();
  19537. }
  19538. }
  19539. }
  19540. function updateMultisampleRenderTarget(renderTarget) {
  19541. if (renderTarget.isWebGLMultisampleRenderTarget) {
  19542. if (isWebGL2) {
  19543. const width = renderTarget.width;
  19544. const height = renderTarget.height;
  19545. let mask = _gl.COLOR_BUFFER_BIT;
  19546. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  19547. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  19548. const renderTargetProperties = properties.get(renderTarget);
  19549. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  19550. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  19551. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  19552. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  19553. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  19554. } else {
  19555. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19556. }
  19557. }
  19558. }
  19559. function getRenderTargetSamples(renderTarget) {
  19560. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  19561. }
  19562. function updateVideoTexture(texture) {
  19563. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  19564. if (_videoTextures.get(texture) !== frame) {
  19565. _videoTextures.set(texture, frame);
  19566. texture.update();
  19567. }
  19568. } // backwards compatibility
  19569. let warnedTexture2D = false;
  19570. let warnedTextureCube = false;
  19571. function safeSetTexture2D(texture, slot) {
  19572. if (texture && texture.isWebGLRenderTarget) {
  19573. if (warnedTexture2D === false) {
  19574. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  19575. warnedTexture2D = true;
  19576. }
  19577. texture = texture.texture;
  19578. }
  19579. setTexture2D(texture, slot);
  19580. }
  19581. function safeSetTextureCube(texture, slot) {
  19582. if (texture && texture.isWebGLCubeRenderTarget) {
  19583. if (warnedTextureCube === false) {
  19584. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  19585. warnedTextureCube = true;
  19586. }
  19587. texture = texture.texture;
  19588. }
  19589. setTextureCube(texture, slot);
  19590. } //
  19591. this.allocateTextureUnit = allocateTextureUnit;
  19592. this.resetTextureUnits = resetTextureUnits;
  19593. this.setTexture2D = setTexture2D;
  19594. this.setTexture2DArray = setTexture2DArray;
  19595. this.setTexture3D = setTexture3D;
  19596. this.setTextureCube = setTextureCube;
  19597. this.setupRenderTarget = setupRenderTarget;
  19598. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19599. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19600. this.safeSetTexture2D = safeSetTexture2D;
  19601. this.safeSetTextureCube = safeSetTextureCube;
  19602. }
  19603. function WebGLUtils(gl, extensions, capabilities) {
  19604. const isWebGL2 = capabilities.isWebGL2;
  19605. function convert(p) {
  19606. let extension;
  19607. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  19608. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  19609. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  19610. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  19611. if (p === ByteType) return gl.BYTE;
  19612. if (p === ShortType) return gl.SHORT;
  19613. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  19614. if (p === IntType) return gl.INT;
  19615. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  19616. if (p === FloatType) return gl.FLOAT;
  19617. if (p === HalfFloatType) {
  19618. if (isWebGL2) return gl.HALF_FLOAT;
  19619. extension = extensions.get('OES_texture_half_float');
  19620. if (extension !== null) {
  19621. return extension.HALF_FLOAT_OES;
  19622. } else {
  19623. return null;
  19624. }
  19625. }
  19626. if (p === AlphaFormat) return gl.ALPHA;
  19627. if (p === RGBFormat) return gl.RGB;
  19628. if (p === RGBAFormat) return gl.RGBA;
  19629. if (p === LuminanceFormat) return gl.LUMINANCE;
  19630. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  19631. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  19632. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  19633. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  19634. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  19635. if (p === RGFormat) return gl.RG;
  19636. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  19637. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  19638. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  19639. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  19640. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  19641. if (extension !== null) {
  19642. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19643. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19644. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19645. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19646. } else {
  19647. return null;
  19648. }
  19649. }
  19650. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  19651. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  19652. if (extension !== null) {
  19653. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19654. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19655. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19656. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19657. } else {
  19658. return null;
  19659. }
  19660. }
  19661. if (p === RGB_ETC1_Format) {
  19662. extension = extensions.get('WEBGL_compressed_texture_etc1');
  19663. if (extension !== null) {
  19664. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19665. } else {
  19666. return null;
  19667. }
  19668. }
  19669. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  19670. extension = extensions.get('WEBGL_compressed_texture_etc');
  19671. if (extension !== null) {
  19672. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  19673. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  19674. }
  19675. }
  19676. 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) {
  19677. extension = extensions.get('WEBGL_compressed_texture_astc');
  19678. if (extension !== null) {
  19679. // TODO Complete?
  19680. return p;
  19681. } else {
  19682. return null;
  19683. }
  19684. }
  19685. if (p === RGBA_BPTC_Format) {
  19686. extension = extensions.get('EXT_texture_compression_bptc');
  19687. if (extension !== null) {
  19688. // TODO Complete?
  19689. return p;
  19690. } else {
  19691. return null;
  19692. }
  19693. }
  19694. if (p === UnsignedInt248Type) {
  19695. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  19696. extension = extensions.get('WEBGL_depth_texture');
  19697. if (extension !== null) {
  19698. return extension.UNSIGNED_INT_24_8_WEBGL;
  19699. } else {
  19700. return null;
  19701. }
  19702. }
  19703. }
  19704. return {
  19705. convert: convert
  19706. };
  19707. }
  19708. class Group extends Object3D {
  19709. constructor() {
  19710. super();
  19711. this.type = 'Group';
  19712. }
  19713. }
  19714. Group.prototype.isGroup = true;
  19715. class ArrayCamera extends PerspectiveCamera {
  19716. constructor(array = []) {
  19717. super();
  19718. this.cameras = array;
  19719. }
  19720. }
  19721. ArrayCamera.prototype.isArrayCamera = true;
  19722. /**
  19723. * @author jsantell / https://www.jsantell.com/
  19724. * @author mrdoob / http://mrdoob.com/
  19725. */
  19726. var cameraLPos = new Vector3();
  19727. var cameraRPos = new Vector3();
  19728. /**
  19729. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19730. * the cameras' projection and world matrices have already been set.
  19731. * And that near and far planes are identical for both cameras.
  19732. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19733. */
  19734. function setProjectionFromUnion(camera, cameraL, cameraR) {
  19735. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  19736. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  19737. var ipd = cameraLPos.distanceTo(cameraRPos);
  19738. var projL = cameraL.projectionMatrix.elements;
  19739. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  19740. // most likely identical top and bottom frustum extents.
  19741. // Use the left camera for these values.
  19742. var near = projL[14] / (projL[10] - 1);
  19743. var far = projL[14] / (projL[10] + 1);
  19744. var topFov = (projL[9] + 1) / projL[5];
  19745. var bottomFov = (projL[9] - 1) / projL[5];
  19746. var leftFov = (projL[8] - 1) / projL[0];
  19747. var rightFov = (projR[8] + 1) / projR[0];
  19748. var left = near * leftFov;
  19749. var right = near * rightFov; // Calculate the new camera's position offset from the
  19750. // left camera. xOffset should be roughly half `ipd`.
  19751. var zOffset = ipd / (-leftFov + rightFov);
  19752. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  19753. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  19754. camera.translateX(xOffset);
  19755. camera.translateZ(zOffset);
  19756. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  19757. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  19758. // the values so that the near plane's position does not change in world space,
  19759. // although must now be relative to the new union camera.
  19760. var near2 = near + zOffset;
  19761. var far2 = far + zOffset;
  19762. var left2 = left - xOffset;
  19763. var right2 = right + (ipd - xOffset);
  19764. var top2 = topFov * far / far2 * near2;
  19765. var bottom2 = bottomFov * far / far2 * near2;
  19766. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  19767. }
  19768. /**
  19769. * @author mrdoob / http://mrdoob.com/
  19770. */
  19771. function WebVRManager(renderer) {
  19772. var renderWidth, renderHeight;
  19773. var scope = this;
  19774. var device = null;
  19775. var frameData = null;
  19776. var poseTarget = null;
  19777. var controllers = [];
  19778. var standingMatrix = new Matrix4();
  19779. var standingMatrixInverse = new Matrix4();
  19780. var framebufferScaleFactor = 1.0;
  19781. var referenceSpaceType = 'local-floor';
  19782. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  19783. frameData = new window.VRFrameData();
  19784. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  19785. }
  19786. var matrixWorldInverse = new Matrix4();
  19787. var tempQuaternion = new Quaternion();
  19788. var tempPosition = new Vector3();
  19789. var cameraL = new PerspectiveCamera();
  19790. cameraL.viewport = new Vector4();
  19791. cameraL.layers.enable(1);
  19792. var cameraR = new PerspectiveCamera();
  19793. cameraR.viewport = new Vector4();
  19794. cameraR.layers.enable(2);
  19795. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  19796. cameraVR.layers.enable(1);
  19797. cameraVR.layers.enable(2);
  19798. var currentSize = new Vector2(),
  19799. currentPixelRatio;
  19800. function onVRDisplayPresentChange() {
  19801. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19802. if (isPresenting) {
  19803. var eyeParameters = device.getEyeParameters('left');
  19804. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19805. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19806. currentPixelRatio = renderer.getPixelRatio();
  19807. renderer.getSize(currentSize);
  19808. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  19809. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  19810. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  19811. animation.start();
  19812. scope.dispatchEvent({
  19813. type: 'sessionstart'
  19814. });
  19815. } else {
  19816. if (scope.enabled) {
  19817. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  19818. }
  19819. animation.stop();
  19820. scope.dispatchEvent({
  19821. type: 'sessionend'
  19822. });
  19823. }
  19824. } //
  19825. var triggers = [];
  19826. var grips = [];
  19827. function findGamepad(id) {
  19828. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19829. for (var i = 0, l = gamepads.length; i < l; i++) {
  19830. var gamepad = gamepads[i];
  19831. 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'))) {
  19832. var hand = gamepad.hand;
  19833. if (id === 0 && (hand === '' || hand === 'right')) return gamepad;
  19834. if (id === 1 && hand === 'left') return gamepad;
  19835. }
  19836. }
  19837. }
  19838. function updateControllers() {
  19839. for (var i = 0; i < controllers.length; i++) {
  19840. var controller = controllers[i];
  19841. var gamepad = findGamepad(i);
  19842. if (gamepad !== undefined && gamepad.pose !== undefined) {
  19843. if (gamepad.pose === null) return; // Pose
  19844. var pose = gamepad.pose;
  19845. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  19846. if (pose.position !== null) controller.position.fromArray(pose.position);
  19847. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  19848. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  19849. controller.matrix.premultiply(standingMatrix);
  19850. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  19851. controller.matrixWorldNeedsUpdate = true;
  19852. controller.visible = true; // Trigger
  19853. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19854. if (triggers[i] === undefined) triggers[i] = false;
  19855. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  19856. triggers[i] = gamepad.buttons[buttonId].pressed;
  19857. if (triggers[i] === true) {
  19858. controller.dispatchEvent({
  19859. type: 'selectstart'
  19860. });
  19861. } else {
  19862. controller.dispatchEvent({
  19863. type: 'selectend'
  19864. });
  19865. controller.dispatchEvent({
  19866. type: 'select'
  19867. });
  19868. }
  19869. } // Grip
  19870. buttonId = 2;
  19871. if (grips[i] === undefined) grips[i] = false; // Skip if the grip button doesn't exist on this controller
  19872. if (gamepad.buttons[buttonId] !== undefined) {
  19873. if (grips[i] !== gamepad.buttons[buttonId].pressed) {
  19874. grips[i] = gamepad.buttons[buttonId].pressed;
  19875. if (grips[i] === true) {
  19876. controller.dispatchEvent({
  19877. type: 'squeezestart'
  19878. });
  19879. } else {
  19880. controller.dispatchEvent({
  19881. type: 'squeezeend'
  19882. });
  19883. controller.dispatchEvent({
  19884. type: 'squeeze'
  19885. });
  19886. }
  19887. }
  19888. }
  19889. } else {
  19890. controller.visible = false;
  19891. }
  19892. }
  19893. }
  19894. function updateViewportFromBounds(viewport, bounds) {
  19895. if (bounds !== null && bounds.length === 4) {
  19896. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  19897. }
  19898. } //
  19899. this.enabled = false;
  19900. this.getController = function (id) {
  19901. var controller = controllers[id];
  19902. if (controller === undefined) {
  19903. controller = new Group();
  19904. controller.matrixAutoUpdate = false;
  19905. controller.visible = false;
  19906. controllers[id] = controller;
  19907. }
  19908. return controller;
  19909. };
  19910. this.getDevice = function () {
  19911. return device;
  19912. };
  19913. this.setDevice = function (value) {
  19914. if (value !== undefined) device = value;
  19915. animation.setContext(value);
  19916. };
  19917. this.setFramebufferScaleFactor = function (value) {
  19918. framebufferScaleFactor = value;
  19919. };
  19920. this.setReferenceSpaceType = function (value) {
  19921. referenceSpaceType = value;
  19922. };
  19923. this.setPoseTarget = function (object) {
  19924. if (object !== undefined) poseTarget = object;
  19925. };
  19926. this.getCamera = function (camera) {
  19927. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19928. device.depthNear = camera.near;
  19929. device.depthFar = camera.far;
  19930. device.getFrameData(frameData); //
  19931. if (referenceSpaceType === 'local-floor') {
  19932. var stageParameters = device.stageParameters;
  19933. if (stageParameters) {
  19934. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  19935. } else {
  19936. standingMatrix.makeTranslation(0, userHeight, 0);
  19937. }
  19938. }
  19939. var pose = frameData.pose;
  19940. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19941. poseObject.matrix.copy(standingMatrix);
  19942. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  19943. if (pose.orientation !== null) {
  19944. tempQuaternion.fromArray(pose.orientation);
  19945. poseObject.quaternion.multiply(tempQuaternion);
  19946. }
  19947. if (pose.position !== null) {
  19948. tempQuaternion.setFromRotationMatrix(standingMatrix);
  19949. tempPosition.fromArray(pose.position);
  19950. tempPosition.applyQuaternion(tempQuaternion);
  19951. poseObject.position.add(tempPosition);
  19952. }
  19953. poseObject.updateMatrixWorld();
  19954. var children = poseObject.children;
  19955. for (var i = 0, l = children.length; i < l; i++) {
  19956. children[i].updateMatrixWorld(true);
  19957. } //
  19958. cameraL.near = camera.near;
  19959. cameraR.near = camera.near;
  19960. cameraL.far = camera.far;
  19961. cameraR.far = camera.far;
  19962. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  19963. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  19964. standingMatrixInverse.getInverse(standingMatrix);
  19965. if (referenceSpaceType === 'local-floor') {
  19966. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  19967. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  19968. }
  19969. var parent = poseObject.parent;
  19970. if (parent !== null) {
  19971. matrixWorldInverse.getInverse(parent.matrixWorld);
  19972. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  19973. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  19974. } // envMap and Mirror needs camera.matrixWorld
  19975. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  19976. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  19977. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  19978. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  19979. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  19980. var layers = device.getLayers();
  19981. if (layers.length) {
  19982. var layer = layers[0];
  19983. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  19984. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  19985. }
  19986. updateControllers();
  19987. return cameraVR;
  19988. };
  19989. this.getStandingMatrix = function () {
  19990. return standingMatrix;
  19991. };
  19992. this.isPresenting = false; // Animation Loop
  19993. var animation = new WebGLAnimation();
  19994. this.setAnimationLoop = function (callback) {
  19995. animation.setAnimationLoop(callback);
  19996. if (this.isPresenting) animation.start();
  19997. };
  19998. this.submitFrame = function () {
  19999. if (this.isPresenting) device.submitFrame();
  20000. };
  20001. this.dispose = function () {
  20002. if (typeof window !== 'undefined') {
  20003. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  20004. }
  20005. }; // DEPRECATED
  20006. this.setFrameOfReferenceType = function () {
  20007. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  20008. };
  20009. this.addEventListener = function () {
  20010. /* Stub */
  20011. };
  20012. }
  20013. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  20014. const _moveEvent = {
  20015. type: 'move'
  20016. };
  20017. class WebXRController {
  20018. constructor() {
  20019. this._targetRay = null;
  20020. this._grip = null;
  20021. this._hand = null;
  20022. }
  20023. getHandSpace() {
  20024. if (this._hand === null) {
  20025. this._hand = new Group();
  20026. this._hand.matrixAutoUpdate = false;
  20027. this._hand.visible = false;
  20028. this._hand.joints = {};
  20029. this._hand.inputState = {
  20030. pinching: false
  20031. };
  20032. }
  20033. return this._hand;
  20034. }
  20035. getTargetRaySpace() {
  20036. if (this._targetRay === null) {
  20037. this._targetRay = new Group();
  20038. this._targetRay.matrixAutoUpdate = false;
  20039. this._targetRay.visible = false;
  20040. this._targetRay.hasLinearVelocity = false;
  20041. this._targetRay.linearVelocity = new Vector3();
  20042. this._targetRay.hasAngularVelocity = false;
  20043. this._targetRay.angularVelocity = new Vector3();
  20044. }
  20045. return this._targetRay;
  20046. }
  20047. getGripSpace() {
  20048. if (this._grip === null) {
  20049. this._grip = new Group();
  20050. this._grip.matrixAutoUpdate = false;
  20051. this._grip.visible = false;
  20052. this._grip.hasLinearVelocity = false;
  20053. this._grip.linearVelocity = new Vector3();
  20054. this._grip.hasAngularVelocity = false;
  20055. this._grip.angularVelocity = new Vector3();
  20056. }
  20057. return this._grip;
  20058. }
  20059. dispatchEvent(event) {
  20060. if (this._targetRay !== null) {
  20061. this._targetRay.dispatchEvent(event);
  20062. }
  20063. if (this._grip !== null) {
  20064. this._grip.dispatchEvent(event);
  20065. }
  20066. if (this._hand !== null) {
  20067. this._hand.dispatchEvent(event);
  20068. }
  20069. return this;
  20070. }
  20071. disconnect(inputSource) {
  20072. this.dispatchEvent({
  20073. type: 'disconnected',
  20074. data: inputSource
  20075. });
  20076. if (this._targetRay !== null) {
  20077. this._targetRay.visible = false;
  20078. }
  20079. if (this._grip !== null) {
  20080. this._grip.visible = false;
  20081. }
  20082. if (this._hand !== null) {
  20083. this._hand.visible = false;
  20084. }
  20085. return this;
  20086. }
  20087. update(inputSource, frame, referenceSpace) {
  20088. let inputPose = null;
  20089. let gripPose = null;
  20090. let handPose = null;
  20091. const targetRay = this._targetRay;
  20092. const grip = this._grip;
  20093. const hand = this._hand;
  20094. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  20095. if (targetRay !== null) {
  20096. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  20097. if (inputPose !== null) {
  20098. targetRay.matrix.fromArray(inputPose.transform.matrix);
  20099. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  20100. if (inputPose.linearVelocity) {
  20101. targetRay.hasLinearVelocity = true;
  20102. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  20103. } else {
  20104. targetRay.hasLinearVelocity = false;
  20105. }
  20106. if (inputPose.angularVelocity) {
  20107. targetRay.hasAngularVelocity = true;
  20108. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  20109. } else {
  20110. targetRay.hasAngularVelocity = false;
  20111. }
  20112. this.dispatchEvent(_moveEvent);
  20113. }
  20114. }
  20115. if (hand && inputSource.hand) {
  20116. handPose = true;
  20117. for (const inputjoint of inputSource.hand.values()) {
  20118. // Update the joints groups with the XRJoint poses
  20119. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  20120. if (hand.joints[inputjoint.jointName] === undefined) {
  20121. // The transform of this joint will be updated with the joint pose on each frame
  20122. const joint = new Group();
  20123. joint.matrixAutoUpdate = false;
  20124. joint.visible = false;
  20125. hand.joints[inputjoint.jointName] = joint; // ??
  20126. hand.add(joint);
  20127. }
  20128. const joint = hand.joints[inputjoint.jointName];
  20129. if (jointPose !== null) {
  20130. joint.matrix.fromArray(jointPose.transform.matrix);
  20131. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  20132. joint.jointRadius = jointPose.radius;
  20133. }
  20134. joint.visible = jointPose !== null;
  20135. } // Custom events
  20136. // Check pinchz
  20137. const indexTip = hand.joints['index-finger-tip'];
  20138. const thumbTip = hand.joints['thumb-tip'];
  20139. const distance = indexTip.position.distanceTo(thumbTip.position);
  20140. const distanceToPinch = 0.02;
  20141. const threshold = 0.005;
  20142. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  20143. hand.inputState.pinching = false;
  20144. this.dispatchEvent({
  20145. type: 'pinchend',
  20146. handedness: inputSource.handedness,
  20147. target: this
  20148. });
  20149. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  20150. hand.inputState.pinching = true;
  20151. this.dispatchEvent({
  20152. type: 'pinchstart',
  20153. handedness: inputSource.handedness,
  20154. target: this
  20155. });
  20156. }
  20157. } else {
  20158. if (grip !== null && inputSource.gripSpace) {
  20159. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  20160. if (gripPose !== null) {
  20161. grip.matrix.fromArray(gripPose.transform.matrix);
  20162. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  20163. if (gripPose.linearVelocity) {
  20164. grip.hasLinearVelocity = true;
  20165. grip.linearVelocity.copy(gripPose.linearVelocity);
  20166. } else {
  20167. grip.hasLinearVelocity = false;
  20168. }
  20169. if (gripPose.angularVelocity) {
  20170. grip.hasAngularVelocity = true;
  20171. grip.angularVelocity.copy(gripPose.angularVelocity);
  20172. } else {
  20173. grip.hasAngularVelocity = false;
  20174. }
  20175. }
  20176. }
  20177. }
  20178. }
  20179. if (targetRay !== null) {
  20180. targetRay.visible = inputPose !== null;
  20181. }
  20182. if (grip !== null) {
  20183. grip.visible = gripPose !== null;
  20184. }
  20185. if (hand !== null) {
  20186. hand.visible = handPose !== null;
  20187. }
  20188. return this;
  20189. }
  20190. }
  20191. class WebXRManager extends EventDispatcher {
  20192. constructor(renderer, gl) {
  20193. super();
  20194. const scope = this;
  20195. const state = renderer.state;
  20196. let session = null;
  20197. let framebufferScaleFactor = 1.0;
  20198. var poseTarget = null;
  20199. let referenceSpace = null;
  20200. let referenceSpaceType = 'local-floor';
  20201. let pose = null;
  20202. var layers = [];
  20203. let glBinding = null;
  20204. let glFramebuffer = null;
  20205. let glProjLayer = null;
  20206. let glBaseLayer = null;
  20207. let isMultisample = false;
  20208. let glMultisampledFramebuffer = null;
  20209. let glColorRenderbuffer = null;
  20210. let glDepthRenderbuffer = null;
  20211. let xrFrame = null;
  20212. let depthStyle = null;
  20213. let clearStyle = null;
  20214. const controllers = [];
  20215. const inputSourcesMap = new Map(); //
  20216. const cameraL = new PerspectiveCamera();
  20217. cameraL.layers.enable(1);
  20218. cameraL.viewport = new Vector4();
  20219. const cameraR = new PerspectiveCamera();
  20220. cameraR.layers.enable(2);
  20221. cameraR.viewport = new Vector4();
  20222. const cameras = [cameraL, cameraR];
  20223. const cameraVR = new ArrayCamera();
  20224. cameraVR.layers.enable(1);
  20225. cameraVR.layers.enable(2);
  20226. let _currentDepthNear = null;
  20227. let _currentDepthFar = null; //
  20228. this.cameraAutoUpdate = true;
  20229. this.layersEnabled = false;
  20230. this.enabled = false;
  20231. this.isPresenting = false;
  20232. this.getCameraPose = function () {
  20233. return pose;
  20234. };
  20235. this.getController = function (index) {
  20236. let controller = controllers[index];
  20237. if (controller === undefined) {
  20238. controller = new WebXRController();
  20239. controllers[index] = controller;
  20240. }
  20241. return controller.getTargetRaySpace();
  20242. };
  20243. this.getControllerGrip = function (index) {
  20244. let controller = controllers[index];
  20245. if (controller === undefined) {
  20246. controller = new WebXRController();
  20247. controllers[index] = controller;
  20248. }
  20249. return controller.getGripSpace();
  20250. };
  20251. this.getHand = function (index) {
  20252. let controller = controllers[index];
  20253. if (controller === undefined) {
  20254. controller = new WebXRController();
  20255. controllers[index] = controller;
  20256. }
  20257. return controller.getHandSpace();
  20258. }; //
  20259. function onSessionEvent(event) {
  20260. const controller = inputSourcesMap.get(event.inputSource);
  20261. if (controller) {
  20262. controller.dispatchEvent({
  20263. type: event.type,
  20264. data: event.inputSource
  20265. });
  20266. }
  20267. }
  20268. function onSessionEnd() {
  20269. inputSourcesMap.forEach(function (controller, inputSource) {
  20270. controller.disconnect(inputSource);
  20271. });
  20272. inputSourcesMap.clear();
  20273. _currentDepthNear = null;
  20274. _currentDepthFar = null; // restore framebuffer/rendering state
  20275. state.bindXRFramebuffer(null);
  20276. renderer.setRenderTarget(renderer.getRenderTarget());
  20277. if (glFramebuffer) gl.deleteFramebuffer(glFramebuffer);
  20278. if (glMultisampledFramebuffer) gl.deleteFramebuffer(glMultisampledFramebuffer);
  20279. if (glColorRenderbuffer) gl.deleteRenderbuffer(glColorRenderbuffer);
  20280. if (glDepthRenderbuffer) gl.deleteRenderbuffer(glDepthRenderbuffer);
  20281. glFramebuffer = null;
  20282. glMultisampledFramebuffer = null;
  20283. glColorRenderbuffer = null;
  20284. glDepthRenderbuffer = null;
  20285. glBaseLayer = null;
  20286. glProjLayer = null;
  20287. glBinding = null;
  20288. session = null; //
  20289. animation.stop();
  20290. scope.isPresenting = false;
  20291. scope.dispatchEvent({
  20292. type: 'sessionend'
  20293. });
  20294. }
  20295. this.setFramebufferScaleFactor = function (value) {
  20296. framebufferScaleFactor = value;
  20297. if (scope.isPresenting === true) {
  20298. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  20299. }
  20300. };
  20301. this.setReferenceSpaceType = function (value) {
  20302. referenceSpaceType = value;
  20303. if (scope.isPresenting === true) {
  20304. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  20305. }
  20306. };
  20307. this.getReferenceSpace = function () {
  20308. return referenceSpace;
  20309. };
  20310. this.getBaseLayer = function () {
  20311. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  20312. };
  20313. this.getBinding = function () {
  20314. return glBinding;
  20315. };
  20316. this.getFrame = function () {
  20317. return xrFrame;
  20318. };
  20319. this.getSession = function () {
  20320. return session;
  20321. };
  20322. this.setSession = async function (value) {
  20323. session = value;
  20324. if (session !== null) {
  20325. session.addEventListener('select', onSessionEvent);
  20326. session.addEventListener('selectstart', onSessionEvent);
  20327. session.addEventListener('selectend', onSessionEvent);
  20328. session.addEventListener('squeeze', onSessionEvent);
  20329. session.addEventListener('squeezestart', onSessionEvent);
  20330. session.addEventListener('squeezeend', onSessionEvent);
  20331. session.addEventListener('end', onSessionEnd);
  20332. session.addEventListener('inputsourceschange', onInputSourcesChange);
  20333. const attributes = gl.getContextAttributes();
  20334. if (attributes.xrCompatible !== true) {
  20335. await gl.makeXRCompatible();
  20336. }
  20337. if (session.renderState.layers === undefined) {
  20338. const layerInit = {
  20339. antialias: attributes.antialias,
  20340. alpha: attributes.alpha,
  20341. depth: attributes.depth,
  20342. stencil: attributes.stencil,
  20343. framebufferScaleFactor: framebufferScaleFactor
  20344. };
  20345. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  20346. session.updateRenderState({
  20347. baseLayer: glBaseLayer
  20348. });
  20349. } else if (gl instanceof WebGLRenderingContext) {
  20350. // Use old style webgl layer because we can't use MSAA
  20351. // WebGL2 support.
  20352. const layerInit = {
  20353. antialias: true,
  20354. alpha: attributes.alpha,
  20355. depth: attributes.depth,
  20356. stencil: attributes.stencil,
  20357. framebufferScaleFactor: framebufferScaleFactor
  20358. };
  20359. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  20360. session.updateRenderState({
  20361. layers: [glBaseLayer]
  20362. });
  20363. } else {
  20364. isMultisample = attributes.antialias;
  20365. let depthFormat = null;
  20366. if (attributes.depth) {
  20367. clearStyle = gl.DEPTH_BUFFER_BIT;
  20368. if (attributes.stencil) clearStyle |= gl.STENCIL_BUFFER_BIT;
  20369. depthStyle = attributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20370. depthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  20371. }
  20372. const projectionlayerInit = {
  20373. colorFormat: attributes.alpha ? gl.RGBA8 : gl.RGB8,
  20374. depthFormat: depthFormat,
  20375. scaleFactor: framebufferScaleFactor
  20376. };
  20377. glBinding = new XRWebGLBinding(session, gl);
  20378. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  20379. glFramebuffer = gl.createFramebuffer();
  20380. session.updateRenderState({
  20381. layers: [glProjLayer]
  20382. });
  20383. if (isMultisample) {
  20384. glMultisampledFramebuffer = gl.createFramebuffer();
  20385. glColorRenderbuffer = gl.createRenderbuffer();
  20386. gl.bindRenderbuffer(gl.RENDERBUFFER, glColorRenderbuffer);
  20387. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, glProjLayer.textureWidth, glProjLayer.textureHeight);
  20388. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  20389. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, glColorRenderbuffer);
  20390. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  20391. if (depthFormat !== null) {
  20392. glDepthRenderbuffer = gl.createRenderbuffer();
  20393. gl.bindRenderbuffer(gl.RENDERBUFFER, glDepthRenderbuffer);
  20394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight);
  20395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, glDepthRenderbuffer);
  20396. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  20397. }
  20398. state.bindFramebuffer(gl.FRAMEBUFFER, null);
  20399. }
  20400. }
  20401. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  20402. animation.setContext(session);
  20403. animation.start();
  20404. scope.isPresenting = true;
  20405. scope.dispatchEvent({
  20406. type: 'sessionstart'
  20407. });
  20408. }
  20409. };
  20410. this.addLayer = function (layer) {
  20411. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20412. return;
  20413. }
  20414. layers.push(layer);
  20415. this.updateLayers();
  20416. };
  20417. this.removeLayer = function (layer) {
  20418. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20419. return;
  20420. }
  20421. layers.splice(layers.indexOf(layer), 1);
  20422. this.updateLayers();
  20423. };
  20424. this.updateLayers = function () {
  20425. var layersCopy = layers.map(function (x) {
  20426. return x;
  20427. });
  20428. layersCopy.unshift(session.renderState.layers[0]);
  20429. session.updateRenderState({
  20430. layers: layersCopy
  20431. });
  20432. };
  20433. function onInputSourcesChange(event) {
  20434. const inputSources = session.inputSources; // Assign inputSources to available controllers
  20435. for (let i = 0; i < controllers.length; i++) {
  20436. inputSourcesMap.set(inputSources[i], controllers[i]);
  20437. } // Notify disconnected
  20438. for (let i = 0; i < event.removed.length; i++) {
  20439. const inputSource = event.removed[i];
  20440. const controller = inputSourcesMap.get(inputSource);
  20441. if (controller) {
  20442. controller.dispatchEvent({
  20443. type: 'disconnected',
  20444. data: inputSource
  20445. });
  20446. inputSourcesMap.delete(inputSource);
  20447. }
  20448. } // Notify connected
  20449. for (let i = 0; i < event.added.length; i++) {
  20450. const inputSource = event.added[i];
  20451. const controller = inputSourcesMap.get(inputSource);
  20452. if (controller) {
  20453. controller.dispatchEvent({
  20454. type: 'connected',
  20455. data: inputSource
  20456. });
  20457. }
  20458. }
  20459. } //
  20460. const cameraLPos = new Vector3();
  20461. const cameraRPos = new Vector3();
  20462. /**
  20463. * Assumes 2 cameras that are parallel and share an X-axis, and that
  20464. * the cameras' projection and world matrices have already been set.
  20465. * And that near and far planes are identical for both cameras.
  20466. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  20467. */
  20468. function setProjectionFromUnion(camera, cameraL, cameraR) {
  20469. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  20470. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  20471. const ipd = cameraLPos.distanceTo(cameraRPos);
  20472. const projL = cameraL.projectionMatrix.elements;
  20473. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  20474. // most likely identical top and bottom frustum extents.
  20475. // Use the left camera for these values.
  20476. const near = projL[14] / (projL[10] - 1);
  20477. const far = projL[14] / (projL[10] + 1);
  20478. const topFov = (projL[9] + 1) / projL[5];
  20479. const bottomFov = (projL[9] - 1) / projL[5];
  20480. const leftFov = (projL[8] - 1) / projL[0];
  20481. const rightFov = (projR[8] + 1) / projR[0];
  20482. const left = near * leftFov;
  20483. const right = near * rightFov; // Calculate the new camera's position offset from the
  20484. // left camera. xOffset should be roughly half `ipd`.
  20485. const zOffset = ipd / (-leftFov + rightFov);
  20486. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  20487. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  20488. camera.translateX(xOffset);
  20489. camera.translateZ(zOffset);
  20490. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  20491. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  20492. // the values so that the near plane's position does not change in world space,
  20493. // although must now be relative to the new union camera.
  20494. const near2 = near + zOffset;
  20495. const far2 = far + zOffset;
  20496. const left2 = left - xOffset;
  20497. const right2 = right + (ipd - xOffset);
  20498. const top2 = topFov * far / far2 * near2;
  20499. const bottom2 = bottomFov * far / far2 * near2;
  20500. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  20501. }
  20502. function updateCamera(camera, parent) {
  20503. if (parent === null) {
  20504. camera.matrixWorld.copy(camera.matrix);
  20505. } else {
  20506. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  20507. }
  20508. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  20509. }
  20510. this.setPoseTarget = function (object) {
  20511. if (object !== undefined) poseTarget = object;
  20512. };
  20513. this.updateCamera = function (camera) {
  20514. if (session === null) return;
  20515. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  20516. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  20517. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  20518. // Note that the new renderState won't apply until the next frame. See #18320
  20519. session.updateRenderState({
  20520. depthNear: cameraVR.near,
  20521. depthFar: cameraVR.far
  20522. });
  20523. _currentDepthNear = cameraVR.near;
  20524. _currentDepthFar = cameraVR.far;
  20525. }
  20526. const cameras = cameraVR.cameras;
  20527. var object = poseTarget || camera;
  20528. const parent = object.parent;
  20529. updateCamera(cameraVR, parent);
  20530. for (let i = 0; i < cameras.length; i++) {
  20531. updateCamera(cameras[i], parent);
  20532. }
  20533. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  20534. object.matrixWorld.copy(cameraVR.matrixWorld);
  20535. object.matrix.copy(cameraVR.matrix);
  20536. object.matrix.decompose(object.position, object.quaternion, object.scale);
  20537. const children = object.children;
  20538. for (let i = 0, l = children.length; i < l; i++) {
  20539. children[i].updateMatrixWorld(true);
  20540. } // update projection matrix for proper view frustum culling
  20541. if (cameras.length === 2) {
  20542. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  20543. } else {
  20544. // assume single camera setup (AR)
  20545. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  20546. }
  20547. };
  20548. this.getCamera = function () {
  20549. return cameraVR;
  20550. };
  20551. this.getFoveation = function () {
  20552. if (glProjLayer !== null) {
  20553. return glProjLayer.fixedFoveation;
  20554. }
  20555. if (glBaseLayer !== null) {
  20556. return glBaseLayer.fixedFoveation;
  20557. }
  20558. return undefined;
  20559. };
  20560. this.setFoveation = function (foveation) {
  20561. // 0 = no foveation = full resolution
  20562. // 1 = maximum foveation = the edges render at lower resolution
  20563. if (glProjLayer !== null) {
  20564. glProjLayer.fixedFoveation = foveation;
  20565. }
  20566. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  20567. glBaseLayer.fixedFoveation = foveation;
  20568. }
  20569. }; // Animation Loop
  20570. let onAnimationFrameCallback = null;
  20571. function onAnimationFrame(time, frame) {
  20572. pose = frame.getViewerPose(referenceSpace);
  20573. xrFrame = frame;
  20574. if (pose !== null) {
  20575. const views = pose.views;
  20576. if (glBaseLayer !== null) {
  20577. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  20578. }
  20579. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  20580. if (views.length !== cameraVR.cameras.length) {
  20581. cameraVR.cameras.length = 0;
  20582. cameraVRNeedsUpdate = true;
  20583. }
  20584. for (let i = 0; i < views.length; i++) {
  20585. const view = views[i];
  20586. let viewport = null;
  20587. if (glBaseLayer !== null) {
  20588. viewport = glBaseLayer.getViewport(view);
  20589. } else {
  20590. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  20591. state.bindXRFramebuffer(glFramebuffer);
  20592. if (glSubImage.depthStencilTexture !== undefined) {
  20593. gl.framebufferTexture2D(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  20594. }
  20595. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  20596. viewport = glSubImage.viewport;
  20597. }
  20598. const camera = cameras[i];
  20599. camera.matrix.fromArray(view.transform.matrix);
  20600. camera.projectionMatrix.fromArray(view.projectionMatrix);
  20601. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  20602. if (i === 0) {
  20603. cameraVR.matrix.copy(camera.matrix);
  20604. }
  20605. if (cameraVRNeedsUpdate === true) {
  20606. cameraVR.cameras.push(camera);
  20607. }
  20608. }
  20609. if (isMultisample) {
  20610. state.bindXRFramebuffer(glMultisampledFramebuffer);
  20611. if (clearStyle !== null) gl.clear(clearStyle);
  20612. }
  20613. } //
  20614. const inputSources = session.inputSources;
  20615. for (let i = 0; i < controllers.length; i++) {
  20616. const controller = controllers[i];
  20617. const inputSource = inputSources[i];
  20618. controller.update(inputSource, frame, referenceSpace);
  20619. }
  20620. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  20621. if (isMultisample) {
  20622. const width = glProjLayer.textureWidth;
  20623. const height = glProjLayer.textureHeight;
  20624. state.bindFramebuffer(gl.READ_FRAMEBUFFER, glMultisampledFramebuffer);
  20625. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glFramebuffer); // Invalidate the depth here to avoid flush of the depth data to main memory.
  20626. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [depthStyle]);
  20627. gl.invalidateFramebuffer(gl.DRAW_FRAMEBUFFER, [depthStyle]);
  20628. gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST); // Invalidate the MSAA buffer because it's not needed anymore.
  20629. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [gl.COLOR_ATTACHMENT0]);
  20630. state.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  20631. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  20632. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  20633. }
  20634. xrFrame = null;
  20635. }
  20636. const animation = new WebGLAnimation();
  20637. animation.setAnimationLoop(onAnimationFrame);
  20638. this.setAnimationLoop = function (callback) {
  20639. onAnimationFrameCallback = callback;
  20640. };
  20641. this.dispose = function () {};
  20642. }
  20643. }
  20644. function WebGLMaterials(properties) {
  20645. function refreshFogUniforms(uniforms, fog) {
  20646. uniforms.fogColor.value.copy(fog.color);
  20647. if (fog.isFog) {
  20648. uniforms.fogNear.value = fog.near;
  20649. uniforms.fogFar.value = fog.far;
  20650. } else if (fog.isFogExp2) {
  20651. uniforms.fogDensity.value = fog.density;
  20652. }
  20653. }
  20654. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  20655. if (material.isMeshBasicMaterial) {
  20656. refreshUniformsCommon(uniforms, material);
  20657. } else if (material.isMeshLambertMaterial) {
  20658. refreshUniformsCommon(uniforms, material);
  20659. refreshUniformsLambert(uniforms, material);
  20660. } else if (material.isMeshToonMaterial) {
  20661. refreshUniformsCommon(uniforms, material);
  20662. refreshUniformsToon(uniforms, material);
  20663. } else if (material.isMeshPhongMaterial) {
  20664. refreshUniformsCommon(uniforms, material);
  20665. refreshUniformsPhong(uniforms, material);
  20666. } else if (material.isMeshStandardMaterial) {
  20667. refreshUniformsCommon(uniforms, material);
  20668. if (material.isMeshPhysicalMaterial) {
  20669. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  20670. } else {
  20671. refreshUniformsStandard(uniforms, material);
  20672. }
  20673. } else if (material.isMeshMatcapMaterial) {
  20674. refreshUniformsCommon(uniforms, material);
  20675. refreshUniformsMatcap(uniforms, material);
  20676. } else if (material.isMeshDepthMaterial) {
  20677. refreshUniformsCommon(uniforms, material);
  20678. refreshUniformsDepth(uniforms, material);
  20679. } else if (material.isMeshDistanceMaterial) {
  20680. refreshUniformsCommon(uniforms, material);
  20681. refreshUniformsDistance(uniforms, material);
  20682. } else if (material.isMeshNormalMaterial) {
  20683. refreshUniformsCommon(uniforms, material);
  20684. refreshUniformsNormal(uniforms, material);
  20685. } else if (material.isLineBasicMaterial) {
  20686. refreshUniformsLine(uniforms, material);
  20687. if (material.isLineDashedMaterial) {
  20688. refreshUniformsDash(uniforms, material);
  20689. }
  20690. } else if (material.isPointsMaterial) {
  20691. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  20692. } else if (material.isSpriteMaterial) {
  20693. refreshUniformsSprites(uniforms, material);
  20694. } else if (material.isShadowMaterial) {
  20695. uniforms.color.value.copy(material.color);
  20696. uniforms.opacity.value = material.opacity;
  20697. } else if (material.isShaderMaterial) {
  20698. material.uniformsNeedUpdate = false; // #15581
  20699. }
  20700. }
  20701. function refreshUniformsCommon(uniforms, material) {
  20702. uniforms.opacity.value = material.opacity;
  20703. if (material.color) {
  20704. uniforms.diffuse.value.copy(material.color);
  20705. }
  20706. if (material.emissive) {
  20707. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  20708. }
  20709. if (material.map) {
  20710. uniforms.map.value = material.map;
  20711. }
  20712. if (material.alphaMap) {
  20713. uniforms.alphaMap.value = material.alphaMap;
  20714. }
  20715. if (material.specularMap) {
  20716. uniforms.specularMap.value = material.specularMap;
  20717. }
  20718. if (material.alphaTest > 0) {
  20719. uniforms.alphaTest.value = material.alphaTest;
  20720. }
  20721. const envMap = properties.get(material).envMap;
  20722. if (envMap) {
  20723. uniforms.envMap.value = envMap;
  20724. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  20725. uniforms.reflectivity.value = material.reflectivity;
  20726. uniforms.ior.value = material.ior;
  20727. uniforms.refractionRatio.value = material.refractionRatio;
  20728. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  20729. if (maxMipLevel !== undefined) {
  20730. uniforms.maxMipLevel.value = maxMipLevel;
  20731. }
  20732. }
  20733. if (material.lightMap) {
  20734. uniforms.lightMap.value = material.lightMap;
  20735. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  20736. }
  20737. if (material.aoMap) {
  20738. uniforms.aoMap.value = material.aoMap;
  20739. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  20740. } // uv repeat and offset setting priorities
  20741. // 1. color map
  20742. // 2. specular map
  20743. // 3. displacementMap map
  20744. // 4. normal map
  20745. // 5. bump map
  20746. // 6. roughnessMap map
  20747. // 7. metalnessMap map
  20748. // 8. alphaMap map
  20749. // 9. emissiveMap map
  20750. // 10. clearcoat map
  20751. // 11. clearcoat normal map
  20752. // 12. clearcoat roughnessMap map
  20753. // 13. specular intensity map
  20754. // 14. specular tint map
  20755. // 15. transmission map
  20756. // 16. thickness map
  20757. let uvScaleMap;
  20758. if (material.map) {
  20759. uvScaleMap = material.map;
  20760. } else if (material.specularMap) {
  20761. uvScaleMap = material.specularMap;
  20762. } else if (material.displacementMap) {
  20763. uvScaleMap = material.displacementMap;
  20764. } else if (material.normalMap) {
  20765. uvScaleMap = material.normalMap;
  20766. } else if (material.bumpMap) {
  20767. uvScaleMap = material.bumpMap;
  20768. } else if (material.roughnessMap) {
  20769. uvScaleMap = material.roughnessMap;
  20770. } else if (material.metalnessMap) {
  20771. uvScaleMap = material.metalnessMap;
  20772. } else if (material.alphaMap) {
  20773. uvScaleMap = material.alphaMap;
  20774. } else if (material.emissiveMap) {
  20775. uvScaleMap = material.emissiveMap;
  20776. } else if (material.clearcoatMap) {
  20777. uvScaleMap = material.clearcoatMap;
  20778. } else if (material.clearcoatNormalMap) {
  20779. uvScaleMap = material.clearcoatNormalMap;
  20780. } else if (material.clearcoatRoughnessMap) {
  20781. uvScaleMap = material.clearcoatRoughnessMap;
  20782. } else if (material.specularIntensityMap) {
  20783. uvScaleMap = material.specularIntensityMap;
  20784. } else if (material.specularTintMap) {
  20785. uvScaleMap = material.specularTintMap;
  20786. } else if (material.transmissionMap) {
  20787. uvScaleMap = material.transmissionMap;
  20788. } else if (material.thicknessMap) {
  20789. uvScaleMap = material.thicknessMap;
  20790. }
  20791. if (uvScaleMap !== undefined) {
  20792. // backwards compatibility
  20793. if (uvScaleMap.isWebGLRenderTarget) {
  20794. uvScaleMap = uvScaleMap.texture;
  20795. }
  20796. if (uvScaleMap.matrixAutoUpdate === true) {
  20797. uvScaleMap.updateMatrix();
  20798. }
  20799. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20800. } // uv repeat and offset setting priorities for uv2
  20801. // 1. ao map
  20802. // 2. light map
  20803. let uv2ScaleMap;
  20804. if (material.aoMap) {
  20805. uv2ScaleMap = material.aoMap;
  20806. } else if (material.lightMap) {
  20807. uv2ScaleMap = material.lightMap;
  20808. }
  20809. if (uv2ScaleMap !== undefined) {
  20810. // backwards compatibility
  20811. if (uv2ScaleMap.isWebGLRenderTarget) {
  20812. uv2ScaleMap = uv2ScaleMap.texture;
  20813. }
  20814. if (uv2ScaleMap.matrixAutoUpdate === true) {
  20815. uv2ScaleMap.updateMatrix();
  20816. }
  20817. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  20818. }
  20819. }
  20820. function refreshUniformsLine(uniforms, material) {
  20821. uniforms.diffuse.value.copy(material.color);
  20822. uniforms.opacity.value = material.opacity;
  20823. }
  20824. function refreshUniformsDash(uniforms, material) {
  20825. uniforms.dashSize.value = material.dashSize;
  20826. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20827. uniforms.scale.value = material.scale;
  20828. }
  20829. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  20830. uniforms.diffuse.value.copy(material.color);
  20831. uniforms.opacity.value = material.opacity;
  20832. uniforms.size.value = material.size * pixelRatio;
  20833. uniforms.scale.value = height * 0.5;
  20834. if (material.map) {
  20835. uniforms.map.value = material.map;
  20836. }
  20837. if (material.alphaMap) {
  20838. uniforms.alphaMap.value = material.alphaMap;
  20839. }
  20840. if (material.alphaTest > 0) {
  20841. uniforms.alphaTest.value = material.alphaTest;
  20842. } // uv repeat and offset setting priorities
  20843. // 1. color map
  20844. // 2. alpha map
  20845. let uvScaleMap;
  20846. if (material.map) {
  20847. uvScaleMap = material.map;
  20848. } else if (material.alphaMap) {
  20849. uvScaleMap = material.alphaMap;
  20850. }
  20851. if (uvScaleMap !== undefined) {
  20852. if (uvScaleMap.matrixAutoUpdate === true) {
  20853. uvScaleMap.updateMatrix();
  20854. }
  20855. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20856. }
  20857. }
  20858. function refreshUniformsSprites(uniforms, material) {
  20859. uniforms.diffuse.value.copy(material.color);
  20860. uniforms.opacity.value = material.opacity;
  20861. uniforms.rotation.value = material.rotation;
  20862. if (material.map) {
  20863. uniforms.map.value = material.map;
  20864. }
  20865. if (material.alphaMap) {
  20866. uniforms.alphaMap.value = material.alphaMap;
  20867. }
  20868. if (material.alphaTest > 0) {
  20869. uniforms.alphaTest.value = material.alphaTest;
  20870. } // uv repeat and offset setting priorities
  20871. // 1. color map
  20872. // 2. alpha map
  20873. let uvScaleMap;
  20874. if (material.map) {
  20875. uvScaleMap = material.map;
  20876. } else if (material.alphaMap) {
  20877. uvScaleMap = material.alphaMap;
  20878. }
  20879. if (uvScaleMap !== undefined) {
  20880. if (uvScaleMap.matrixAutoUpdate === true) {
  20881. uvScaleMap.updateMatrix();
  20882. }
  20883. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20884. }
  20885. }
  20886. function refreshUniformsLambert(uniforms, material) {
  20887. if (material.emissiveMap) {
  20888. uniforms.emissiveMap.value = material.emissiveMap;
  20889. }
  20890. }
  20891. function refreshUniformsPhong(uniforms, material) {
  20892. uniforms.specular.value.copy(material.specular);
  20893. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  20894. if (material.emissiveMap) {
  20895. uniforms.emissiveMap.value = material.emissiveMap;
  20896. }
  20897. if (material.bumpMap) {
  20898. uniforms.bumpMap.value = material.bumpMap;
  20899. uniforms.bumpScale.value = material.bumpScale;
  20900. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20901. }
  20902. if (material.normalMap) {
  20903. uniforms.normalMap.value = material.normalMap;
  20904. uniforms.normalScale.value.copy(material.normalScale);
  20905. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20906. }
  20907. if (material.displacementMap) {
  20908. uniforms.displacementMap.value = material.displacementMap;
  20909. uniforms.displacementScale.value = material.displacementScale;
  20910. uniforms.displacementBias.value = material.displacementBias;
  20911. }
  20912. }
  20913. function refreshUniformsToon(uniforms, material) {
  20914. if (material.gradientMap) {
  20915. uniforms.gradientMap.value = material.gradientMap;
  20916. }
  20917. if (material.emissiveMap) {
  20918. uniforms.emissiveMap.value = material.emissiveMap;
  20919. }
  20920. if (material.bumpMap) {
  20921. uniforms.bumpMap.value = material.bumpMap;
  20922. uniforms.bumpScale.value = material.bumpScale;
  20923. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20924. }
  20925. if (material.normalMap) {
  20926. uniforms.normalMap.value = material.normalMap;
  20927. uniforms.normalScale.value.copy(material.normalScale);
  20928. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20929. }
  20930. if (material.displacementMap) {
  20931. uniforms.displacementMap.value = material.displacementMap;
  20932. uniforms.displacementScale.value = material.displacementScale;
  20933. uniforms.displacementBias.value = material.displacementBias;
  20934. }
  20935. }
  20936. function refreshUniformsStandard(uniforms, material) {
  20937. uniforms.roughness.value = material.roughness;
  20938. uniforms.metalness.value = material.metalness;
  20939. if (material.roughnessMap) {
  20940. uniforms.roughnessMap.value = material.roughnessMap;
  20941. }
  20942. if (material.metalnessMap) {
  20943. uniforms.metalnessMap.value = material.metalnessMap;
  20944. }
  20945. if (material.emissiveMap) {
  20946. uniforms.emissiveMap.value = material.emissiveMap;
  20947. }
  20948. if (material.bumpMap) {
  20949. uniforms.bumpMap.value = material.bumpMap;
  20950. uniforms.bumpScale.value = material.bumpScale;
  20951. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20952. }
  20953. if (material.normalMap) {
  20954. uniforms.normalMap.value = material.normalMap;
  20955. uniforms.normalScale.value.copy(material.normalScale);
  20956. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20957. }
  20958. if (material.displacementMap) {
  20959. uniforms.displacementMap.value = material.displacementMap;
  20960. uniforms.displacementScale.value = material.displacementScale;
  20961. uniforms.displacementBias.value = material.displacementBias;
  20962. }
  20963. const envMap = properties.get(material).envMap;
  20964. if (envMap) {
  20965. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20966. uniforms.envMapIntensity.value = material.envMapIntensity;
  20967. }
  20968. }
  20969. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  20970. refreshUniformsStandard(uniforms, material);
  20971. uniforms.ior.value = material.ior; // also part of uniforms common
  20972. if (material.sheen > 0) {
  20973. uniforms.sheenTint.value.copy(material.sheenTint).multiplyScalar(material.sheen);
  20974. uniforms.sheenRoughness.value = material.sheenRoughness;
  20975. }
  20976. if (material.clearcoat > 0) {
  20977. uniforms.clearcoat.value = material.clearcoat;
  20978. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20979. if (material.clearcoatMap) {
  20980. uniforms.clearcoatMap.value = material.clearcoatMap;
  20981. }
  20982. if (material.clearcoatRoughnessMap) {
  20983. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  20984. }
  20985. if (material.clearcoatNormalMap) {
  20986. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  20987. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20988. if (material.side === BackSide) {
  20989. uniforms.clearcoatNormalScale.value.negate();
  20990. }
  20991. }
  20992. }
  20993. if (material.transmission > 0) {
  20994. uniforms.transmission.value = material.transmission;
  20995. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  20996. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  20997. if (material.transmissionMap) {
  20998. uniforms.transmissionMap.value = material.transmissionMap;
  20999. }
  21000. uniforms.thickness.value = material.thickness;
  21001. if (material.thicknessMap) {
  21002. uniforms.thicknessMap.value = material.thicknessMap;
  21003. }
  21004. uniforms.attenuationDistance.value = material.attenuationDistance;
  21005. uniforms.attenuationTint.value.copy(material.attenuationTint);
  21006. }
  21007. uniforms.specularIntensity.value = material.specularIntensity;
  21008. uniforms.specularTint.value.copy(material.specularTint);
  21009. if (material.specularIntensityMap) {
  21010. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  21011. }
  21012. if (material.specularTintMap) {
  21013. uniforms.specularTintMap.value = material.specularTintMap;
  21014. }
  21015. }
  21016. function refreshUniformsMatcap(uniforms, material) {
  21017. if (material.matcap) {
  21018. uniforms.matcap.value = material.matcap;
  21019. }
  21020. if (material.bumpMap) {
  21021. uniforms.bumpMap.value = material.bumpMap;
  21022. uniforms.bumpScale.value = material.bumpScale;
  21023. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  21024. }
  21025. if (material.normalMap) {
  21026. uniforms.normalMap.value = material.normalMap;
  21027. uniforms.normalScale.value.copy(material.normalScale);
  21028. if (material.side === BackSide) uniforms.normalScale.value.negate();
  21029. }
  21030. if (material.displacementMap) {
  21031. uniforms.displacementMap.value = material.displacementMap;
  21032. uniforms.displacementScale.value = material.displacementScale;
  21033. uniforms.displacementBias.value = material.displacementBias;
  21034. }
  21035. }
  21036. function refreshUniformsDepth(uniforms, material) {
  21037. if (material.displacementMap) {
  21038. uniforms.displacementMap.value = material.displacementMap;
  21039. uniforms.displacementScale.value = material.displacementScale;
  21040. uniforms.displacementBias.value = material.displacementBias;
  21041. }
  21042. }
  21043. function refreshUniformsDistance(uniforms, material) {
  21044. if (material.displacementMap) {
  21045. uniforms.displacementMap.value = material.displacementMap;
  21046. uniforms.displacementScale.value = material.displacementScale;
  21047. uniforms.displacementBias.value = material.displacementBias;
  21048. }
  21049. uniforms.referencePosition.value.copy(material.referencePosition);
  21050. uniforms.nearDistance.value = material.nearDistance;
  21051. uniforms.farDistance.value = material.farDistance;
  21052. }
  21053. function refreshUniformsNormal(uniforms, material) {
  21054. if (material.bumpMap) {
  21055. uniforms.bumpMap.value = material.bumpMap;
  21056. uniforms.bumpScale.value = material.bumpScale;
  21057. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  21058. }
  21059. if (material.normalMap) {
  21060. uniforms.normalMap.value = material.normalMap;
  21061. uniforms.normalScale.value.copy(material.normalScale);
  21062. if (material.side === BackSide) uniforms.normalScale.value.negate();
  21063. }
  21064. if (material.displacementMap) {
  21065. uniforms.displacementMap.value = material.displacementMap;
  21066. uniforms.displacementScale.value = material.displacementScale;
  21067. uniforms.displacementBias.value = material.displacementBias;
  21068. }
  21069. }
  21070. return {
  21071. refreshFogUniforms: refreshFogUniforms,
  21072. refreshMaterialUniforms: refreshMaterialUniforms
  21073. };
  21074. }
  21075. function createCanvasElement() {
  21076. const canvas = createElementNS('canvas');
  21077. canvas.style.display = 'block';
  21078. return canvas;
  21079. }
  21080. function WebGLRenderer(parameters = {}) {
  21081. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  21082. _context = parameters.context !== undefined ? parameters.context : null,
  21083. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  21084. _depth = parameters.depth !== undefined ? parameters.depth : true,
  21085. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  21086. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  21087. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  21088. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  21089. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  21090. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  21091. let currentRenderList = null;
  21092. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  21093. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  21094. const renderListStack = [];
  21095. const renderStateStack = []; // public properties
  21096. this.domElement = _canvas; // Debug configuration container
  21097. this.debug = {
  21098. /**
  21099. * Enables error checking and reporting when shader programs are being compiled
  21100. * @type {boolean}
  21101. */
  21102. checkShaderErrors: true
  21103. }; // clearing
  21104. this.autoClear = true;
  21105. this.autoClearColor = true;
  21106. this.autoClearDepth = true;
  21107. this.autoClearStencil = true; // scene graph
  21108. this.sortObjects = true; // user-defined clipping
  21109. this.clippingPlanes = [];
  21110. this.localClippingEnabled = false; // physically based shading
  21111. this.gammaFactor = 2.0; // for backwards compatibility
  21112. this.outputEncoding = LinearEncoding; // physical lights
  21113. this.physicallyCorrectLights = false; // tone mapping
  21114. this.toneMapping = NoToneMapping;
  21115. this.toneMappingExposure = 1.0; // internal properties
  21116. const _this = this;
  21117. let _isContextLost = false; // internal state cache
  21118. let _currentActiveCubeFace = 0;
  21119. let _currentActiveMipmapLevel = 0;
  21120. let _currentRenderTarget = null;
  21121. let _currentMaterialId = -1;
  21122. let _currentCamera = null;
  21123. const _currentViewport = new Vector4();
  21124. const _currentScissor = new Vector4();
  21125. let _currentScissorTest = null; //
  21126. let _width = _canvas.width;
  21127. let _height = _canvas.height;
  21128. let _pixelRatio = 1;
  21129. let _opaqueSort = null;
  21130. let _transparentSort = null;
  21131. const _viewport = new Vector4(0, 0, _width, _height);
  21132. const _scissor = new Vector4(0, 0, _width, _height);
  21133. let _scissorTest = false; //
  21134. const _currentDrawBuffers = []; // frustum
  21135. const _frustum = new Frustum(); // clipping
  21136. let _clippingEnabled = false;
  21137. let _localClippingEnabled = false; // transmission
  21138. let _transmissionRenderTarget = null; // camera matrices cache
  21139. const _projScreenMatrix = new Matrix4();
  21140. const _vector3 = new Vector3();
  21141. const _emptyScene = {
  21142. background: null,
  21143. fog: null,
  21144. environment: null,
  21145. overrideMaterial: null,
  21146. isScene: true
  21147. };
  21148. function getTargetPixelRatio() {
  21149. return _currentRenderTarget === null ? _pixelRatio : 1;
  21150. } // initialize
  21151. let _gl = _context;
  21152. function getContext(contextNames, contextAttributes) {
  21153. for (let i = 0; i < contextNames.length; i++) {
  21154. const contextName = contextNames[i];
  21155. const context = _canvas.getContext(contextName, contextAttributes);
  21156. if (context !== null) return context;
  21157. }
  21158. return null;
  21159. }
  21160. try {
  21161. const contextAttributes = {
  21162. alpha: _alpha,
  21163. depth: _depth,
  21164. stencil: _stencil,
  21165. antialias: _antialias,
  21166. premultipliedAlpha: _premultipliedAlpha,
  21167. preserveDrawingBuffer: _preserveDrawingBuffer,
  21168. powerPreference: _powerPreference,
  21169. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  21170. }; // event listeners must be registered before WebGL context is created, see #12753
  21171. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  21172. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  21173. if (_gl === null) {
  21174. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  21175. if (_this.isWebGL1Renderer === true) {
  21176. contextNames.shift();
  21177. }
  21178. _gl = getContext(contextNames, contextAttributes);
  21179. if (_gl === null) {
  21180. if (getContext(contextNames)) {
  21181. throw new Error('Error creating WebGL context with your selected attributes.');
  21182. } else {
  21183. throw new Error('Error creating WebGL context.');
  21184. }
  21185. }
  21186. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  21187. if (_gl.getShaderPrecisionFormat === undefined) {
  21188. _gl.getShaderPrecisionFormat = function () {
  21189. return {
  21190. 'rangeMin': 1,
  21191. 'rangeMax': 1,
  21192. 'precision': 1
  21193. };
  21194. };
  21195. }
  21196. } catch (error) {
  21197. console.error('THREE.WebGLRenderer: ' + error.message);
  21198. throw error;
  21199. }
  21200. let extensions, capabilities, state, info;
  21201. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  21202. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  21203. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  21204. let utils, bindingStates;
  21205. function initGLContext() {
  21206. extensions = new WebGLExtensions(_gl);
  21207. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  21208. extensions.init(capabilities);
  21209. utils = new WebGLUtils(_gl, extensions, capabilities);
  21210. state = new WebGLState(_gl, extensions, capabilities);
  21211. _currentDrawBuffers[0] = _gl.BACK;
  21212. info = new WebGLInfo(_gl);
  21213. properties = new WebGLProperties();
  21214. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  21215. cubemaps = new WebGLCubeMaps(_this);
  21216. cubeuvmaps = new WebGLCubeUVMaps(_this);
  21217. attributes = new WebGLAttributes(_gl, capabilities);
  21218. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  21219. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  21220. objects = new WebGLObjects(_gl, geometries, attributes, info);
  21221. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  21222. clipping = new WebGLClipping(properties);
  21223. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  21224. materials = new WebGLMaterials(properties);
  21225. renderLists = new WebGLRenderLists(properties);
  21226. renderStates = new WebGLRenderStates(extensions, capabilities);
  21227. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  21228. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  21229. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  21230. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  21231. info.programs = programCache.programs;
  21232. _this.capabilities = capabilities;
  21233. _this.extensions = extensions;
  21234. _this.properties = properties;
  21235. _this.renderLists = renderLists;
  21236. _this.shadowMap = shadowMap;
  21237. _this.state = state;
  21238. _this.info = info;
  21239. }
  21240. initGLContext();
  21241. const xr = typeof navigator !== 'undefined' && 'xr' in navigator ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  21242. this.xr = xr; // API
  21243. this.getContext = function () {
  21244. return _gl;
  21245. };
  21246. this.getContextAttributes = function () {
  21247. return _gl.getContextAttributes();
  21248. };
  21249. this.forceContextLoss = function () {
  21250. const extension = extensions.get('WEBGL_lose_context');
  21251. if (extension) extension.loseContext();
  21252. };
  21253. this.forceContextRestore = function () {
  21254. const extension = extensions.get('WEBGL_lose_context');
  21255. if (extension) extension.restoreContext();
  21256. };
  21257. this.getPixelRatio = function () {
  21258. return _pixelRatio;
  21259. };
  21260. this.setPixelRatio = function (value) {
  21261. if (value === undefined) return;
  21262. _pixelRatio = value;
  21263. this.setSize(_width, _height, false);
  21264. };
  21265. this.getSize = function (target) {
  21266. return target.set(_width, _height);
  21267. };
  21268. this.setSize = function (width, height, updateStyle) {
  21269. if (xr.isPresenting) {
  21270. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  21271. return;
  21272. }
  21273. _width = width;
  21274. _height = height;
  21275. _canvas.width = Math.floor(width * _pixelRatio);
  21276. _canvas.height = Math.floor(height * _pixelRatio);
  21277. if (updateStyle !== false) {
  21278. _canvas.style.width = width + 'px';
  21279. _canvas.style.height = height + 'px';
  21280. }
  21281. this.setViewport(0, 0, width, height);
  21282. };
  21283. this.getDrawingBufferSize = function (target) {
  21284. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  21285. };
  21286. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  21287. _width = width;
  21288. _height = height;
  21289. _pixelRatio = pixelRatio;
  21290. _canvas.width = Math.floor(width * pixelRatio);
  21291. _canvas.height = Math.floor(height * pixelRatio);
  21292. this.setViewport(0, 0, width, height);
  21293. };
  21294. this.getCurrentViewport = function (target) {
  21295. return target.copy(_currentViewport);
  21296. };
  21297. this.getViewport = function (target) {
  21298. return target.copy(_viewport);
  21299. };
  21300. this.setViewport = function (x, y, width, height) {
  21301. if (x.isVector4) {
  21302. _viewport.set(x.x, x.y, x.z, x.w);
  21303. } else {
  21304. _viewport.set(x, y, width, height);
  21305. }
  21306. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  21307. };
  21308. this.getScissor = function (target) {
  21309. return target.copy(_scissor);
  21310. };
  21311. this.setScissor = function (x, y, width, height) {
  21312. if (x.isVector4) {
  21313. _scissor.set(x.x, x.y, x.z, x.w);
  21314. } else {
  21315. _scissor.set(x, y, width, height);
  21316. }
  21317. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  21318. };
  21319. this.getScissorTest = function () {
  21320. return _scissorTest;
  21321. };
  21322. this.setScissorTest = function (boolean) {
  21323. state.setScissorTest(_scissorTest = boolean);
  21324. };
  21325. this.setOpaqueSort = function (method) {
  21326. _opaqueSort = method;
  21327. };
  21328. this.setTransparentSort = function (method) {
  21329. _transparentSort = method;
  21330. }; // Clearing
  21331. this.getClearColor = function (target) {
  21332. return target.copy(background.getClearColor());
  21333. };
  21334. this.setClearColor = function () {
  21335. background.setClearColor.apply(background, arguments);
  21336. };
  21337. this.getClearAlpha = function () {
  21338. return background.getClearAlpha();
  21339. };
  21340. this.setClearAlpha = function () {
  21341. background.setClearAlpha.apply(background, arguments);
  21342. };
  21343. this.clear = function (color, depth, stencil) {
  21344. let bits = 0;
  21345. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  21346. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  21347. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  21348. _gl.clear(bits);
  21349. };
  21350. this.clearColor = function () {
  21351. this.clear(true, false, false);
  21352. };
  21353. this.clearDepth = function () {
  21354. this.clear(false, true, false);
  21355. };
  21356. this.clearStencil = function () {
  21357. this.clear(false, false, true);
  21358. }; //
  21359. this.dispose = function () {
  21360. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  21361. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  21362. renderLists.dispose();
  21363. renderStates.dispose();
  21364. properties.dispose();
  21365. cubemaps.dispose();
  21366. cubeuvmaps.dispose();
  21367. objects.dispose();
  21368. bindingStates.dispose();
  21369. xr.dispose();
  21370. xr.removeEventListener('sessionstart', onXRSessionStart);
  21371. xr.removeEventListener('sessionend', onXRSessionEnd);
  21372. if (_transmissionRenderTarget) {
  21373. _transmissionRenderTarget.dispose();
  21374. _transmissionRenderTarget = null;
  21375. }
  21376. animation.stop();
  21377. }; // Events
  21378. function onContextLost(event) {
  21379. event.preventDefault();
  21380. console.log('THREE.WebGLRenderer: Context Lost.');
  21381. _isContextLost = true;
  21382. }
  21383. function onContextRestore() {
  21384. console.log('THREE.WebGLRenderer: Context Restored.');
  21385. _isContextLost = false;
  21386. const infoAutoReset = info.autoReset;
  21387. const shadowMapEnabled = shadowMap.enabled;
  21388. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  21389. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  21390. const shadowMapType = shadowMap.type;
  21391. initGLContext();
  21392. info.autoReset = infoAutoReset;
  21393. shadowMap.enabled = shadowMapEnabled;
  21394. shadowMap.autoUpdate = shadowMapAutoUpdate;
  21395. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  21396. shadowMap.type = shadowMapType;
  21397. }
  21398. function onMaterialDispose(event) {
  21399. const material = event.target;
  21400. material.removeEventListener('dispose', onMaterialDispose);
  21401. deallocateMaterial(material);
  21402. } // Buffer deallocation
  21403. function deallocateMaterial(material) {
  21404. releaseMaterialProgramReferences(material);
  21405. properties.remove(material);
  21406. }
  21407. function releaseMaterialProgramReferences(material) {
  21408. const programs = properties.get(material).programs;
  21409. if (programs !== undefined) {
  21410. programs.forEach(function (program) {
  21411. programCache.releaseProgram(program);
  21412. });
  21413. }
  21414. } // Buffer rendering
  21415. function renderObjectImmediate(object, program) {
  21416. object.render(function (object) {
  21417. _this.renderBufferImmediate(object, program);
  21418. });
  21419. }
  21420. this.renderBufferImmediate = function (object, program) {
  21421. bindingStates.initAttributes();
  21422. const buffers = properties.get(object);
  21423. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  21424. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  21425. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  21426. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  21427. const programAttributes = program.getAttributes();
  21428. if (object.hasPositions) {
  21429. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  21430. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  21431. bindingStates.enableAttribute(programAttributes.position.location);
  21432. _gl.vertexAttribPointer(programAttributes.position.location, 3, _gl.FLOAT, false, 0, 0);
  21433. }
  21434. if (object.hasNormals) {
  21435. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  21436. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  21437. bindingStates.enableAttribute(programAttributes.normal.location);
  21438. _gl.vertexAttribPointer(programAttributes.normal.location, 3, _gl.FLOAT, false, 0, 0);
  21439. }
  21440. if (object.hasUvs) {
  21441. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  21442. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  21443. bindingStates.enableAttribute(programAttributes.uv.location);
  21444. _gl.vertexAttribPointer(programAttributes.uv.location, 2, _gl.FLOAT, false, 0, 0);
  21445. }
  21446. if (object.hasColors) {
  21447. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  21448. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  21449. bindingStates.enableAttribute(programAttributes.color.location);
  21450. _gl.vertexAttribPointer(programAttributes.color.location, 3, _gl.FLOAT, false, 0, 0);
  21451. }
  21452. bindingStates.disableUnusedAttributes();
  21453. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  21454. object.count = 0;
  21455. };
  21456. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  21457. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  21458. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  21459. const program = setProgram(camera, scene, geometry, material, object);
  21460. state.setMaterial(material, frontFaceCW); //
  21461. let index = geometry.index;
  21462. const position = geometry.attributes.position; //
  21463. if (index === null) {
  21464. if (position === undefined || position.count === 0) return;
  21465. } else if (index.count === 0) {
  21466. return;
  21467. } //
  21468. let rangeFactor = 1;
  21469. if (material.wireframe === true) {
  21470. index = geometries.getWireframeAttribute(geometry);
  21471. rangeFactor = 2;
  21472. }
  21473. bindingStates.setup(object, material, program, geometry, index);
  21474. let attribute;
  21475. let renderer = bufferRenderer;
  21476. if (index !== null) {
  21477. attribute = attributes.get(index);
  21478. renderer = indexedBufferRenderer;
  21479. renderer.setIndex(attribute);
  21480. } //
  21481. const dataCount = index !== null ? index.count : position.count;
  21482. const rangeStart = geometry.drawRange.start * rangeFactor;
  21483. const rangeCount = geometry.drawRange.count * rangeFactor;
  21484. const groupStart = group !== null ? group.start * rangeFactor : 0;
  21485. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  21486. const drawStart = Math.max(rangeStart, groupStart);
  21487. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  21488. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  21489. if (drawCount === 0) return; //
  21490. if (object.isMesh) {
  21491. if (material.wireframe === true) {
  21492. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  21493. renderer.setMode(_gl.LINES);
  21494. } else {
  21495. renderer.setMode(_gl.TRIANGLES);
  21496. }
  21497. } else if (object.isLine) {
  21498. let lineWidth = material.linewidth;
  21499. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  21500. state.setLineWidth(lineWidth * getTargetPixelRatio());
  21501. if (object.isLineSegments) {
  21502. renderer.setMode(_gl.LINES);
  21503. } else if (object.isLineLoop) {
  21504. renderer.setMode(_gl.LINE_LOOP);
  21505. } else {
  21506. renderer.setMode(_gl.LINE_STRIP);
  21507. }
  21508. } else if (object.isPoints) {
  21509. renderer.setMode(_gl.POINTS);
  21510. } else if (object.isSprite) {
  21511. renderer.setMode(_gl.TRIANGLES);
  21512. }
  21513. if (object.isInstancedMesh) {
  21514. renderer.renderInstances(drawStart, drawCount, object.count);
  21515. } else if (geometry.isInstancedBufferGeometry) {
  21516. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  21517. renderer.renderInstances(drawStart, drawCount, instanceCount);
  21518. } else {
  21519. renderer.render(drawStart, drawCount);
  21520. }
  21521. }; // Compile
  21522. this.compile = function (scene, camera) {
  21523. currentRenderState = renderStates.get(scene);
  21524. currentRenderState.init();
  21525. renderStateStack.push(currentRenderState);
  21526. scene.traverseVisible(function (object) {
  21527. if (object.isLight && object.layers.test(camera.layers)) {
  21528. currentRenderState.pushLight(object);
  21529. if (object.castShadow) {
  21530. currentRenderState.pushShadow(object);
  21531. }
  21532. }
  21533. });
  21534. currentRenderState.setupLights(_this.physicallyCorrectLights);
  21535. scene.traverse(function (object) {
  21536. const material = object.material;
  21537. if (material) {
  21538. if (Array.isArray(material)) {
  21539. for (let i = 0; i < material.length; i++) {
  21540. const material2 = material[i];
  21541. getProgram(material2, scene, object);
  21542. }
  21543. } else {
  21544. getProgram(material, scene, object);
  21545. }
  21546. }
  21547. });
  21548. renderStateStack.pop();
  21549. currentRenderState = null;
  21550. }; // Animation Loop
  21551. let onAnimationFrameCallback = null;
  21552. function onAnimationFrame(time) {
  21553. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  21554. }
  21555. function onXRSessionStart() {
  21556. animation.stop();
  21557. }
  21558. function onXRSessionEnd() {
  21559. animation.start();
  21560. }
  21561. const animation = new WebGLAnimation();
  21562. animation.setAnimationLoop(onAnimationFrame);
  21563. if (typeof window !== 'undefined') animation.setContext(window);
  21564. this.setAnimationLoop = function (callback) {
  21565. onAnimationFrameCallback = callback;
  21566. xr.setAnimationLoop(callback);
  21567. callback === null ? animation.stop() : animation.start();
  21568. };
  21569. xr.addEventListener('sessionstart', onXRSessionStart);
  21570. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  21571. this.render = function (scene, camera) {
  21572. if (camera !== undefined && camera.isCamera !== true) {
  21573. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  21574. return;
  21575. }
  21576. if (_isContextLost === true) return; // update scene graph
  21577. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  21578. if (camera.parent === null) camera.updateMatrixWorld();
  21579. if (xr.enabled === true && xr.isPresenting === true) {
  21580. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  21581. camera = xr.getCamera(); // use XR camera for rendering
  21582. } //
  21583. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  21584. currentRenderState = renderStates.get(scene, renderStateStack.length);
  21585. currentRenderState.init();
  21586. renderStateStack.push(currentRenderState);
  21587. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  21588. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  21589. _localClippingEnabled = this.localClippingEnabled;
  21590. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  21591. currentRenderList = renderLists.get(scene, renderListStack.length);
  21592. currentRenderList.init();
  21593. renderListStack.push(currentRenderList);
  21594. projectObject(scene, camera, 0, _this.sortObjects);
  21595. currentRenderList.finish();
  21596. if (_this.sortObjects === true) {
  21597. currentRenderList.sort(_opaqueSort, _transparentSort);
  21598. } //
  21599. if (_clippingEnabled === true) clipping.beginShadows();
  21600. const shadowsArray = currentRenderState.state.shadowsArray;
  21601. shadowMap.render(shadowsArray, scene, camera);
  21602. if (_clippingEnabled === true) clipping.endShadows(); //
  21603. if (this.info.autoReset === true) this.info.reset(); //
  21604. background.render(currentRenderList, scene); // render scene
  21605. currentRenderState.setupLights(_this.physicallyCorrectLights);
  21606. if (camera.isArrayCamera) {
  21607. const cameras = camera.cameras;
  21608. for (let i = 0, l = cameras.length; i < l; i++) {
  21609. const camera2 = cameras[i];
  21610. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  21611. }
  21612. } else {
  21613. renderScene(currentRenderList, scene, camera);
  21614. } //
  21615. if (_currentRenderTarget !== null) {
  21616. // resolve multisample renderbuffers to a single-sample texture if necessary
  21617. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  21618. textures.updateRenderTargetMipmap(_currentRenderTarget);
  21619. } //
  21620. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  21621. state.buffers.depth.setTest(true);
  21622. state.buffers.depth.setMask(true);
  21623. state.buffers.color.setMask(true);
  21624. state.setPolygonOffset(false);
  21625. if (xr.enabled && xr.submitFrame) {
  21626. xr.submitFrame();
  21627. } // _gl.finish();
  21628. bindingStates.resetDefaultState();
  21629. _currentMaterialId = -1;
  21630. _currentCamera = null;
  21631. renderStateStack.pop();
  21632. if (renderStateStack.length > 0) {
  21633. currentRenderState = renderStateStack[renderStateStack.length - 1];
  21634. } else {
  21635. currentRenderState = null;
  21636. }
  21637. renderListStack.pop();
  21638. if (renderListStack.length > 0) {
  21639. currentRenderList = renderListStack[renderListStack.length - 1];
  21640. } else {
  21641. currentRenderList = null;
  21642. }
  21643. };
  21644. function projectObject(object, camera, groupOrder, sortObjects) {
  21645. if (object.visible === false) return;
  21646. const visible = object.layers.test(camera.layers);
  21647. if (visible) {
  21648. if (object.isGroup) {
  21649. groupOrder = object.renderOrder;
  21650. } else if (object.isLOD) {
  21651. if (object.autoUpdate === true) object.update(camera);
  21652. } else if (object.isLight) {
  21653. currentRenderState.pushLight(object);
  21654. if (object.castShadow) {
  21655. currentRenderState.pushShadow(object);
  21656. }
  21657. } else if (object.isSprite) {
  21658. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  21659. if (sortObjects) {
  21660. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21661. }
  21662. const geometry = objects.update(object);
  21663. const material = object.material;
  21664. if (material.visible) {
  21665. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  21666. }
  21667. }
  21668. } else if (object.isImmediateRenderObject) {
  21669. if (sortObjects) {
  21670. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21671. }
  21672. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  21673. } else if (object.isMesh || object.isLine || object.isPoints) {
  21674. if (object.isSkinnedMesh) {
  21675. // update skeleton only once in a frame
  21676. if (object.skeleton.frame !== info.render.frame) {
  21677. object.skeleton.update();
  21678. object.skeleton.frame = info.render.frame;
  21679. }
  21680. }
  21681. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  21682. if (sortObjects) {
  21683. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21684. }
  21685. const geometry = objects.update(object);
  21686. const material = object.material;
  21687. if (Array.isArray(material)) {
  21688. const groups = geometry.groups;
  21689. for (let i = 0, l = groups.length; i < l; i++) {
  21690. const group = groups[i];
  21691. const groupMaterial = material[group.materialIndex];
  21692. if (groupMaterial && groupMaterial.visible) {
  21693. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  21694. }
  21695. }
  21696. } else if (material.visible) {
  21697. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  21698. }
  21699. }
  21700. }
  21701. }
  21702. const children = object.children;
  21703. for (let i = 0, l = children.length; i < l; i++) {
  21704. projectObject(children[i], camera, groupOrder, sortObjects);
  21705. }
  21706. }
  21707. function renderScene(currentRenderList, scene, camera, viewport) {
  21708. const opaqueObjects = currentRenderList.opaque;
  21709. const transmissiveObjects = currentRenderList.transmissive;
  21710. const transparentObjects = currentRenderList.transparent;
  21711. currentRenderState.setupLightsView(camera);
  21712. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  21713. if (viewport) state.viewport(_currentViewport.copy(viewport));
  21714. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  21715. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  21716. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  21717. }
  21718. function renderTransmissionPass(opaqueObjects, scene, camera) {
  21719. if (_transmissionRenderTarget === null) {
  21720. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  21721. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  21722. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  21723. generateMipmaps: true,
  21724. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  21725. minFilter: LinearMipmapLinearFilter,
  21726. magFilter: NearestFilter,
  21727. wrapS: ClampToEdgeWrapping,
  21728. wrapT: ClampToEdgeWrapping
  21729. });
  21730. }
  21731. const currentRenderTarget = _this.getRenderTarget();
  21732. _this.setRenderTarget(_transmissionRenderTarget);
  21733. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  21734. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  21735. const currentToneMapping = _this.toneMapping;
  21736. _this.toneMapping = NoToneMapping;
  21737. renderObjects(opaqueObjects, scene, camera);
  21738. _this.toneMapping = currentToneMapping;
  21739. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  21740. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  21741. _this.setRenderTarget(currentRenderTarget);
  21742. }
  21743. function renderObjects(renderList, scene, camera) {
  21744. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  21745. for (let i = 0, l = renderList.length; i < l; i++) {
  21746. const renderItem = renderList[i];
  21747. const object = renderItem.object;
  21748. const geometry = renderItem.geometry;
  21749. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  21750. const group = renderItem.group;
  21751. if (object.layers.test(camera.layers)) {
  21752. renderObject(object, scene, camera, geometry, material, group);
  21753. }
  21754. }
  21755. }
  21756. function renderObject(object, scene, camera, geometry, material, group) {
  21757. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  21758. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  21759. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  21760. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  21761. if (object.isImmediateRenderObject) {
  21762. const program = setProgram(camera, scene, geometry, material, object);
  21763. state.setMaterial(material);
  21764. bindingStates.reset();
  21765. renderObjectImmediate(object, program);
  21766. } else {
  21767. if (material.transparent === true && material.side === DoubleSide) {
  21768. material.side = BackSide;
  21769. material.needsUpdate = true;
  21770. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  21771. material.side = FrontSide;
  21772. material.needsUpdate = true;
  21773. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  21774. material.side = DoubleSide;
  21775. } else {
  21776. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  21777. }
  21778. }
  21779. object.onAfterRender(_this, scene, camera, geometry, material, group);
  21780. }
  21781. function getProgram(material, scene, object) {
  21782. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21783. const materialProperties = properties.get(material);
  21784. const lights = currentRenderState.state.lights;
  21785. const shadowsArray = currentRenderState.state.shadowsArray;
  21786. const lightsStateVersion = lights.state.version;
  21787. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  21788. const programCacheKey = programCache.getProgramCacheKey(parameters);
  21789. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  21790. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  21791. materialProperties.fog = scene.fog;
  21792. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  21793. if (programs === undefined) {
  21794. // new material
  21795. material.addEventListener('dispose', onMaterialDispose);
  21796. programs = new Map();
  21797. materialProperties.programs = programs;
  21798. }
  21799. let program = programs.get(programCacheKey);
  21800. if (program !== undefined) {
  21801. // early out if program and light state is identical
  21802. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  21803. updateCommonMaterialProperties(material, parameters);
  21804. return program;
  21805. }
  21806. } else {
  21807. parameters.uniforms = programCache.getUniforms(material);
  21808. material.onBuild(parameters, _this);
  21809. material.onBeforeCompile(parameters, _this);
  21810. program = programCache.acquireProgram(parameters, programCacheKey);
  21811. programs.set(programCacheKey, program);
  21812. materialProperties.uniforms = parameters.uniforms;
  21813. }
  21814. const uniforms = materialProperties.uniforms;
  21815. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  21816. uniforms.clippingPlanes = clipping.uniform;
  21817. }
  21818. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  21819. materialProperties.needsLights = materialNeedsLights(material);
  21820. materialProperties.lightsStateVersion = lightsStateVersion;
  21821. if (materialProperties.needsLights) {
  21822. // wire up the material to this renderer's lighting state
  21823. uniforms.ambientLightColor.value = lights.state.ambient;
  21824. uniforms.lightProbe.value = lights.state.probe;
  21825. uniforms.directionalLights.value = lights.state.directional;
  21826. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  21827. uniforms.spotLights.value = lights.state.spot;
  21828. uniforms.spotLightShadows.value = lights.state.spotShadow;
  21829. uniforms.rectAreaLights.value = lights.state.rectArea;
  21830. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  21831. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  21832. uniforms.pointLights.value = lights.state.point;
  21833. uniforms.pointLightShadows.value = lights.state.pointShadow;
  21834. uniforms.hemisphereLights.value = lights.state.hemi;
  21835. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  21836. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  21837. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  21838. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  21839. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  21840. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  21841. }
  21842. const progUniforms = program.getUniforms();
  21843. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  21844. materialProperties.currentProgram = program;
  21845. materialProperties.uniformsList = uniformsList;
  21846. return program;
  21847. }
  21848. function updateCommonMaterialProperties(material, parameters) {
  21849. const materialProperties = properties.get(material);
  21850. materialProperties.outputEncoding = parameters.outputEncoding;
  21851. materialProperties.instancing = parameters.instancing;
  21852. materialProperties.skinning = parameters.skinning;
  21853. materialProperties.morphTargets = parameters.morphTargets;
  21854. materialProperties.morphNormals = parameters.morphNormals;
  21855. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  21856. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  21857. materialProperties.numIntersection = parameters.numClipIntersection;
  21858. materialProperties.vertexAlphas = parameters.vertexAlphas;
  21859. materialProperties.vertexTangents = parameters.vertexTangents;
  21860. }
  21861. function setProgram(camera, scene, geometry, material, object) {
  21862. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21863. textures.resetTextureUnits();
  21864. const fog = scene.fog;
  21865. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  21866. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  21867. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  21868. const vertexAlphas = material.vertexColors === true && !!geometry && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  21869. const vertexTangents = !!material.normalMap && !!geometry && !!geometry.attributes.tangent;
  21870. const morphTargets = !!geometry && !!geometry.morphAttributes.position;
  21871. const morphNormals = !!geometry && !!geometry.morphAttributes.normal;
  21872. const morphTargetsCount = !!geometry && !!geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  21873. const materialProperties = properties.get(material);
  21874. const lights = currentRenderState.state.lights;
  21875. if (_clippingEnabled === true) {
  21876. if (_localClippingEnabled === true || camera !== _currentCamera) {
  21877. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  21878. // object instead of the material, once it becomes feasible
  21879. // (#8465, #8379)
  21880. clipping.setState(material, camera, useCache);
  21881. }
  21882. } //
  21883. let needsProgramChange = false;
  21884. if (material.version === materialProperties.__version) {
  21885. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  21886. needsProgramChange = true;
  21887. } else if (materialProperties.outputEncoding !== encoding) {
  21888. needsProgramChange = true;
  21889. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  21890. needsProgramChange = true;
  21891. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  21892. needsProgramChange = true;
  21893. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  21894. needsProgramChange = true;
  21895. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  21896. needsProgramChange = true;
  21897. } else if (materialProperties.envMap !== envMap) {
  21898. needsProgramChange = true;
  21899. } else if (material.fog && materialProperties.fog !== fog) {
  21900. needsProgramChange = true;
  21901. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  21902. needsProgramChange = true;
  21903. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  21904. needsProgramChange = true;
  21905. } else if (materialProperties.vertexTangents !== vertexTangents) {
  21906. needsProgramChange = true;
  21907. } else if (materialProperties.morphTargets !== morphTargets) {
  21908. needsProgramChange = true;
  21909. } else if (materialProperties.morphNormals !== morphNormals) {
  21910. needsProgramChange = true;
  21911. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  21912. needsProgramChange = true;
  21913. }
  21914. } else {
  21915. needsProgramChange = true;
  21916. materialProperties.__version = material.version;
  21917. } //
  21918. let program = materialProperties.currentProgram;
  21919. if (needsProgramChange === true) {
  21920. program = getProgram(material, scene, object);
  21921. }
  21922. let refreshProgram = false;
  21923. let refreshMaterial = false;
  21924. let refreshLights = false;
  21925. const p_uniforms = program.getUniforms(),
  21926. m_uniforms = materialProperties.uniforms;
  21927. if (state.useProgram(program.program)) {
  21928. refreshProgram = true;
  21929. refreshMaterial = true;
  21930. refreshLights = true;
  21931. }
  21932. if (material.id !== _currentMaterialId) {
  21933. _currentMaterialId = material.id;
  21934. refreshMaterial = true;
  21935. }
  21936. if (refreshProgram || _currentCamera !== camera) {
  21937. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  21938. if (capabilities.logarithmicDepthBuffer) {
  21939. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  21940. }
  21941. if (_currentCamera !== camera) {
  21942. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  21943. // now, in case this material supports lights - or later, when
  21944. // the next material that does gets activated:
  21945. refreshMaterial = true; // set to true on material change
  21946. refreshLights = true; // remains set until update done
  21947. } // load material specific uniforms
  21948. // (shader material also gets them for the sake of genericity)
  21949. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  21950. const uCamPos = p_uniforms.map.cameraPosition;
  21951. if (uCamPos !== undefined) {
  21952. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  21953. }
  21954. }
  21955. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  21956. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  21957. }
  21958. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  21959. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  21960. }
  21961. } // skinning and morph target uniforms must be set even if material didn't change
  21962. // auto-setting of texture unit for bone and morph texture must go before other textures
  21963. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  21964. if (object.isSkinnedMesh) {
  21965. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  21966. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  21967. const skeleton = object.skeleton;
  21968. if (skeleton) {
  21969. if (capabilities.floatVertexTextures) {
  21970. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  21971. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  21972. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  21973. } else {
  21974. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  21975. }
  21976. }
  21977. }
  21978. if (!!geometry && (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined)) {
  21979. morphtargets.update(object, geometry, material, program);
  21980. }
  21981. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  21982. materialProperties.receiveShadow = object.receiveShadow;
  21983. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  21984. }
  21985. if (refreshMaterial) {
  21986. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  21987. if (materialProperties.needsLights) {
  21988. // the current material requires lighting info
  21989. // note: all lighting uniforms are always set correctly
  21990. // they simply reference the renderer's state for their
  21991. // values
  21992. //
  21993. // use the current material's .needsUpdate flags to set
  21994. // the GL state when required
  21995. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  21996. } // refresh uniforms common to several materials
  21997. if (fog && material.fog) {
  21998. materials.refreshFogUniforms(m_uniforms, fog);
  21999. }
  22000. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  22001. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  22002. }
  22003. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  22004. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  22005. material.uniformsNeedUpdate = false;
  22006. }
  22007. if (material.isSpriteMaterial) {
  22008. p_uniforms.setValue(_gl, 'center', object.center);
  22009. } // common matrices
  22010. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  22011. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  22012. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  22013. return program;
  22014. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  22015. function markUniformsLightsNeedsUpdate(uniforms, value) {
  22016. uniforms.ambientLightColor.needsUpdate = value;
  22017. uniforms.lightProbe.needsUpdate = value;
  22018. uniforms.directionalLights.needsUpdate = value;
  22019. uniforms.directionalLightShadows.needsUpdate = value;
  22020. uniforms.pointLights.needsUpdate = value;
  22021. uniforms.pointLightShadows.needsUpdate = value;
  22022. uniforms.spotLights.needsUpdate = value;
  22023. uniforms.spotLightShadows.needsUpdate = value;
  22024. uniforms.rectAreaLights.needsUpdate = value;
  22025. uniforms.hemisphereLights.needsUpdate = value;
  22026. }
  22027. function materialNeedsLights(material) {
  22028. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  22029. }
  22030. this.setTexture2D = function () {
  22031. var warned = false; // backwards compatibility: peel texture.texture
  22032. return function setTexture2D(texture, slot) {
  22033. if (texture && texture.isWebGLRenderTarget) {
  22034. if (!warned) {
  22035. console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead.");
  22036. warned = true;
  22037. }
  22038. texture = texture.texture;
  22039. }
  22040. textures.setTexture2D(texture, slot);
  22041. };
  22042. }();
  22043. this.getActiveCubeFace = function () {
  22044. return _currentActiveCubeFace;
  22045. };
  22046. this.getActiveMipmapLevel = function () {
  22047. return _currentActiveMipmapLevel;
  22048. };
  22049. this.getRenderTarget = function () {
  22050. return _currentRenderTarget;
  22051. };
  22052. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  22053. _currentRenderTarget = renderTarget;
  22054. _currentActiveCubeFace = activeCubeFace;
  22055. _currentActiveMipmapLevel = activeMipmapLevel;
  22056. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  22057. textures.setupRenderTarget(renderTarget);
  22058. }
  22059. let framebuffer = null;
  22060. let isCube = false;
  22061. let isRenderTarget3D = false;
  22062. if (renderTarget) {
  22063. const texture = renderTarget.texture;
  22064. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  22065. isRenderTarget3D = true;
  22066. }
  22067. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  22068. if (renderTarget.isWebGLCubeRenderTarget) {
  22069. framebuffer = __webglFramebuffer[activeCubeFace];
  22070. isCube = true;
  22071. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  22072. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  22073. } else {
  22074. framebuffer = __webglFramebuffer;
  22075. }
  22076. _currentViewport.copy(renderTarget.viewport);
  22077. _currentScissor.copy(renderTarget.scissor);
  22078. _currentScissorTest = renderTarget.scissorTest;
  22079. } else {
  22080. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  22081. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  22082. _currentScissorTest = _scissorTest;
  22083. }
  22084. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  22085. if (framebufferBound && capabilities.drawBuffers) {
  22086. let needsUpdate = false;
  22087. if (renderTarget) {
  22088. if (renderTarget.isWebGLMultipleRenderTargets) {
  22089. const textures = renderTarget.texture;
  22090. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  22091. for (let i = 0, il = textures.length; i < il; i++) {
  22092. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  22093. }
  22094. _currentDrawBuffers.length = textures.length;
  22095. needsUpdate = true;
  22096. }
  22097. } else {
  22098. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  22099. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  22100. _currentDrawBuffers.length = 1;
  22101. needsUpdate = true;
  22102. }
  22103. }
  22104. } else {
  22105. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  22106. _currentDrawBuffers[0] = _gl.BACK;
  22107. _currentDrawBuffers.length = 1;
  22108. needsUpdate = true;
  22109. }
  22110. }
  22111. if (needsUpdate) {
  22112. if (capabilities.isWebGL2) {
  22113. _gl.drawBuffers(_currentDrawBuffers);
  22114. } else {
  22115. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  22116. }
  22117. }
  22118. }
  22119. state.viewport(_currentViewport);
  22120. state.scissor(_currentScissor);
  22121. state.setScissorTest(_currentScissorTest);
  22122. if (isCube) {
  22123. const textureProperties = properties.get(renderTarget.texture);
  22124. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  22125. } else if (isRenderTarget3D) {
  22126. const textureProperties = properties.get(renderTarget.texture);
  22127. const layer = activeCubeFace || 0;
  22128. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  22129. }
  22130. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  22131. };
  22132. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  22133. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  22134. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  22135. return;
  22136. }
  22137. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  22138. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  22139. framebuffer = framebuffer[activeCubeFaceIndex];
  22140. }
  22141. if (framebuffer) {
  22142. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  22143. try {
  22144. const texture = renderTarget.texture;
  22145. const textureFormat = texture.format;
  22146. const textureType = texture.type;
  22147. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  22148. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  22149. return;
  22150. }
  22151. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  22152. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  22153. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  22154. !halfFloatSupportedByExt) {
  22155. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  22156. return;
  22157. }
  22158. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  22159. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  22160. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  22161. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  22162. }
  22163. } else {
  22164. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  22165. }
  22166. } finally {
  22167. // restore framebuffer of current render target if necessary
  22168. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  22169. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  22170. }
  22171. }
  22172. };
  22173. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  22174. const levelScale = Math.pow(2, -level);
  22175. const width = Math.floor(texture.image.width * levelScale);
  22176. const height = Math.floor(texture.image.height * levelScale);
  22177. let glFormat = utils.convert(texture.format);
  22178. if (capabilities.isWebGL2) {
  22179. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  22180. // Not needed in Chrome 93+
  22181. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  22182. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  22183. }
  22184. textures.setTexture2D(texture, 0);
  22185. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  22186. state.unbindTexture();
  22187. };
  22188. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  22189. const width = srcTexture.image.width;
  22190. const height = srcTexture.image.height;
  22191. const glFormat = utils.convert(dstTexture.format);
  22192. const glType = utils.convert(dstTexture.type);
  22193. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  22194. // parameters, make sure they are correct for the dstTexture
  22195. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  22196. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  22197. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  22198. if (srcTexture.isDataTexture) {
  22199. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  22200. } else {
  22201. if (srcTexture.isCompressedTexture) {
  22202. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  22203. } else {
  22204. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  22205. }
  22206. } // Generate mipmaps only when copying level 0
  22207. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  22208. state.unbindTexture();
  22209. };
  22210. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  22211. if (_this.isWebGL1Renderer) {
  22212. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  22213. return;
  22214. }
  22215. const width = sourceBox.max.x - sourceBox.min.x + 1;
  22216. const height = sourceBox.max.y - sourceBox.min.y + 1;
  22217. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  22218. const glFormat = utils.convert(dstTexture.format);
  22219. const glType = utils.convert(dstTexture.type);
  22220. let glTarget;
  22221. if (dstTexture.isDataTexture3D) {
  22222. textures.setTexture3D(dstTexture, 0);
  22223. glTarget = _gl.TEXTURE_3D;
  22224. } else if (dstTexture.isDataTexture2DArray) {
  22225. textures.setTexture2DArray(dstTexture, 0);
  22226. glTarget = _gl.TEXTURE_2D_ARRAY;
  22227. } else {
  22228. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  22229. return;
  22230. }
  22231. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  22232. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  22233. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  22234. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  22235. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  22236. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  22237. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  22238. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  22239. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  22240. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  22241. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  22242. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  22243. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  22244. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  22245. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  22246. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  22247. } else {
  22248. if (srcTexture.isCompressedTexture) {
  22249. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  22250. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  22251. } else {
  22252. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  22253. }
  22254. }
  22255. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  22256. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  22257. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  22258. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  22259. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  22260. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  22261. state.unbindTexture();
  22262. };
  22263. this.initTexture = function (texture) {
  22264. textures.setTexture2D(texture, 0);
  22265. state.unbindTexture();
  22266. };
  22267. this.resetState = function () {
  22268. _currentActiveCubeFace = 0;
  22269. _currentActiveMipmapLevel = 0;
  22270. _currentRenderTarget = null;
  22271. state.reset();
  22272. bindingStates.reset();
  22273. };
  22274. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  22275. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  22276. detail: this
  22277. })); // eslint-disable-line no-undef
  22278. }
  22279. }
  22280. class WebGL1Renderer extends WebGLRenderer {}
  22281. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  22282. class FogExp2 {
  22283. constructor(color, density = 0.00025) {
  22284. this.name = '';
  22285. this.color = new Color(color);
  22286. this.density = density;
  22287. }
  22288. clone() {
  22289. return new FogExp2(this.color, this.density);
  22290. }
  22291. toJSON() {
  22292. return {
  22293. type: 'FogExp2',
  22294. color: this.color.getHex(),
  22295. density: this.density
  22296. };
  22297. }
  22298. }
  22299. FogExp2.prototype.isFogExp2 = true;
  22300. class Fog {
  22301. constructor(color, near = 1, far = 1000) {
  22302. this.name = '';
  22303. this.color = new Color(color);
  22304. this.near = near;
  22305. this.far = far;
  22306. }
  22307. clone() {
  22308. return new Fog(this.color, this.near, this.far);
  22309. }
  22310. toJSON() {
  22311. return {
  22312. type: 'Fog',
  22313. color: this.color.getHex(),
  22314. near: this.near,
  22315. far: this.far
  22316. };
  22317. }
  22318. }
  22319. Fog.prototype.isFog = true;
  22320. class Scene extends Object3D {
  22321. constructor() {
  22322. super();
  22323. this.type = 'Scene';
  22324. this.background = null;
  22325. this.environment = null;
  22326. this.fog = null;
  22327. this.overrideMaterial = null;
  22328. this.autoUpdate = true; // checked by the renderer
  22329. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  22330. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  22331. detail: this
  22332. })); // eslint-disable-line no-undef
  22333. }
  22334. }
  22335. copy(source, recursive) {
  22336. super.copy(source, recursive);
  22337. if (source.background !== null) this.background = source.background.clone();
  22338. if (source.environment !== null) this.environment = source.environment.clone();
  22339. if (source.fog !== null) this.fog = source.fog.clone();
  22340. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  22341. this.autoUpdate = source.autoUpdate;
  22342. this.matrixAutoUpdate = source.matrixAutoUpdate;
  22343. return this;
  22344. }
  22345. toJSON(meta) {
  22346. const data = super.toJSON(meta);
  22347. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  22348. return data;
  22349. }
  22350. }
  22351. Scene.prototype.isScene = true;
  22352. class InterleavedBuffer {
  22353. constructor(array, stride) {
  22354. this.array = array;
  22355. this.stride = stride;
  22356. this.count = array !== undefined ? array.length / stride : 0;
  22357. this.usage = StaticDrawUsage;
  22358. this.updateRange = {
  22359. offset: 0,
  22360. count: -1
  22361. };
  22362. this.version = 0;
  22363. this.uuid = generateUUID();
  22364. }
  22365. onUploadCallback() {}
  22366. set needsUpdate(value) {
  22367. if (value === true) this.version++;
  22368. }
  22369. setUsage(value) {
  22370. this.usage = value;
  22371. return this;
  22372. }
  22373. copy(source) {
  22374. this.array = new source.array.constructor(source.array);
  22375. this.count = source.count;
  22376. this.stride = source.stride;
  22377. this.usage = source.usage;
  22378. return this;
  22379. }
  22380. copyAt(index1, attribute, index2) {
  22381. index1 *= this.stride;
  22382. index2 *= attribute.stride;
  22383. for (let i = 0, l = this.stride; i < l; i++) {
  22384. this.array[index1 + i] = attribute.array[index2 + i];
  22385. }
  22386. return this;
  22387. }
  22388. set(value, offset = 0) {
  22389. this.array.set(value, offset);
  22390. return this;
  22391. }
  22392. clone(data) {
  22393. if (data.arrayBuffers === undefined) {
  22394. data.arrayBuffers = {};
  22395. }
  22396. if (this.array.buffer._uuid === undefined) {
  22397. this.array.buffer._uuid = generateUUID();
  22398. }
  22399. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  22400. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  22401. }
  22402. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  22403. const ib = new this.constructor(array, this.stride);
  22404. ib.setUsage(this.usage);
  22405. return ib;
  22406. }
  22407. onUpload(callback) {
  22408. this.onUploadCallback = callback;
  22409. return this;
  22410. }
  22411. toJSON(data) {
  22412. if (data.arrayBuffers === undefined) {
  22413. data.arrayBuffers = {};
  22414. } // generate UUID for array buffer if necessary
  22415. if (this.array.buffer._uuid === undefined) {
  22416. this.array.buffer._uuid = generateUUID();
  22417. }
  22418. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  22419. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  22420. } //
  22421. return {
  22422. uuid: this.uuid,
  22423. buffer: this.array.buffer._uuid,
  22424. type: this.array.constructor.name,
  22425. stride: this.stride
  22426. };
  22427. }
  22428. }
  22429. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  22430. const _vector$6 = /*@__PURE__*/new Vector3();
  22431. class InterleavedBufferAttribute {
  22432. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  22433. this.name = '';
  22434. this.data = interleavedBuffer;
  22435. this.itemSize = itemSize;
  22436. this.offset = offset;
  22437. this.normalized = normalized === true;
  22438. }
  22439. get count() {
  22440. return this.data.count;
  22441. }
  22442. get array() {
  22443. return this.data.array;
  22444. }
  22445. set needsUpdate(value) {
  22446. this.data.needsUpdate = value;
  22447. }
  22448. applyMatrix4(m) {
  22449. for (let i = 0, l = this.data.count; i < l; i++) {
  22450. _vector$6.x = this.getX(i);
  22451. _vector$6.y = this.getY(i);
  22452. _vector$6.z = this.getZ(i);
  22453. _vector$6.applyMatrix4(m);
  22454. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  22455. }
  22456. return this;
  22457. }
  22458. applyNormalMatrix(m) {
  22459. for (let i = 0, l = this.count; i < l; i++) {
  22460. _vector$6.x = this.getX(i);
  22461. _vector$6.y = this.getY(i);
  22462. _vector$6.z = this.getZ(i);
  22463. _vector$6.applyNormalMatrix(m);
  22464. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  22465. }
  22466. return this;
  22467. }
  22468. transformDirection(m) {
  22469. for (let i = 0, l = this.count; i < l; i++) {
  22470. _vector$6.x = this.getX(i);
  22471. _vector$6.y = this.getY(i);
  22472. _vector$6.z = this.getZ(i);
  22473. _vector$6.transformDirection(m);
  22474. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  22475. }
  22476. return this;
  22477. }
  22478. setX(index, x) {
  22479. this.data.array[index * this.data.stride + this.offset] = x;
  22480. return this;
  22481. }
  22482. setY(index, y) {
  22483. this.data.array[index * this.data.stride + this.offset + 1] = y;
  22484. return this;
  22485. }
  22486. setZ(index, z) {
  22487. this.data.array[index * this.data.stride + this.offset + 2] = z;
  22488. return this;
  22489. }
  22490. setW(index, w) {
  22491. this.data.array[index * this.data.stride + this.offset + 3] = w;
  22492. return this;
  22493. }
  22494. getX(index) {
  22495. return this.data.array[index * this.data.stride + this.offset];
  22496. }
  22497. getY(index) {
  22498. return this.data.array[index * this.data.stride + this.offset + 1];
  22499. }
  22500. getZ(index) {
  22501. return this.data.array[index * this.data.stride + this.offset + 2];
  22502. }
  22503. getW(index) {
  22504. return this.data.array[index * this.data.stride + this.offset + 3];
  22505. }
  22506. setXY(index, x, y) {
  22507. index = index * this.data.stride + this.offset;
  22508. this.data.array[index + 0] = x;
  22509. this.data.array[index + 1] = y;
  22510. return this;
  22511. }
  22512. setXYZ(index, x, y, z) {
  22513. index = index * this.data.stride + this.offset;
  22514. this.data.array[index + 0] = x;
  22515. this.data.array[index + 1] = y;
  22516. this.data.array[index + 2] = z;
  22517. return this;
  22518. }
  22519. setXYZW(index, x, y, z, w) {
  22520. index = index * this.data.stride + this.offset;
  22521. this.data.array[index + 0] = x;
  22522. this.data.array[index + 1] = y;
  22523. this.data.array[index + 2] = z;
  22524. this.data.array[index + 3] = w;
  22525. return this;
  22526. }
  22527. clone(data) {
  22528. if (data === undefined) {
  22529. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  22530. const array = [];
  22531. for (let i = 0; i < this.count; i++) {
  22532. const index = i * this.data.stride + this.offset;
  22533. for (let j = 0; j < this.itemSize; j++) {
  22534. array.push(this.data.array[index + j]);
  22535. }
  22536. }
  22537. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  22538. } else {
  22539. if (data.interleavedBuffers === undefined) {
  22540. data.interleavedBuffers = {};
  22541. }
  22542. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22543. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  22544. }
  22545. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  22546. }
  22547. }
  22548. toJSON(data) {
  22549. if (data === undefined) {
  22550. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  22551. const array = [];
  22552. for (let i = 0; i < this.count; i++) {
  22553. const index = i * this.data.stride + this.offset;
  22554. for (let j = 0; j < this.itemSize; j++) {
  22555. array.push(this.data.array[index + j]);
  22556. }
  22557. } // deinterleave data and save it as an ordinary buffer attribute for now
  22558. return {
  22559. itemSize: this.itemSize,
  22560. type: this.array.constructor.name,
  22561. array: array,
  22562. normalized: this.normalized
  22563. };
  22564. } else {
  22565. // save as true interlaved attribtue
  22566. if (data.interleavedBuffers === undefined) {
  22567. data.interleavedBuffers = {};
  22568. }
  22569. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22570. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  22571. }
  22572. return {
  22573. isInterleavedBufferAttribute: true,
  22574. itemSize: this.itemSize,
  22575. data: this.data.uuid,
  22576. offset: this.offset,
  22577. normalized: this.normalized
  22578. };
  22579. }
  22580. }
  22581. }
  22582. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  22583. /**
  22584. * parameters = {
  22585. * color: <hex>,
  22586. * map: new THREE.Texture( <Image> ),
  22587. * alphaMap: new THREE.Texture( <Image> ),
  22588. * rotation: <float>,
  22589. * sizeAttenuation: <bool>
  22590. * }
  22591. */
  22592. class SpriteMaterial extends Material {
  22593. constructor(parameters) {
  22594. super();
  22595. this.type = 'SpriteMaterial';
  22596. this.color = new Color(0xffffff);
  22597. this.map = null;
  22598. this.alphaMap = null;
  22599. this.rotation = 0;
  22600. this.sizeAttenuation = true;
  22601. this.transparent = true;
  22602. this.setValues(parameters);
  22603. }
  22604. copy(source) {
  22605. super.copy(source);
  22606. this.color.copy(source.color);
  22607. this.map = source.map;
  22608. this.alphaMap = source.alphaMap;
  22609. this.rotation = source.rotation;
  22610. this.sizeAttenuation = source.sizeAttenuation;
  22611. return this;
  22612. }
  22613. }
  22614. SpriteMaterial.prototype.isSpriteMaterial = true;
  22615. let _geometry;
  22616. const _intersectPoint = /*@__PURE__*/new Vector3();
  22617. const _worldScale = /*@__PURE__*/new Vector3();
  22618. const _mvPosition = /*@__PURE__*/new Vector3();
  22619. const _alignedPosition = /*@__PURE__*/new Vector2();
  22620. const _rotatedPosition = /*@__PURE__*/new Vector2();
  22621. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  22622. const _vA = /*@__PURE__*/new Vector3();
  22623. const _vB = /*@__PURE__*/new Vector3();
  22624. const _vC = /*@__PURE__*/new Vector3();
  22625. const _uvA = /*@__PURE__*/new Vector2();
  22626. const _uvB = /*@__PURE__*/new Vector2();
  22627. const _uvC = /*@__PURE__*/new Vector2();
  22628. class Sprite extends Object3D {
  22629. constructor(material) {
  22630. super();
  22631. this.type = 'Sprite';
  22632. if (_geometry === undefined) {
  22633. _geometry = new BufferGeometry();
  22634. const 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]);
  22635. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  22636. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  22637. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  22638. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  22639. }
  22640. this.geometry = _geometry;
  22641. this.material = material !== undefined ? material : new SpriteMaterial();
  22642. this.center = new Vector2(0.5, 0.5);
  22643. }
  22644. raycast(raycaster, intersects) {
  22645. if (raycaster.camera === null) {
  22646. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  22647. }
  22648. _worldScale.setFromMatrixScale(this.matrixWorld);
  22649. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  22650. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  22651. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  22652. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  22653. _worldScale.multiplyScalar(-_mvPosition.z);
  22654. }
  22655. const rotation = this.material.rotation;
  22656. let sin, cos;
  22657. if (rotation !== 0) {
  22658. cos = Math.cos(rotation);
  22659. sin = Math.sin(rotation);
  22660. }
  22661. const center = this.center;
  22662. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22663. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22664. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22665. _uvA.set(0, 0);
  22666. _uvB.set(1, 0);
  22667. _uvC.set(1, 1); // check first triangle
  22668. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  22669. if (intersect === null) {
  22670. // check second triangle
  22671. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22672. _uvB.set(0, 1);
  22673. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  22674. if (intersect === null) {
  22675. return;
  22676. }
  22677. }
  22678. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  22679. if (distance < raycaster.near || distance > raycaster.far) return;
  22680. intersects.push({
  22681. distance: distance,
  22682. point: _intersectPoint.clone(),
  22683. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  22684. face: null,
  22685. object: this
  22686. });
  22687. }
  22688. copy(source) {
  22689. super.copy(source);
  22690. if (source.center !== undefined) this.center.copy(source.center);
  22691. this.material = source.material;
  22692. return this;
  22693. }
  22694. }
  22695. Sprite.prototype.isSprite = true;
  22696. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  22697. // compute position in camera space
  22698. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  22699. if (sin !== undefined) {
  22700. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  22701. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  22702. } else {
  22703. _rotatedPosition.copy(_alignedPosition);
  22704. }
  22705. vertexPosition.copy(mvPosition);
  22706. vertexPosition.x += _rotatedPosition.x;
  22707. vertexPosition.y += _rotatedPosition.y; // transform to world space
  22708. vertexPosition.applyMatrix4(_viewWorldMatrix);
  22709. }
  22710. const _v1$2 = /*@__PURE__*/new Vector3();
  22711. const _v2$1 = /*@__PURE__*/new Vector3();
  22712. class LOD extends Object3D {
  22713. constructor() {
  22714. super();
  22715. this._currentLevel = 0;
  22716. this.type = 'LOD';
  22717. Object.defineProperties(this, {
  22718. levels: {
  22719. enumerable: true,
  22720. value: []
  22721. },
  22722. isLOD: {
  22723. value: true
  22724. }
  22725. });
  22726. this.autoUpdate = true;
  22727. }
  22728. copy(source) {
  22729. super.copy(source, false);
  22730. const levels = source.levels;
  22731. for (let i = 0, l = levels.length; i < l; i++) {
  22732. const level = levels[i];
  22733. this.addLevel(level.object.clone(), level.distance);
  22734. }
  22735. this.autoUpdate = source.autoUpdate;
  22736. return this;
  22737. }
  22738. addLevel(object, distance = 0) {
  22739. distance = Math.abs(distance);
  22740. const levels = this.levels;
  22741. let l;
  22742. for (l = 0; l < levels.length; l++) {
  22743. if (distance < levels[l].distance) {
  22744. break;
  22745. }
  22746. }
  22747. levels.splice(l, 0, {
  22748. distance: distance,
  22749. object: object
  22750. });
  22751. this.add(object);
  22752. return this;
  22753. }
  22754. getCurrentLevel() {
  22755. return this._currentLevel;
  22756. }
  22757. getObjectForDistance(distance) {
  22758. const levels = this.levels;
  22759. if (levels.length > 0) {
  22760. let i, l;
  22761. for (i = 1, l = levels.length; i < l; i++) {
  22762. if (distance < levels[i].distance) {
  22763. break;
  22764. }
  22765. }
  22766. return levels[i - 1].object;
  22767. }
  22768. return null;
  22769. }
  22770. raycast(raycaster, intersects) {
  22771. const levels = this.levels;
  22772. if (levels.length > 0) {
  22773. _v1$2.setFromMatrixPosition(this.matrixWorld);
  22774. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  22775. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  22776. }
  22777. }
  22778. update(camera) {
  22779. const levels = this.levels;
  22780. if (levels.length > 1) {
  22781. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  22782. _v2$1.setFromMatrixPosition(this.matrixWorld);
  22783. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  22784. levels[0].object.visible = true;
  22785. let i, l;
  22786. for (i = 1, l = levels.length; i < l; i++) {
  22787. if (distance >= levels[i].distance) {
  22788. levels[i - 1].object.visible = false;
  22789. levels[i].object.visible = true;
  22790. } else {
  22791. break;
  22792. }
  22793. }
  22794. this._currentLevel = i - 1;
  22795. for (; i < l; i++) {
  22796. levels[i].object.visible = false;
  22797. }
  22798. }
  22799. }
  22800. toJSON(meta) {
  22801. const data = super.toJSON(meta);
  22802. if (this.autoUpdate === false) data.object.autoUpdate = false;
  22803. data.object.levels = [];
  22804. const levels = this.levels;
  22805. for (let i = 0, l = levels.length; i < l; i++) {
  22806. const level = levels[i];
  22807. data.object.levels.push({
  22808. object: level.object.uuid,
  22809. distance: level.distance
  22810. });
  22811. }
  22812. return data;
  22813. }
  22814. }
  22815. const _basePosition = /*@__PURE__*/new Vector3();
  22816. const _skinIndex = /*@__PURE__*/new Vector4();
  22817. const _skinWeight = /*@__PURE__*/new Vector4();
  22818. const _vector$5 = /*@__PURE__*/new Vector3();
  22819. const _matrix = /*@__PURE__*/new Matrix4();
  22820. class SkinnedMesh extends Mesh {
  22821. constructor(geometry, material) {
  22822. super(geometry, material);
  22823. this.type = 'SkinnedMesh';
  22824. this.bindMode = 'attached';
  22825. this.bindMatrix = new Matrix4();
  22826. this.bindMatrixInverse = new Matrix4();
  22827. }
  22828. copy(source) {
  22829. super.copy(source);
  22830. this.bindMode = source.bindMode;
  22831. this.bindMatrix.copy(source.bindMatrix);
  22832. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  22833. this.skeleton = source.skeleton;
  22834. return this;
  22835. }
  22836. bind(skeleton, bindMatrix) {
  22837. this.skeleton = skeleton;
  22838. if (bindMatrix === undefined) {
  22839. this.updateMatrixWorld(true);
  22840. this.skeleton.calculateInverses();
  22841. bindMatrix = this.matrixWorld;
  22842. }
  22843. this.bindMatrix.copy(bindMatrix);
  22844. this.bindMatrixInverse.copy(bindMatrix).invert();
  22845. }
  22846. pose() {
  22847. this.skeleton.pose();
  22848. }
  22849. normalizeSkinWeights() {
  22850. const vector = new Vector4();
  22851. const skinWeight = this.geometry.attributes.skinWeight;
  22852. for (let i = 0, l = skinWeight.count; i < l; i++) {
  22853. vector.x = skinWeight.getX(i);
  22854. vector.y = skinWeight.getY(i);
  22855. vector.z = skinWeight.getZ(i);
  22856. vector.w = skinWeight.getW(i);
  22857. const scale = 1.0 / vector.manhattanLength();
  22858. if (scale !== Infinity) {
  22859. vector.multiplyScalar(scale);
  22860. } else {
  22861. vector.set(1, 0, 0, 0); // do something reasonable
  22862. }
  22863. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  22864. }
  22865. }
  22866. updateMatrixWorld(force) {
  22867. super.updateMatrixWorld(force);
  22868. if (this.bindMode === 'attached') {
  22869. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  22870. } else if (this.bindMode === 'detached') {
  22871. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  22872. } else {
  22873. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  22874. }
  22875. }
  22876. boneTransform(index, target) {
  22877. const skeleton = this.skeleton;
  22878. const geometry = this.geometry;
  22879. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  22880. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  22881. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  22882. target.set(0, 0, 0);
  22883. for (let i = 0; i < 4; i++) {
  22884. const weight = _skinWeight.getComponent(i);
  22885. if (weight !== 0) {
  22886. const boneIndex = _skinIndex.getComponent(i);
  22887. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  22888. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  22889. }
  22890. }
  22891. return target.applyMatrix4(this.bindMatrixInverse);
  22892. }
  22893. }
  22894. SkinnedMesh.prototype.isSkinnedMesh = true;
  22895. class Bone extends Object3D {
  22896. constructor() {
  22897. super();
  22898. this.type = 'Bone';
  22899. }
  22900. }
  22901. Bone.prototype.isBone = true;
  22902. class DataTexture extends Texture {
  22903. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  22904. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  22905. this.image = {
  22906. data: data,
  22907. width: width,
  22908. height: height
  22909. };
  22910. this.magFilter = magFilter;
  22911. this.minFilter = minFilter;
  22912. this.generateMipmaps = false;
  22913. this.flipY = false;
  22914. this.unpackAlignment = 1;
  22915. this.needsUpdate = true;
  22916. }
  22917. }
  22918. DataTexture.prototype.isDataTexture = true;
  22919. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  22920. const _identityMatrix = /*@__PURE__*/new Matrix4();
  22921. class Skeleton {
  22922. constructor(bones = [], boneInverses = []) {
  22923. this.uuid = generateUUID();
  22924. this.bones = bones.slice(0);
  22925. this.boneInverses = boneInverses;
  22926. this.boneMatrices = null;
  22927. this.boneTexture = null;
  22928. this.boneTextureSize = 0;
  22929. this.frame = -1;
  22930. this.init();
  22931. }
  22932. init() {
  22933. const bones = this.bones;
  22934. const boneInverses = this.boneInverses;
  22935. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  22936. if (boneInverses.length === 0) {
  22937. this.calculateInverses();
  22938. } else {
  22939. // handle special case
  22940. if (bones.length !== boneInverses.length) {
  22941. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  22942. this.boneInverses = [];
  22943. for (let i = 0, il = this.bones.length; i < il; i++) {
  22944. this.boneInverses.push(new Matrix4());
  22945. }
  22946. }
  22947. }
  22948. }
  22949. calculateInverses() {
  22950. this.boneInverses.length = 0;
  22951. for (let i = 0, il = this.bones.length; i < il; i++) {
  22952. const inverse = new Matrix4();
  22953. if (this.bones[i]) {
  22954. inverse.copy(this.bones[i].matrixWorld).invert();
  22955. }
  22956. this.boneInverses.push(inverse);
  22957. }
  22958. }
  22959. pose() {
  22960. // recover the bind-time world matrices
  22961. for (let i = 0, il = this.bones.length; i < il; i++) {
  22962. const bone = this.bones[i];
  22963. if (bone) {
  22964. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  22965. }
  22966. } // compute the local matrices, positions, rotations and scales
  22967. for (let i = 0, il = this.bones.length; i < il; i++) {
  22968. const bone = this.bones[i];
  22969. if (bone) {
  22970. if (bone.parent && bone.parent.isBone) {
  22971. bone.matrix.copy(bone.parent.matrixWorld).invert();
  22972. bone.matrix.multiply(bone.matrixWorld);
  22973. } else {
  22974. bone.matrix.copy(bone.matrixWorld);
  22975. }
  22976. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  22977. }
  22978. }
  22979. }
  22980. update() {
  22981. const bones = this.bones;
  22982. const boneInverses = this.boneInverses;
  22983. const boneMatrices = this.boneMatrices;
  22984. const boneTexture = this.boneTexture; // flatten bone matrices to array
  22985. for (let i = 0, il = bones.length; i < il; i++) {
  22986. // compute the offset between the current and the original transform
  22987. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  22988. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  22989. _offsetMatrix.toArray(boneMatrices, i * 16);
  22990. }
  22991. if (boneTexture !== null) {
  22992. boneTexture.needsUpdate = true;
  22993. }
  22994. }
  22995. clone() {
  22996. return new Skeleton(this.bones, this.boneInverses);
  22997. }
  22998. computeBoneTexture() {
  22999. // layout (1 matrix = 4 pixels)
  23000. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  23001. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  23002. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  23003. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  23004. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  23005. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  23006. size = ceilPowerOfTwo(size);
  23007. size = Math.max(size, 4);
  23008. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  23009. boneMatrices.set(this.boneMatrices); // copy current values
  23010. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  23011. this.boneMatrices = boneMatrices;
  23012. this.boneTexture = boneTexture;
  23013. this.boneTextureSize = size;
  23014. return this;
  23015. }
  23016. getBoneByName(name) {
  23017. for (let i = 0, il = this.bones.length; i < il; i++) {
  23018. const bone = this.bones[i];
  23019. if (bone.name === name) {
  23020. return bone;
  23021. }
  23022. }
  23023. return undefined;
  23024. }
  23025. dispose() {
  23026. if (this.boneTexture !== null) {
  23027. this.boneTexture.dispose();
  23028. this.boneTexture = null;
  23029. }
  23030. }
  23031. fromJSON(json, bones) {
  23032. this.uuid = json.uuid;
  23033. for (let i = 0, l = json.bones.length; i < l; i++) {
  23034. const uuid = json.bones[i];
  23035. let bone = bones[uuid];
  23036. if (bone === undefined) {
  23037. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  23038. bone = new Bone();
  23039. }
  23040. this.bones.push(bone);
  23041. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  23042. }
  23043. this.init();
  23044. return this;
  23045. }
  23046. toJSON() {
  23047. const data = {
  23048. metadata: {
  23049. version: 4.5,
  23050. type: 'Skeleton',
  23051. generator: 'Skeleton.toJSON'
  23052. },
  23053. bones: [],
  23054. boneInverses: []
  23055. };
  23056. data.uuid = this.uuid;
  23057. const bones = this.bones;
  23058. const boneInverses = this.boneInverses;
  23059. for (let i = 0, l = bones.length; i < l; i++) {
  23060. const bone = bones[i];
  23061. data.bones.push(bone.uuid);
  23062. const boneInverse = boneInverses[i];
  23063. data.boneInverses.push(boneInverse.toArray());
  23064. }
  23065. return data;
  23066. }
  23067. }
  23068. class InstancedBufferAttribute extends BufferAttribute {
  23069. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  23070. if (typeof normalized === 'number') {
  23071. meshPerAttribute = normalized;
  23072. normalized = false;
  23073. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23074. }
  23075. super(array, itemSize, normalized);
  23076. this.meshPerAttribute = meshPerAttribute;
  23077. }
  23078. copy(source) {
  23079. super.copy(source);
  23080. this.meshPerAttribute = source.meshPerAttribute;
  23081. return this;
  23082. }
  23083. toJSON() {
  23084. const data = super.toJSON();
  23085. data.meshPerAttribute = this.meshPerAttribute;
  23086. data.isInstancedBufferAttribute = true;
  23087. return data;
  23088. }
  23089. }
  23090. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23091. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  23092. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  23093. const _instanceIntersects = [];
  23094. const _mesh = /*@__PURE__*/new Mesh();
  23095. class InstancedMesh extends Mesh {
  23096. constructor(geometry, material, count) {
  23097. super(geometry, material);
  23098. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  23099. this.instanceColor = null;
  23100. this.count = count;
  23101. this.frustumCulled = false;
  23102. }
  23103. copy(source) {
  23104. super.copy(source);
  23105. this.instanceMatrix.copy(source.instanceMatrix);
  23106. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  23107. this.count = source.count;
  23108. return this;
  23109. }
  23110. getColorAt(index, color) {
  23111. color.fromArray(this.instanceColor.array, index * 3);
  23112. }
  23113. getMatrixAt(index, matrix) {
  23114. matrix.fromArray(this.instanceMatrix.array, index * 16);
  23115. }
  23116. raycast(raycaster, intersects) {
  23117. const matrixWorld = this.matrixWorld;
  23118. const raycastTimes = this.count;
  23119. _mesh.geometry = this.geometry;
  23120. _mesh.material = this.material;
  23121. if (_mesh.material === undefined) return;
  23122. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  23123. // calculate the world matrix for each instance
  23124. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  23125. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  23126. _mesh.matrixWorld = _instanceWorldMatrix;
  23127. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  23128. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  23129. const intersect = _instanceIntersects[i];
  23130. intersect.instanceId = instanceId;
  23131. intersect.object = this;
  23132. intersects.push(intersect);
  23133. }
  23134. _instanceIntersects.length = 0;
  23135. }
  23136. }
  23137. setColorAt(index, color) {
  23138. if (this.instanceColor === null) {
  23139. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  23140. }
  23141. color.toArray(this.instanceColor.array, index * 3);
  23142. }
  23143. setMatrixAt(index, matrix) {
  23144. matrix.toArray(this.instanceMatrix.array, index * 16);
  23145. }
  23146. updateMorphTargets() {}
  23147. dispose() {
  23148. this.dispatchEvent({
  23149. type: 'dispose'
  23150. });
  23151. }
  23152. }
  23153. InstancedMesh.prototype.isInstancedMesh = true;
  23154. /**
  23155. * parameters = {
  23156. * color: <hex>,
  23157. * opacity: <float>,
  23158. *
  23159. * linewidth: <float>,
  23160. * linecap: "round",
  23161. * linejoin: "round"
  23162. * }
  23163. */
  23164. class LineBasicMaterial extends Material {
  23165. constructor(parameters) {
  23166. super();
  23167. this.type = 'LineBasicMaterial';
  23168. this.color = new Color(0xffffff);
  23169. this.linewidth = 1;
  23170. this.linecap = 'round';
  23171. this.linejoin = 'round';
  23172. this.setValues(parameters);
  23173. }
  23174. copy(source) {
  23175. super.copy(source);
  23176. this.color.copy(source.color);
  23177. this.linewidth = source.linewidth;
  23178. this.linecap = source.linecap;
  23179. this.linejoin = source.linejoin;
  23180. return this;
  23181. }
  23182. }
  23183. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  23184. const _start$1 = /*@__PURE__*/new Vector3();
  23185. const _end$1 = /*@__PURE__*/new Vector3();
  23186. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  23187. const _ray$1 = /*@__PURE__*/new Ray();
  23188. const _sphere$1 = /*@__PURE__*/new Sphere();
  23189. class Line extends Object3D {
  23190. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  23191. super();
  23192. this.type = 'Line';
  23193. this.geometry = geometry;
  23194. this.material = material;
  23195. this.updateMorphTargets();
  23196. }
  23197. copy(source) {
  23198. super.copy(source);
  23199. this.material = source.material;
  23200. this.geometry = source.geometry;
  23201. return this;
  23202. }
  23203. computeLineDistances() {
  23204. const geometry = this.geometry;
  23205. if (geometry.isBufferGeometry) {
  23206. // we assume non-indexed geometry
  23207. if (geometry.index === null) {
  23208. const positionAttribute = geometry.attributes.position;
  23209. const lineDistances = [0];
  23210. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  23211. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  23212. _end$1.fromBufferAttribute(positionAttribute, i);
  23213. lineDistances[i] = lineDistances[i - 1];
  23214. lineDistances[i] += _start$1.distanceTo(_end$1);
  23215. }
  23216. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  23217. } else {
  23218. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  23219. }
  23220. } else if (geometry.isGeometry) {
  23221. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23222. }
  23223. return this;
  23224. }
  23225. raycast(raycaster, intersects) {
  23226. const geometry = this.geometry;
  23227. const matrixWorld = this.matrixWorld;
  23228. const threshold = raycaster.params.Line.threshold;
  23229. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  23230. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  23231. _sphere$1.copy(geometry.boundingSphere);
  23232. _sphere$1.applyMatrix4(matrixWorld);
  23233. _sphere$1.radius += threshold;
  23234. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  23235. _inverseMatrix$1.copy(matrixWorld).invert();
  23236. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  23237. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  23238. const localThresholdSq = localThreshold * localThreshold;
  23239. const vStart = new Vector3();
  23240. const vEnd = new Vector3();
  23241. const interSegment = new Vector3();
  23242. const interRay = new Vector3();
  23243. const step = this.isLineSegments ? 2 : 1;
  23244. if (geometry.isBufferGeometry) {
  23245. const index = geometry.index;
  23246. const attributes = geometry.attributes;
  23247. const positionAttribute = attributes.position;
  23248. if (index !== null) {
  23249. const start = Math.max(0, drawRange.start);
  23250. const end = Math.min(index.count, drawRange.start + drawRange.count);
  23251. for (let i = start, l = end - 1; i < l; i += step) {
  23252. const a = index.getX(i);
  23253. const b = index.getX(i + 1);
  23254. vStart.fromBufferAttribute(positionAttribute, a);
  23255. vEnd.fromBufferAttribute(positionAttribute, b);
  23256. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  23257. if (distSq > localThresholdSq) continue;
  23258. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  23259. const distance = raycaster.ray.origin.distanceTo(interRay);
  23260. if (distance < raycaster.near || distance > raycaster.far) continue;
  23261. intersects.push({
  23262. distance: distance,
  23263. // What do we want? intersection point on the ray or on the segment??
  23264. // point: raycaster.ray.at( distance ),
  23265. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  23266. index: i,
  23267. face: null,
  23268. faceIndex: null,
  23269. object: this
  23270. });
  23271. }
  23272. } else {
  23273. const start = Math.max(0, drawRange.start);
  23274. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  23275. for (let i = start, l = end - 1; i < l; i += step) {
  23276. vStart.fromBufferAttribute(positionAttribute, i);
  23277. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  23278. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  23279. if (distSq > localThresholdSq) continue;
  23280. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  23281. const distance = raycaster.ray.origin.distanceTo(interRay);
  23282. if (distance < raycaster.near || distance > raycaster.far) continue;
  23283. intersects.push({
  23284. distance: distance,
  23285. // What do we want? intersection point on the ray or on the segment??
  23286. // point: raycaster.ray.at( distance ),
  23287. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  23288. index: i,
  23289. face: null,
  23290. faceIndex: null,
  23291. object: this
  23292. });
  23293. }
  23294. }
  23295. } else if (geometry.isGeometry) {
  23296. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23297. }
  23298. }
  23299. updateMorphTargets() {
  23300. const geometry = this.geometry;
  23301. if (geometry.isBufferGeometry) {
  23302. const morphAttributes = geometry.morphAttributes;
  23303. const keys = Object.keys(morphAttributes);
  23304. if (keys.length > 0) {
  23305. const morphAttribute = morphAttributes[keys[0]];
  23306. if (morphAttribute !== undefined) {
  23307. this.morphTargetInfluences = [];
  23308. this.morphTargetDictionary = {};
  23309. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  23310. const name = morphAttribute[m].name || String(m);
  23311. this.morphTargetInfluences.push(0);
  23312. this.morphTargetDictionary[name] = m;
  23313. }
  23314. }
  23315. }
  23316. } else {
  23317. const morphTargets = geometry.morphTargets;
  23318. if (morphTargets !== undefined && morphTargets.length > 0) {
  23319. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  23320. }
  23321. }
  23322. }
  23323. }
  23324. Line.prototype.isLine = true;
  23325. const _start = /*@__PURE__*/new Vector3();
  23326. const _end = /*@__PURE__*/new Vector3();
  23327. class LineSegments extends Line {
  23328. constructor(geometry, material) {
  23329. super(geometry, material);
  23330. this.type = 'LineSegments';
  23331. }
  23332. computeLineDistances() {
  23333. const geometry = this.geometry;
  23334. if (geometry.isBufferGeometry) {
  23335. // we assume non-indexed geometry
  23336. if (geometry.index === null) {
  23337. const positionAttribute = geometry.attributes.position;
  23338. const lineDistances = [];
  23339. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  23340. _start.fromBufferAttribute(positionAttribute, i);
  23341. _end.fromBufferAttribute(positionAttribute, i + 1);
  23342. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  23343. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  23344. }
  23345. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  23346. } else {
  23347. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  23348. }
  23349. } else if (geometry.isGeometry) {
  23350. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23351. }
  23352. return this;
  23353. }
  23354. }
  23355. LineSegments.prototype.isLineSegments = true;
  23356. class LineLoop extends Line {
  23357. constructor(geometry, material) {
  23358. super(geometry, material);
  23359. this.type = 'LineLoop';
  23360. }
  23361. }
  23362. LineLoop.prototype.isLineLoop = true;
  23363. /**
  23364. * parameters = {
  23365. * color: <hex>,
  23366. * opacity: <float>,
  23367. * map: new THREE.Texture( <Image> ),
  23368. * alphaMap: new THREE.Texture( <Image> ),
  23369. *
  23370. * size: <float>,
  23371. * sizeAttenuation: <bool>
  23372. *
  23373. * }
  23374. */
  23375. class PointsMaterial extends Material {
  23376. constructor(parameters) {
  23377. super();
  23378. this.type = 'PointsMaterial';
  23379. this.color = new Color(0xffffff);
  23380. this.map = null;
  23381. this.alphaMap = null;
  23382. this.size = 1;
  23383. this.sizeAttenuation = true;
  23384. this.setValues(parameters);
  23385. }
  23386. copy(source) {
  23387. super.copy(source);
  23388. this.color.copy(source.color);
  23389. this.map = source.map;
  23390. this.alphaMap = source.alphaMap;
  23391. this.size = source.size;
  23392. this.sizeAttenuation = source.sizeAttenuation;
  23393. return this;
  23394. }
  23395. }
  23396. PointsMaterial.prototype.isPointsMaterial = true;
  23397. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  23398. const _ray = /*@__PURE__*/new Ray();
  23399. const _sphere = /*@__PURE__*/new Sphere();
  23400. const _position$2 = /*@__PURE__*/new Vector3();
  23401. class Points extends Object3D {
  23402. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  23403. super();
  23404. this.type = 'Points';
  23405. this.geometry = geometry;
  23406. this.material = material;
  23407. this.updateMorphTargets();
  23408. }
  23409. copy(source) {
  23410. super.copy(source);
  23411. this.material = source.material;
  23412. this.geometry = source.geometry;
  23413. return this;
  23414. }
  23415. raycast(raycaster, intersects) {
  23416. const geometry = this.geometry;
  23417. const matrixWorld = this.matrixWorld;
  23418. const threshold = raycaster.params.Points.threshold;
  23419. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  23420. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  23421. _sphere.copy(geometry.boundingSphere);
  23422. _sphere.applyMatrix4(matrixWorld);
  23423. _sphere.radius += threshold;
  23424. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  23425. _inverseMatrix.copy(matrixWorld).invert();
  23426. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  23427. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  23428. const localThresholdSq = localThreshold * localThreshold;
  23429. if (geometry.isBufferGeometry) {
  23430. const index = geometry.index;
  23431. const attributes = geometry.attributes;
  23432. const positionAttribute = attributes.position;
  23433. if (index !== null) {
  23434. const start = Math.max(0, drawRange.start);
  23435. const end = Math.min(index.count, drawRange.start + drawRange.count);
  23436. for (let i = start, il = end; i < il; i++) {
  23437. const a = index.getX(i);
  23438. _position$2.fromBufferAttribute(positionAttribute, a);
  23439. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  23440. }
  23441. } else {
  23442. const start = Math.max(0, drawRange.start);
  23443. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  23444. for (let i = start, l = end; i < l; i++) {
  23445. _position$2.fromBufferAttribute(positionAttribute, i);
  23446. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  23447. }
  23448. }
  23449. } else {
  23450. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23451. }
  23452. }
  23453. updateMorphTargets() {
  23454. const geometry = this.geometry;
  23455. if (geometry.isBufferGeometry) {
  23456. const morphAttributes = geometry.morphAttributes;
  23457. const keys = Object.keys(morphAttributes);
  23458. if (keys.length > 0) {
  23459. const morphAttribute = morphAttributes[keys[0]];
  23460. if (morphAttribute !== undefined) {
  23461. this.morphTargetInfluences = [];
  23462. this.morphTargetDictionary = {};
  23463. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  23464. const name = morphAttribute[m].name || String(m);
  23465. this.morphTargetInfluences.push(0);
  23466. this.morphTargetDictionary[name] = m;
  23467. }
  23468. }
  23469. }
  23470. } else {
  23471. const morphTargets = geometry.morphTargets;
  23472. if (morphTargets !== undefined && morphTargets.length > 0) {
  23473. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  23474. }
  23475. }
  23476. }
  23477. }
  23478. Points.prototype.isPoints = true;
  23479. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  23480. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  23481. if (rayPointDistanceSq < localThresholdSq) {
  23482. const intersectPoint = new Vector3();
  23483. _ray.closestPointToPoint(point, intersectPoint);
  23484. intersectPoint.applyMatrix4(matrixWorld);
  23485. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  23486. if (distance < raycaster.near || distance > raycaster.far) return;
  23487. intersects.push({
  23488. distance: distance,
  23489. distanceToRay: Math.sqrt(rayPointDistanceSq),
  23490. point: intersectPoint,
  23491. index: index,
  23492. face: null,
  23493. object: object
  23494. });
  23495. }
  23496. }
  23497. class VideoTexture extends Texture {
  23498. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23499. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23500. this.format = format !== undefined ? format : RGBFormat;
  23501. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  23502. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  23503. this.generateMipmaps = false;
  23504. const scope = this;
  23505. function updateVideo() {
  23506. scope.needsUpdate = true;
  23507. video.requestVideoFrameCallback(updateVideo);
  23508. }
  23509. if ('requestVideoFrameCallback' in video) {
  23510. video.requestVideoFrameCallback(updateVideo);
  23511. }
  23512. }
  23513. clone() {
  23514. return new this.constructor(this.image).copy(this);
  23515. }
  23516. update() {
  23517. const video = this.image;
  23518. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  23519. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  23520. this.needsUpdate = true;
  23521. }
  23522. }
  23523. }
  23524. VideoTexture.prototype.isVideoTexture = true;
  23525. class CompressedTexture extends Texture {
  23526. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  23527. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  23528. this.image = {
  23529. width: width,
  23530. height: height
  23531. };
  23532. this.mipmaps = mipmaps; // no flipping for cube textures
  23533. // (also flipping doesn't work for compressed textures )
  23534. this.flipY = false; // can't generate mipmaps for compressed textures
  23535. // mips must be embedded in DDS files
  23536. this.generateMipmaps = false;
  23537. }
  23538. }
  23539. CompressedTexture.prototype.isCompressedTexture = true;
  23540. class CanvasTexture extends Texture {
  23541. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23542. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23543. this.needsUpdate = true;
  23544. }
  23545. }
  23546. CanvasTexture.prototype.isCanvasTexture = true;
  23547. class DepthTexture extends Texture {
  23548. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  23549. format = format !== undefined ? format : DepthFormat;
  23550. if (format !== DepthFormat && format !== DepthStencilFormat) {
  23551. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  23552. }
  23553. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  23554. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  23555. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23556. this.image = {
  23557. width: width,
  23558. height: height
  23559. };
  23560. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  23561. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  23562. this.flipY = false;
  23563. this.generateMipmaps = false;
  23564. }
  23565. }
  23566. DepthTexture.prototype.isDepthTexture = true;
  23567. class CircleGeometry extends BufferGeometry {
  23568. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  23569. super();
  23570. this.type = 'CircleGeometry';
  23571. this.parameters = {
  23572. radius: radius,
  23573. segments: segments,
  23574. thetaStart: thetaStart,
  23575. thetaLength: thetaLength
  23576. };
  23577. segments = Math.max(3, segments); // buffers
  23578. const indices = [];
  23579. const vertices = [];
  23580. const normals = [];
  23581. const uvs = []; // helper variables
  23582. const vertex = new Vector3();
  23583. const uv = new Vector2(); // center point
  23584. vertices.push(0, 0, 0);
  23585. normals.push(0, 0, 1);
  23586. uvs.push(0.5, 0.5);
  23587. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  23588. const segment = thetaStart + s / segments * thetaLength; // vertex
  23589. vertex.x = radius * Math.cos(segment);
  23590. vertex.y = radius * Math.sin(segment);
  23591. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23592. normals.push(0, 0, 1); // uvs
  23593. uv.x = (vertices[i] / radius + 1) / 2;
  23594. uv.y = (vertices[i + 1] / radius + 1) / 2;
  23595. uvs.push(uv.x, uv.y);
  23596. } // indices
  23597. for (let i = 1; i <= segments; i++) {
  23598. indices.push(i, i + 1, 0);
  23599. } // build geometry
  23600. this.setIndex(indices);
  23601. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23602. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23603. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23604. }
  23605. static fromJSON(data) {
  23606. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  23607. }
  23608. }
  23609. class CylinderGeometry extends BufferGeometry {
  23610. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  23611. super();
  23612. this.type = 'CylinderGeometry';
  23613. this.parameters = {
  23614. radiusTop: radiusTop,
  23615. radiusBottom: radiusBottom,
  23616. height: height,
  23617. radialSegments: radialSegments,
  23618. heightSegments: heightSegments,
  23619. openEnded: openEnded,
  23620. thetaStart: thetaStart,
  23621. thetaLength: thetaLength
  23622. };
  23623. const scope = this;
  23624. radialSegments = Math.floor(radialSegments);
  23625. heightSegments = Math.floor(heightSegments); // buffers
  23626. const indices = [];
  23627. const vertices = [];
  23628. const normals = [];
  23629. const uvs = []; // helper variables
  23630. let index = 0;
  23631. const indexArray = [];
  23632. const halfHeight = height / 2;
  23633. let groupStart = 0; // generate geometry
  23634. generateTorso();
  23635. if (openEnded === false) {
  23636. if (radiusTop > 0) generateCap(true);
  23637. if (radiusBottom > 0) generateCap(false);
  23638. } // build geometry
  23639. this.setIndex(indices);
  23640. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23641. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23642. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23643. function generateTorso() {
  23644. const normal = new Vector3();
  23645. const vertex = new Vector3();
  23646. let groupCount = 0; // this will be used to calculate the normal
  23647. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  23648. for (let y = 0; y <= heightSegments; y++) {
  23649. const indexRow = [];
  23650. const v = y / heightSegments; // calculate the radius of the current row
  23651. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  23652. for (let x = 0; x <= radialSegments; x++) {
  23653. const u = x / radialSegments;
  23654. const theta = u * thetaLength + thetaStart;
  23655. const sinTheta = Math.sin(theta);
  23656. const cosTheta = Math.cos(theta); // vertex
  23657. vertex.x = radius * sinTheta;
  23658. vertex.y = -v * height + halfHeight;
  23659. vertex.z = radius * cosTheta;
  23660. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23661. normal.set(sinTheta, slope, cosTheta).normalize();
  23662. normals.push(normal.x, normal.y, normal.z); // uv
  23663. uvs.push(u, 1 - v); // save index of vertex in respective row
  23664. indexRow.push(index++);
  23665. } // now save vertices of the row in our index array
  23666. indexArray.push(indexRow);
  23667. } // generate indices
  23668. for (let x = 0; x < radialSegments; x++) {
  23669. for (let y = 0; y < heightSegments; y++) {
  23670. // we use the index array to access the correct indices
  23671. const a = indexArray[y][x];
  23672. const b = indexArray[y + 1][x];
  23673. const c = indexArray[y + 1][x + 1];
  23674. const d = indexArray[y][x + 1]; // faces
  23675. indices.push(a, b, d);
  23676. indices.push(b, c, d); // update group counter
  23677. groupCount += 6;
  23678. }
  23679. } // add a group to the geometry. this will ensure multi material support
  23680. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  23681. groupStart += groupCount;
  23682. }
  23683. function generateCap(top) {
  23684. // save the index of the first center vertex
  23685. const centerIndexStart = index;
  23686. const uv = new Vector2();
  23687. const vertex = new Vector3();
  23688. let groupCount = 0;
  23689. const radius = top === true ? radiusTop : radiusBottom;
  23690. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  23691. // because the geometry needs one set of uvs per face,
  23692. // we must generate a center vertex per face/segment
  23693. for (let x = 1; x <= radialSegments; x++) {
  23694. // vertex
  23695. vertices.push(0, halfHeight * sign, 0); // normal
  23696. normals.push(0, sign, 0); // uv
  23697. uvs.push(0.5, 0.5); // increase index
  23698. index++;
  23699. } // save the index of the last center vertex
  23700. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  23701. for (let x = 0; x <= radialSegments; x++) {
  23702. const u = x / radialSegments;
  23703. const theta = u * thetaLength + thetaStart;
  23704. const cosTheta = Math.cos(theta);
  23705. const sinTheta = Math.sin(theta); // vertex
  23706. vertex.x = radius * sinTheta;
  23707. vertex.y = halfHeight * sign;
  23708. vertex.z = radius * cosTheta;
  23709. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23710. normals.push(0, sign, 0); // uv
  23711. uv.x = cosTheta * 0.5 + 0.5;
  23712. uv.y = sinTheta * 0.5 * sign + 0.5;
  23713. uvs.push(uv.x, uv.y); // increase index
  23714. index++;
  23715. } // generate indices
  23716. for (let x = 0; x < radialSegments; x++) {
  23717. const c = centerIndexStart + x;
  23718. const i = centerIndexEnd + x;
  23719. if (top === true) {
  23720. // face top
  23721. indices.push(i, i + 1, c);
  23722. } else {
  23723. // face bottom
  23724. indices.push(i + 1, i, c);
  23725. }
  23726. groupCount += 3;
  23727. } // add a group to the geometry. this will ensure multi material support
  23728. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  23729. groupStart += groupCount;
  23730. }
  23731. }
  23732. static fromJSON(data) {
  23733. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23734. }
  23735. }
  23736. class ConeGeometry extends CylinderGeometry {
  23737. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  23738. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  23739. this.type = 'ConeGeometry';
  23740. this.parameters = {
  23741. radius: radius,
  23742. height: height,
  23743. radialSegments: radialSegments,
  23744. heightSegments: heightSegments,
  23745. openEnded: openEnded,
  23746. thetaStart: thetaStart,
  23747. thetaLength: thetaLength
  23748. };
  23749. }
  23750. static fromJSON(data) {
  23751. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23752. }
  23753. }
  23754. class PolyhedronGeometry extends BufferGeometry {
  23755. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  23756. super();
  23757. this.type = 'PolyhedronGeometry';
  23758. this.parameters = {
  23759. vertices: vertices,
  23760. indices: indices,
  23761. radius: radius,
  23762. detail: detail
  23763. }; // default buffer data
  23764. const vertexBuffer = [];
  23765. const uvBuffer = []; // the subdivision creates the vertex buffer data
  23766. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  23767. applyRadius(radius); // finally, create the uv data
  23768. generateUVs(); // build non-indexed geometry
  23769. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  23770. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  23771. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  23772. if (detail === 0) {
  23773. this.computeVertexNormals(); // flat normals
  23774. } else {
  23775. this.normalizeNormals(); // smooth normals
  23776. } // helper functions
  23777. function subdivide(detail) {
  23778. const a = new Vector3();
  23779. const b = new Vector3();
  23780. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  23781. for (let i = 0; i < indices.length; i += 3) {
  23782. // get the vertices of the face
  23783. getVertexByIndex(indices[i + 0], a);
  23784. getVertexByIndex(indices[i + 1], b);
  23785. getVertexByIndex(indices[i + 2], c); // perform subdivision
  23786. subdivideFace(a, b, c, detail);
  23787. }
  23788. }
  23789. function subdivideFace(a, b, c, detail) {
  23790. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  23791. const v = []; // construct all of the vertices for this subdivision
  23792. for (let i = 0; i <= cols; i++) {
  23793. v[i] = [];
  23794. const aj = a.clone().lerp(c, i / cols);
  23795. const bj = b.clone().lerp(c, i / cols);
  23796. const rows = cols - i;
  23797. for (let j = 0; j <= rows; j++) {
  23798. if (j === 0 && i === cols) {
  23799. v[i][j] = aj;
  23800. } else {
  23801. v[i][j] = aj.clone().lerp(bj, j / rows);
  23802. }
  23803. }
  23804. } // construct all of the faces
  23805. for (let i = 0; i < cols; i++) {
  23806. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  23807. const k = Math.floor(j / 2);
  23808. if (j % 2 === 0) {
  23809. pushVertex(v[i][k + 1]);
  23810. pushVertex(v[i + 1][k]);
  23811. pushVertex(v[i][k]);
  23812. } else {
  23813. pushVertex(v[i][k + 1]);
  23814. pushVertex(v[i + 1][k + 1]);
  23815. pushVertex(v[i + 1][k]);
  23816. }
  23817. }
  23818. }
  23819. }
  23820. function applyRadius(radius) {
  23821. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  23822. for (let i = 0; i < vertexBuffer.length; i += 3) {
  23823. vertex.x = vertexBuffer[i + 0];
  23824. vertex.y = vertexBuffer[i + 1];
  23825. vertex.z = vertexBuffer[i + 2];
  23826. vertex.normalize().multiplyScalar(radius);
  23827. vertexBuffer[i + 0] = vertex.x;
  23828. vertexBuffer[i + 1] = vertex.y;
  23829. vertexBuffer[i + 2] = vertex.z;
  23830. }
  23831. }
  23832. function generateUVs() {
  23833. const vertex = new Vector3();
  23834. for (let i = 0; i < vertexBuffer.length; i += 3) {
  23835. vertex.x = vertexBuffer[i + 0];
  23836. vertex.y = vertexBuffer[i + 1];
  23837. vertex.z = vertexBuffer[i + 2];
  23838. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  23839. const v = inclination(vertex) / Math.PI + 0.5;
  23840. uvBuffer.push(u, 1 - v);
  23841. }
  23842. correctUVs();
  23843. correctSeam();
  23844. }
  23845. function correctSeam() {
  23846. // handle case when face straddles the seam, see #3269
  23847. for (let i = 0; i < uvBuffer.length; i += 6) {
  23848. // uv data of a single face
  23849. const x0 = uvBuffer[i + 0];
  23850. const x1 = uvBuffer[i + 2];
  23851. const x2 = uvBuffer[i + 4];
  23852. const max = Math.max(x0, x1, x2);
  23853. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  23854. if (max > 0.9 && min < 0.1) {
  23855. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  23856. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  23857. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  23858. }
  23859. }
  23860. }
  23861. function pushVertex(vertex) {
  23862. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  23863. }
  23864. function getVertexByIndex(index, vertex) {
  23865. const stride = index * 3;
  23866. vertex.x = vertices[stride + 0];
  23867. vertex.y = vertices[stride + 1];
  23868. vertex.z = vertices[stride + 2];
  23869. }
  23870. function correctUVs() {
  23871. const a = new Vector3();
  23872. const b = new Vector3();
  23873. const c = new Vector3();
  23874. const centroid = new Vector3();
  23875. const uvA = new Vector2();
  23876. const uvB = new Vector2();
  23877. const uvC = new Vector2();
  23878. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  23879. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  23880. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  23881. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  23882. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  23883. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  23884. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  23885. centroid.copy(a).add(b).add(c).divideScalar(3);
  23886. const azi = azimuth(centroid);
  23887. correctUV(uvA, j + 0, a, azi);
  23888. correctUV(uvB, j + 2, b, azi);
  23889. correctUV(uvC, j + 4, c, azi);
  23890. }
  23891. }
  23892. function correctUV(uv, stride, vector, azimuth) {
  23893. if (azimuth < 0 && uv.x === 1) {
  23894. uvBuffer[stride] = uv.x - 1;
  23895. }
  23896. if (vector.x === 0 && vector.z === 0) {
  23897. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  23898. }
  23899. } // Angle around the Y axis, counter-clockwise when looking from above.
  23900. function azimuth(vector) {
  23901. return Math.atan2(vector.z, -vector.x);
  23902. } // Angle above the XZ plane.
  23903. function inclination(vector) {
  23904. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  23905. }
  23906. }
  23907. static fromJSON(data) {
  23908. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  23909. }
  23910. }
  23911. class DodecahedronGeometry extends PolyhedronGeometry {
  23912. constructor(radius = 1, detail = 0) {
  23913. const t = (1 + Math.sqrt(5)) / 2;
  23914. const r = 1 / t;
  23915. const vertices = [// (±1, ±1, ±1)
  23916. -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/φ, ±φ)
  23917. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  23918. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  23919. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  23920. const 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];
  23921. super(vertices, indices, radius, detail);
  23922. this.type = 'DodecahedronGeometry';
  23923. this.parameters = {
  23924. radius: radius,
  23925. detail: detail
  23926. };
  23927. }
  23928. static fromJSON(data) {
  23929. return new DodecahedronGeometry(data.radius, data.detail);
  23930. }
  23931. }
  23932. const _v0 = new Vector3();
  23933. const _v1$1 = new Vector3();
  23934. const _normal = new Vector3();
  23935. const _triangle = new Triangle();
  23936. class EdgesGeometry extends BufferGeometry {
  23937. constructor(geometry = null, thresholdAngle = 1) {
  23938. super();
  23939. this.type = 'EdgesGeometry';
  23940. this.parameters = {
  23941. geometry: geometry,
  23942. thresholdAngle: thresholdAngle
  23943. };
  23944. if (geometry !== null) {
  23945. const precisionPoints = 4;
  23946. const precision = Math.pow(10, precisionPoints);
  23947. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  23948. const indexAttr = geometry.getIndex();
  23949. const positionAttr = geometry.getAttribute('position');
  23950. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23951. const indexArr = [0, 0, 0];
  23952. const vertKeys = ['a', 'b', 'c'];
  23953. const hashes = new Array(3);
  23954. const edgeData = {};
  23955. const vertices = [];
  23956. for (let i = 0; i < indexCount; i += 3) {
  23957. if (indexAttr) {
  23958. indexArr[0] = indexAttr.getX(i);
  23959. indexArr[1] = indexAttr.getX(i + 1);
  23960. indexArr[2] = indexAttr.getX(i + 2);
  23961. } else {
  23962. indexArr[0] = i;
  23963. indexArr[1] = i + 1;
  23964. indexArr[2] = i + 2;
  23965. }
  23966. const {
  23967. a,
  23968. b,
  23969. c
  23970. } = _triangle;
  23971. a.fromBufferAttribute(positionAttr, indexArr[0]);
  23972. b.fromBufferAttribute(positionAttr, indexArr[1]);
  23973. c.fromBufferAttribute(positionAttr, indexArr[2]);
  23974. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  23975. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  23976. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  23977. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  23978. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  23979. continue;
  23980. } // iterate over every edge
  23981. for (let j = 0; j < 3; j++) {
  23982. // get the first and next vertex making up the edge
  23983. const jNext = (j + 1) % 3;
  23984. const vecHash0 = hashes[j];
  23985. const vecHash1 = hashes[jNext];
  23986. const v0 = _triangle[vertKeys[j]];
  23987. const v1 = _triangle[vertKeys[jNext]];
  23988. const hash = `${vecHash0}_${vecHash1}`;
  23989. const reverseHash = `${vecHash1}_${vecHash0}`;
  23990. if (reverseHash in edgeData && edgeData[reverseHash]) {
  23991. // if we found a sibling edge add it into the vertex array if
  23992. // it meets the angle threshold and delete the edge from the map.
  23993. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  23994. vertices.push(v0.x, v0.y, v0.z);
  23995. vertices.push(v1.x, v1.y, v1.z);
  23996. }
  23997. edgeData[reverseHash] = null;
  23998. } else if (!(hash in edgeData)) {
  23999. // if we've already got an edge here then skip adding a new one
  24000. edgeData[hash] = {
  24001. index0: indexArr[j],
  24002. index1: indexArr[jNext],
  24003. normal: _normal.clone()
  24004. };
  24005. }
  24006. }
  24007. } // iterate over all remaining, unmatched edges and add them to the vertex array
  24008. for (const key in edgeData) {
  24009. if (edgeData[key]) {
  24010. const {
  24011. index0,
  24012. index1
  24013. } = edgeData[key];
  24014. _v0.fromBufferAttribute(positionAttr, index0);
  24015. _v1$1.fromBufferAttribute(positionAttr, index1);
  24016. vertices.push(_v0.x, _v0.y, _v0.z);
  24017. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  24018. }
  24019. }
  24020. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24021. }
  24022. }
  24023. }
  24024. /**
  24025. * Extensible curve object.
  24026. *
  24027. * Some common of curve methods:
  24028. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  24029. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  24030. * .getPoints(), .getSpacedPoints()
  24031. * .getLength()
  24032. * .updateArcLengths()
  24033. *
  24034. * This following curves inherit from THREE.Curve:
  24035. *
  24036. * -- 2D curves --
  24037. * THREE.ArcCurve
  24038. * THREE.CubicBezierCurve
  24039. * THREE.EllipseCurve
  24040. * THREE.LineCurve
  24041. * THREE.QuadraticBezierCurve
  24042. * THREE.SplineCurve
  24043. *
  24044. * -- 3D curves --
  24045. * THREE.CatmullRomCurve3
  24046. * THREE.CubicBezierCurve3
  24047. * THREE.LineCurve3
  24048. * THREE.QuadraticBezierCurve3
  24049. *
  24050. * A series of curves can be represented as a THREE.CurvePath.
  24051. *
  24052. **/
  24053. class Curve {
  24054. constructor() {
  24055. this.type = 'Curve';
  24056. this.arcLengthDivisions = 200;
  24057. } // Virtual base class method to overwrite and implement in subclasses
  24058. // - t [0 .. 1]
  24059. getPoint() {
  24060. console.warn('THREE.Curve: .getPoint() not implemented.');
  24061. return null;
  24062. } // Get point at relative position in curve according to arc length
  24063. // - u [0 .. 1]
  24064. getPointAt(u, optionalTarget) {
  24065. const t = this.getUtoTmapping(u);
  24066. return this.getPoint(t, optionalTarget);
  24067. } // Get sequence of points using getPoint( t )
  24068. getPoints(divisions = 5) {
  24069. const points = [];
  24070. for (let d = 0; d <= divisions; d++) {
  24071. points.push(this.getPoint(d / divisions));
  24072. }
  24073. return points;
  24074. } // Get sequence of points using getPointAt( u )
  24075. getSpacedPoints(divisions = 5) {
  24076. const points = [];
  24077. for (let d = 0; d <= divisions; d++) {
  24078. points.push(this.getPointAt(d / divisions));
  24079. }
  24080. return points;
  24081. } // Get total curve arc length
  24082. getLength() {
  24083. const lengths = this.getLengths();
  24084. return lengths[lengths.length - 1];
  24085. } // Get list of cumulative segment lengths
  24086. getLengths(divisions = this.arcLengthDivisions) {
  24087. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  24088. return this.cacheArcLengths;
  24089. }
  24090. this.needsUpdate = false;
  24091. const cache = [];
  24092. let current,
  24093. last = this.getPoint(0);
  24094. let sum = 0;
  24095. cache.push(0);
  24096. for (let p = 1; p <= divisions; p++) {
  24097. current = this.getPoint(p / divisions);
  24098. sum += current.distanceTo(last);
  24099. cache.push(sum);
  24100. last = current;
  24101. }
  24102. this.cacheArcLengths = cache;
  24103. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  24104. }
  24105. updateArcLengths() {
  24106. this.needsUpdate = true;
  24107. this.getLengths();
  24108. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  24109. getUtoTmapping(u, distance) {
  24110. const arcLengths = this.getLengths();
  24111. let i = 0;
  24112. const il = arcLengths.length;
  24113. let targetArcLength; // The targeted u distance value to get
  24114. if (distance) {
  24115. targetArcLength = distance;
  24116. } else {
  24117. targetArcLength = u * arcLengths[il - 1];
  24118. } // binary search for the index with largest value smaller than target u distance
  24119. let low = 0,
  24120. high = il - 1,
  24121. comparison;
  24122. while (low <= high) {
  24123. 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
  24124. comparison = arcLengths[i] - targetArcLength;
  24125. if (comparison < 0) {
  24126. low = i + 1;
  24127. } else if (comparison > 0) {
  24128. high = i - 1;
  24129. } else {
  24130. high = i;
  24131. break; // DONE
  24132. }
  24133. }
  24134. i = high;
  24135. if (arcLengths[i] === targetArcLength) {
  24136. return i / (il - 1);
  24137. } // we could get finer grain at lengths, or use simple interpolation between two points
  24138. const lengthBefore = arcLengths[i];
  24139. const lengthAfter = arcLengths[i + 1];
  24140. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  24141. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  24142. const t = (i + segmentFraction) / (il - 1);
  24143. return t;
  24144. } // Returns a unit vector tangent at t
  24145. // In case any sub curve does not implement its tangent derivation,
  24146. // 2 points a small delta apart will be used to find its gradient
  24147. // which seems to give a reasonable approximation
  24148. getTangent(t, optionalTarget) {
  24149. const delta = 0.0001;
  24150. let t1 = t - delta;
  24151. let t2 = t + delta; // Capping in case of danger
  24152. if (t1 < 0) t1 = 0;
  24153. if (t2 > 1) t2 = 1;
  24154. const pt1 = this.getPoint(t1);
  24155. const pt2 = this.getPoint(t2);
  24156. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  24157. tangent.copy(pt2).sub(pt1).normalize();
  24158. return tangent;
  24159. }
  24160. getTangentAt(u, optionalTarget) {
  24161. const t = this.getUtoTmapping(u);
  24162. return this.getTangent(t, optionalTarget);
  24163. }
  24164. computeFrenetFrames(segments, closed) {
  24165. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  24166. const normal = new Vector3();
  24167. const tangents = [];
  24168. const normals = [];
  24169. const binormals = [];
  24170. const vec = new Vector3();
  24171. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  24172. for (let i = 0; i <= segments; i++) {
  24173. const u = i / segments;
  24174. tangents[i] = this.getTangentAt(u, new Vector3());
  24175. } // select an initial normal vector perpendicular to the first tangent vector,
  24176. // and in the direction of the minimum tangent xyz component
  24177. normals[0] = new Vector3();
  24178. binormals[0] = new Vector3();
  24179. let min = Number.MAX_VALUE;
  24180. const tx = Math.abs(tangents[0].x);
  24181. const ty = Math.abs(tangents[0].y);
  24182. const tz = Math.abs(tangents[0].z);
  24183. if (tx <= min) {
  24184. min = tx;
  24185. normal.set(1, 0, 0);
  24186. }
  24187. if (ty <= min) {
  24188. min = ty;
  24189. normal.set(0, 1, 0);
  24190. }
  24191. if (tz <= min) {
  24192. normal.set(0, 0, 1);
  24193. }
  24194. vec.crossVectors(tangents[0], normal).normalize();
  24195. normals[0].crossVectors(tangents[0], vec);
  24196. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  24197. for (let i = 1; i <= segments; i++) {
  24198. normals[i] = normals[i - 1].clone();
  24199. binormals[i] = binormals[i - 1].clone();
  24200. vec.crossVectors(tangents[i - 1], tangents[i]);
  24201. if (vec.length() > Number.EPSILON) {
  24202. vec.normalize();
  24203. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  24204. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  24205. }
  24206. binormals[i].crossVectors(tangents[i], normals[i]);
  24207. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  24208. if (closed === true) {
  24209. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  24210. theta /= segments;
  24211. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  24212. theta = -theta;
  24213. }
  24214. for (let i = 1; i <= segments; i++) {
  24215. // twist a little...
  24216. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  24217. binormals[i].crossVectors(tangents[i], normals[i]);
  24218. }
  24219. }
  24220. return {
  24221. tangents: tangents,
  24222. normals: normals,
  24223. binormals: binormals
  24224. };
  24225. }
  24226. clone() {
  24227. return new this.constructor().copy(this);
  24228. }
  24229. copy(source) {
  24230. this.arcLengthDivisions = source.arcLengthDivisions;
  24231. return this;
  24232. }
  24233. toJSON() {
  24234. const data = {
  24235. metadata: {
  24236. version: 4.5,
  24237. type: 'Curve',
  24238. generator: 'Curve.toJSON'
  24239. }
  24240. };
  24241. data.arcLengthDivisions = this.arcLengthDivisions;
  24242. data.type = this.type;
  24243. return data;
  24244. }
  24245. fromJSON(json) {
  24246. this.arcLengthDivisions = json.arcLengthDivisions;
  24247. return this;
  24248. }
  24249. }
  24250. class EllipseCurve extends Curve {
  24251. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  24252. super();
  24253. this.type = 'EllipseCurve';
  24254. this.aX = aX;
  24255. this.aY = aY;
  24256. this.xRadius = xRadius;
  24257. this.yRadius = yRadius;
  24258. this.aStartAngle = aStartAngle;
  24259. this.aEndAngle = aEndAngle;
  24260. this.aClockwise = aClockwise;
  24261. this.aRotation = aRotation;
  24262. }
  24263. getPoint(t, optionalTarget) {
  24264. const point = optionalTarget || new Vector2();
  24265. const twoPi = Math.PI * 2;
  24266. let deltaAngle = this.aEndAngle - this.aStartAngle;
  24267. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  24268. while (deltaAngle < 0) deltaAngle += twoPi;
  24269. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  24270. if (deltaAngle < Number.EPSILON) {
  24271. if (samePoints) {
  24272. deltaAngle = 0;
  24273. } else {
  24274. deltaAngle = twoPi;
  24275. }
  24276. }
  24277. if (this.aClockwise === true && !samePoints) {
  24278. if (deltaAngle === twoPi) {
  24279. deltaAngle = -twoPi;
  24280. } else {
  24281. deltaAngle = deltaAngle - twoPi;
  24282. }
  24283. }
  24284. const angle = this.aStartAngle + t * deltaAngle;
  24285. let x = this.aX + this.xRadius * Math.cos(angle);
  24286. let y = this.aY + this.yRadius * Math.sin(angle);
  24287. if (this.aRotation !== 0) {
  24288. const cos = Math.cos(this.aRotation);
  24289. const sin = Math.sin(this.aRotation);
  24290. const tx = x - this.aX;
  24291. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  24292. x = tx * cos - ty * sin + this.aX;
  24293. y = tx * sin + ty * cos + this.aY;
  24294. }
  24295. return point.set(x, y);
  24296. }
  24297. copy(source) {
  24298. super.copy(source);
  24299. this.aX = source.aX;
  24300. this.aY = source.aY;
  24301. this.xRadius = source.xRadius;
  24302. this.yRadius = source.yRadius;
  24303. this.aStartAngle = source.aStartAngle;
  24304. this.aEndAngle = source.aEndAngle;
  24305. this.aClockwise = source.aClockwise;
  24306. this.aRotation = source.aRotation;
  24307. return this;
  24308. }
  24309. toJSON() {
  24310. const data = super.toJSON();
  24311. data.aX = this.aX;
  24312. data.aY = this.aY;
  24313. data.xRadius = this.xRadius;
  24314. data.yRadius = this.yRadius;
  24315. data.aStartAngle = this.aStartAngle;
  24316. data.aEndAngle = this.aEndAngle;
  24317. data.aClockwise = this.aClockwise;
  24318. data.aRotation = this.aRotation;
  24319. return data;
  24320. }
  24321. fromJSON(json) {
  24322. super.fromJSON(json);
  24323. this.aX = json.aX;
  24324. this.aY = json.aY;
  24325. this.xRadius = json.xRadius;
  24326. this.yRadius = json.yRadius;
  24327. this.aStartAngle = json.aStartAngle;
  24328. this.aEndAngle = json.aEndAngle;
  24329. this.aClockwise = json.aClockwise;
  24330. this.aRotation = json.aRotation;
  24331. return this;
  24332. }
  24333. }
  24334. EllipseCurve.prototype.isEllipseCurve = true;
  24335. class ArcCurve extends EllipseCurve {
  24336. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  24337. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  24338. this.type = 'ArcCurve';
  24339. }
  24340. }
  24341. ArcCurve.prototype.isArcCurve = true;
  24342. /**
  24343. * Centripetal CatmullRom Curve - which is useful for avoiding
  24344. * cusps and self-intersections in non-uniform catmull rom curves.
  24345. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24346. *
  24347. * curve.type accepts centripetal(default), chordal and catmullrom
  24348. * curve.tension is used for catmullrom which defaults to 0.5
  24349. */
  24350. /*
  24351. Based on an optimized c++ solution in
  24352. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24353. - http://ideone.com/NoEbVM
  24354. This CubicPoly class could be used for reusing some variables and calculations,
  24355. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24356. which can be placed in CurveUtils.
  24357. */
  24358. function CubicPoly() {
  24359. let c0 = 0,
  24360. c1 = 0,
  24361. c2 = 0,
  24362. c3 = 0;
  24363. /*
  24364. * Compute coefficients for a cubic polynomial
  24365. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24366. * such that
  24367. * p(0) = x0, p(1) = x1
  24368. * and
  24369. * p'(0) = t0, p'(1) = t1.
  24370. */
  24371. function init(x0, x1, t0, t1) {
  24372. c0 = x0;
  24373. c1 = t0;
  24374. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  24375. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24376. }
  24377. return {
  24378. initCatmullRom: function (x0, x1, x2, x3, tension) {
  24379. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  24380. },
  24381. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  24382. // compute tangents when parameterized in [t1,t2]
  24383. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  24384. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  24385. t1 *= dt1;
  24386. t2 *= dt1;
  24387. init(x1, x2, t1, t2);
  24388. },
  24389. calc: function (t) {
  24390. const t2 = t * t;
  24391. const t3 = t2 * t;
  24392. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24393. }
  24394. };
  24395. } //
  24396. const tmp = new Vector3();
  24397. const px = new CubicPoly(),
  24398. py = new CubicPoly(),
  24399. pz = new CubicPoly();
  24400. class CatmullRomCurve3 extends Curve {
  24401. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  24402. super();
  24403. this.type = 'CatmullRomCurve3';
  24404. this.points = points;
  24405. this.closed = closed;
  24406. this.curveType = curveType;
  24407. this.tension = tension;
  24408. }
  24409. getPoint(t, optionalTarget = new Vector3()) {
  24410. const point = optionalTarget;
  24411. const points = this.points;
  24412. const l = points.length;
  24413. const p = (l - (this.closed ? 0 : 1)) * t;
  24414. let intPoint = Math.floor(p);
  24415. let weight = p - intPoint;
  24416. if (this.closed) {
  24417. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  24418. } else if (weight === 0 && intPoint === l - 1) {
  24419. intPoint = l - 2;
  24420. weight = 1;
  24421. }
  24422. let p0, p3; // 4 points (p1 & p2 defined below)
  24423. if (this.closed || intPoint > 0) {
  24424. p0 = points[(intPoint - 1) % l];
  24425. } else {
  24426. // extrapolate first point
  24427. tmp.subVectors(points[0], points[1]).add(points[0]);
  24428. p0 = tmp;
  24429. }
  24430. const p1 = points[intPoint % l];
  24431. const p2 = points[(intPoint + 1) % l];
  24432. if (this.closed || intPoint + 2 < l) {
  24433. p3 = points[(intPoint + 2) % l];
  24434. } else {
  24435. // extrapolate last point
  24436. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  24437. p3 = tmp;
  24438. }
  24439. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  24440. // init Centripetal / Chordal Catmull-Rom
  24441. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24442. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  24443. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  24444. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  24445. if (dt1 < 1e-4) dt1 = 1.0;
  24446. if (dt0 < 1e-4) dt0 = dt1;
  24447. if (dt2 < 1e-4) dt2 = dt1;
  24448. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  24449. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  24450. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  24451. } else if (this.curveType === 'catmullrom') {
  24452. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  24453. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  24454. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  24455. }
  24456. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  24457. return point;
  24458. }
  24459. copy(source) {
  24460. super.copy(source);
  24461. this.points = [];
  24462. for (let i = 0, l = source.points.length; i < l; i++) {
  24463. const point = source.points[i];
  24464. this.points.push(point.clone());
  24465. }
  24466. this.closed = source.closed;
  24467. this.curveType = source.curveType;
  24468. this.tension = source.tension;
  24469. return this;
  24470. }
  24471. toJSON() {
  24472. const data = super.toJSON();
  24473. data.points = [];
  24474. for (let i = 0, l = this.points.length; i < l; i++) {
  24475. const point = this.points[i];
  24476. data.points.push(point.toArray());
  24477. }
  24478. data.closed = this.closed;
  24479. data.curveType = this.curveType;
  24480. data.tension = this.tension;
  24481. return data;
  24482. }
  24483. fromJSON(json) {
  24484. super.fromJSON(json);
  24485. this.points = [];
  24486. for (let i = 0, l = json.points.length; i < l; i++) {
  24487. const point = json.points[i];
  24488. this.points.push(new Vector3().fromArray(point));
  24489. }
  24490. this.closed = json.closed;
  24491. this.curveType = json.curveType;
  24492. this.tension = json.tension;
  24493. return this;
  24494. }
  24495. }
  24496. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  24497. /**
  24498. * Bezier Curves formulas obtained from
  24499. * http://en.wikipedia.org/wiki/Bézier_curve
  24500. */
  24501. function CatmullRom(t, p0, p1, p2, p3) {
  24502. const v0 = (p2 - p0) * 0.5;
  24503. const v1 = (p3 - p1) * 0.5;
  24504. const t2 = t * t;
  24505. const t3 = t * t2;
  24506. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  24507. } //
  24508. function QuadraticBezierP0(t, p) {
  24509. const k = 1 - t;
  24510. return k * k * p;
  24511. }
  24512. function QuadraticBezierP1(t, p) {
  24513. return 2 * (1 - t) * t * p;
  24514. }
  24515. function QuadraticBezierP2(t, p) {
  24516. return t * t * p;
  24517. }
  24518. function QuadraticBezier(t, p0, p1, p2) {
  24519. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  24520. } //
  24521. function CubicBezierP0(t, p) {
  24522. const k = 1 - t;
  24523. return k * k * k * p;
  24524. }
  24525. function CubicBezierP1(t, p) {
  24526. const k = 1 - t;
  24527. return 3 * k * k * t * p;
  24528. }
  24529. function CubicBezierP2(t, p) {
  24530. return 3 * (1 - t) * t * t * p;
  24531. }
  24532. function CubicBezierP3(t, p) {
  24533. return t * t * t * p;
  24534. }
  24535. function CubicBezier(t, p0, p1, p2, p3) {
  24536. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  24537. }
  24538. class CubicBezierCurve extends Curve {
  24539. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  24540. super();
  24541. this.type = 'CubicBezierCurve';
  24542. this.v0 = v0;
  24543. this.v1 = v1;
  24544. this.v2 = v2;
  24545. this.v3 = v3;
  24546. }
  24547. getPoint(t, optionalTarget = new Vector2()) {
  24548. const point = optionalTarget;
  24549. const v0 = this.v0,
  24550. v1 = this.v1,
  24551. v2 = this.v2,
  24552. v3 = this.v3;
  24553. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  24554. return point;
  24555. }
  24556. copy(source) {
  24557. super.copy(source);
  24558. this.v0.copy(source.v0);
  24559. this.v1.copy(source.v1);
  24560. this.v2.copy(source.v2);
  24561. this.v3.copy(source.v3);
  24562. return this;
  24563. }
  24564. toJSON() {
  24565. const data = super.toJSON();
  24566. data.v0 = this.v0.toArray();
  24567. data.v1 = this.v1.toArray();
  24568. data.v2 = this.v2.toArray();
  24569. data.v3 = this.v3.toArray();
  24570. return data;
  24571. }
  24572. fromJSON(json) {
  24573. super.fromJSON(json);
  24574. this.v0.fromArray(json.v0);
  24575. this.v1.fromArray(json.v1);
  24576. this.v2.fromArray(json.v2);
  24577. this.v3.fromArray(json.v3);
  24578. return this;
  24579. }
  24580. }
  24581. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  24582. class CubicBezierCurve3 extends Curve {
  24583. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  24584. super();
  24585. this.type = 'CubicBezierCurve3';
  24586. this.v0 = v0;
  24587. this.v1 = v1;
  24588. this.v2 = v2;
  24589. this.v3 = v3;
  24590. }
  24591. getPoint(t, optionalTarget = new Vector3()) {
  24592. const point = optionalTarget;
  24593. const v0 = this.v0,
  24594. v1 = this.v1,
  24595. v2 = this.v2,
  24596. v3 = this.v3;
  24597. 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));
  24598. return point;
  24599. }
  24600. copy(source) {
  24601. super.copy(source);
  24602. this.v0.copy(source.v0);
  24603. this.v1.copy(source.v1);
  24604. this.v2.copy(source.v2);
  24605. this.v3.copy(source.v3);
  24606. return this;
  24607. }
  24608. toJSON() {
  24609. const data = super.toJSON();
  24610. data.v0 = this.v0.toArray();
  24611. data.v1 = this.v1.toArray();
  24612. data.v2 = this.v2.toArray();
  24613. data.v3 = this.v3.toArray();
  24614. return data;
  24615. }
  24616. fromJSON(json) {
  24617. super.fromJSON(json);
  24618. this.v0.fromArray(json.v0);
  24619. this.v1.fromArray(json.v1);
  24620. this.v2.fromArray(json.v2);
  24621. this.v3.fromArray(json.v3);
  24622. return this;
  24623. }
  24624. }
  24625. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  24626. class LineCurve extends Curve {
  24627. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  24628. super();
  24629. this.type = 'LineCurve';
  24630. this.v1 = v1;
  24631. this.v2 = v2;
  24632. }
  24633. getPoint(t, optionalTarget = new Vector2()) {
  24634. const point = optionalTarget;
  24635. if (t === 1) {
  24636. point.copy(this.v2);
  24637. } else {
  24638. point.copy(this.v2).sub(this.v1);
  24639. point.multiplyScalar(t).add(this.v1);
  24640. }
  24641. return point;
  24642. } // Line curve is linear, so we can overwrite default getPointAt
  24643. getPointAt(u, optionalTarget) {
  24644. return this.getPoint(u, optionalTarget);
  24645. }
  24646. getTangent(t, optionalTarget) {
  24647. const tangent = optionalTarget || new Vector2();
  24648. tangent.copy(this.v2).sub(this.v1).normalize();
  24649. return tangent;
  24650. }
  24651. copy(source) {
  24652. super.copy(source);
  24653. this.v1.copy(source.v1);
  24654. this.v2.copy(source.v2);
  24655. return this;
  24656. }
  24657. toJSON() {
  24658. const data = super.toJSON();
  24659. data.v1 = this.v1.toArray();
  24660. data.v2 = this.v2.toArray();
  24661. return data;
  24662. }
  24663. fromJSON(json) {
  24664. super.fromJSON(json);
  24665. this.v1.fromArray(json.v1);
  24666. this.v2.fromArray(json.v2);
  24667. return this;
  24668. }
  24669. }
  24670. LineCurve.prototype.isLineCurve = true;
  24671. class LineCurve3 extends Curve {
  24672. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  24673. super();
  24674. this.type = 'LineCurve3';
  24675. this.isLineCurve3 = true;
  24676. this.v1 = v1;
  24677. this.v2 = v2;
  24678. }
  24679. getPoint(t, optionalTarget = new Vector3()) {
  24680. const point = optionalTarget;
  24681. if (t === 1) {
  24682. point.copy(this.v2);
  24683. } else {
  24684. point.copy(this.v2).sub(this.v1);
  24685. point.multiplyScalar(t).add(this.v1);
  24686. }
  24687. return point;
  24688. } // Line curve is linear, so we can overwrite default getPointAt
  24689. getPointAt(u, optionalTarget) {
  24690. return this.getPoint(u, optionalTarget);
  24691. }
  24692. copy(source) {
  24693. super.copy(source);
  24694. this.v1.copy(source.v1);
  24695. this.v2.copy(source.v2);
  24696. return this;
  24697. }
  24698. toJSON() {
  24699. const data = super.toJSON();
  24700. data.v1 = this.v1.toArray();
  24701. data.v2 = this.v2.toArray();
  24702. return data;
  24703. }
  24704. fromJSON(json) {
  24705. super.fromJSON(json);
  24706. this.v1.fromArray(json.v1);
  24707. this.v2.fromArray(json.v2);
  24708. return this;
  24709. }
  24710. }
  24711. class QuadraticBezierCurve extends Curve {
  24712. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  24713. super();
  24714. this.type = 'QuadraticBezierCurve';
  24715. this.v0 = v0;
  24716. this.v1 = v1;
  24717. this.v2 = v2;
  24718. }
  24719. getPoint(t, optionalTarget = new Vector2()) {
  24720. const point = optionalTarget;
  24721. const v0 = this.v0,
  24722. v1 = this.v1,
  24723. v2 = this.v2;
  24724. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  24725. return point;
  24726. }
  24727. copy(source) {
  24728. super.copy(source);
  24729. this.v0.copy(source.v0);
  24730. this.v1.copy(source.v1);
  24731. this.v2.copy(source.v2);
  24732. return this;
  24733. }
  24734. toJSON() {
  24735. const data = super.toJSON();
  24736. data.v0 = this.v0.toArray();
  24737. data.v1 = this.v1.toArray();
  24738. data.v2 = this.v2.toArray();
  24739. return data;
  24740. }
  24741. fromJSON(json) {
  24742. super.fromJSON(json);
  24743. this.v0.fromArray(json.v0);
  24744. this.v1.fromArray(json.v1);
  24745. this.v2.fromArray(json.v2);
  24746. return this;
  24747. }
  24748. }
  24749. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  24750. class QuadraticBezierCurve3 extends Curve {
  24751. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  24752. super();
  24753. this.type = 'QuadraticBezierCurve3';
  24754. this.v0 = v0;
  24755. this.v1 = v1;
  24756. this.v2 = v2;
  24757. }
  24758. getPoint(t, optionalTarget = new Vector3()) {
  24759. const point = optionalTarget;
  24760. const v0 = this.v0,
  24761. v1 = this.v1,
  24762. v2 = this.v2;
  24763. 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));
  24764. return point;
  24765. }
  24766. copy(source) {
  24767. super.copy(source);
  24768. this.v0.copy(source.v0);
  24769. this.v1.copy(source.v1);
  24770. this.v2.copy(source.v2);
  24771. return this;
  24772. }
  24773. toJSON() {
  24774. const data = super.toJSON();
  24775. data.v0 = this.v0.toArray();
  24776. data.v1 = this.v1.toArray();
  24777. data.v2 = this.v2.toArray();
  24778. return data;
  24779. }
  24780. fromJSON(json) {
  24781. super.fromJSON(json);
  24782. this.v0.fromArray(json.v0);
  24783. this.v1.fromArray(json.v1);
  24784. this.v2.fromArray(json.v2);
  24785. return this;
  24786. }
  24787. }
  24788. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  24789. class SplineCurve extends Curve {
  24790. constructor(points = []) {
  24791. super();
  24792. this.type = 'SplineCurve';
  24793. this.points = points;
  24794. }
  24795. getPoint(t, optionalTarget = new Vector2()) {
  24796. const point = optionalTarget;
  24797. const points = this.points;
  24798. const p = (points.length - 1) * t;
  24799. const intPoint = Math.floor(p);
  24800. const weight = p - intPoint;
  24801. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  24802. const p1 = points[intPoint];
  24803. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  24804. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  24805. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  24806. return point;
  24807. }
  24808. copy(source) {
  24809. super.copy(source);
  24810. this.points = [];
  24811. for (let i = 0, l = source.points.length; i < l; i++) {
  24812. const point = source.points[i];
  24813. this.points.push(point.clone());
  24814. }
  24815. return this;
  24816. }
  24817. toJSON() {
  24818. const data = super.toJSON();
  24819. data.points = [];
  24820. for (let i = 0, l = this.points.length; i < l; i++) {
  24821. const point = this.points[i];
  24822. data.points.push(point.toArray());
  24823. }
  24824. return data;
  24825. }
  24826. fromJSON(json) {
  24827. super.fromJSON(json);
  24828. this.points = [];
  24829. for (let i = 0, l = json.points.length; i < l; i++) {
  24830. const point = json.points[i];
  24831. this.points.push(new Vector2().fromArray(point));
  24832. }
  24833. return this;
  24834. }
  24835. }
  24836. SplineCurve.prototype.isSplineCurve = true;
  24837. var Curves = /*#__PURE__*/Object.freeze({
  24838. __proto__: null,
  24839. ArcCurve: ArcCurve,
  24840. CatmullRomCurve3: CatmullRomCurve3,
  24841. CubicBezierCurve: CubicBezierCurve,
  24842. CubicBezierCurve3: CubicBezierCurve3,
  24843. EllipseCurve: EllipseCurve,
  24844. LineCurve: LineCurve,
  24845. LineCurve3: LineCurve3,
  24846. QuadraticBezierCurve: QuadraticBezierCurve,
  24847. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24848. SplineCurve: SplineCurve
  24849. });
  24850. /**************************************************************
  24851. * Curved Path - a curve path is simply a array of connected
  24852. * curves, but retains the api of a curve
  24853. **************************************************************/
  24854. class CurvePath extends Curve {
  24855. constructor() {
  24856. super();
  24857. this.type = 'CurvePath';
  24858. this.curves = [];
  24859. this.autoClose = false; // Automatically closes the path
  24860. }
  24861. add(curve) {
  24862. this.curves.push(curve);
  24863. }
  24864. closePath() {
  24865. // Add a line curve if start and end of lines are not connected
  24866. const startPoint = this.curves[0].getPoint(0);
  24867. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  24868. if (!startPoint.equals(endPoint)) {
  24869. this.curves.push(new LineCurve(endPoint, startPoint));
  24870. }
  24871. } // To get accurate point with reference to
  24872. // entire path distance at time t,
  24873. // following has to be done:
  24874. // 1. Length of each sub path have to be known
  24875. // 2. Locate and identify type of curve
  24876. // 3. Get t for the curve
  24877. // 4. Return curve.getPointAt(t')
  24878. getPoint(t, optionalTarget) {
  24879. const d = t * this.getLength();
  24880. const curveLengths = this.getCurveLengths();
  24881. let i = 0; // To think about boundaries points.
  24882. while (i < curveLengths.length) {
  24883. if (curveLengths[i] >= d) {
  24884. const diff = curveLengths[i] - d;
  24885. const curve = this.curves[i];
  24886. const segmentLength = curve.getLength();
  24887. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24888. return curve.getPointAt(u, optionalTarget);
  24889. }
  24890. i++;
  24891. }
  24892. return null; // loop where sum != 0, sum > d , sum+1 <d
  24893. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24894. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24895. // getPoint() depends on getLength
  24896. getLength() {
  24897. const lens = this.getCurveLengths();
  24898. return lens[lens.length - 1];
  24899. } // cacheLengths must be recalculated.
  24900. updateArcLengths() {
  24901. this.needsUpdate = true;
  24902. this.cacheLengths = null;
  24903. this.getCurveLengths();
  24904. } // Compute lengths and cache them
  24905. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24906. getCurveLengths() {
  24907. // We use cache values if curves and cache array are same length
  24908. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  24909. return this.cacheLengths;
  24910. } // Get length of sub-curve
  24911. // Push sums into cached array
  24912. const lengths = [];
  24913. let sums = 0;
  24914. for (let i = 0, l = this.curves.length; i < l; i++) {
  24915. sums += this.curves[i].getLength();
  24916. lengths.push(sums);
  24917. }
  24918. this.cacheLengths = lengths;
  24919. return lengths;
  24920. }
  24921. getSpacedPoints(divisions = 40) {
  24922. const points = [];
  24923. for (let i = 0; i <= divisions; i++) {
  24924. points.push(this.getPoint(i / divisions));
  24925. }
  24926. if (this.autoClose) {
  24927. points.push(points[0]);
  24928. }
  24929. return points;
  24930. }
  24931. getPoints(divisions = 12) {
  24932. const points = [];
  24933. let last;
  24934. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  24935. const curve = curves[i];
  24936. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  24937. const pts = curve.getPoints(resolution);
  24938. for (let j = 0; j < pts.length; j++) {
  24939. const point = pts[j];
  24940. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  24941. points.push(point);
  24942. last = point;
  24943. }
  24944. }
  24945. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  24946. points.push(points[0]);
  24947. }
  24948. return points;
  24949. }
  24950. copy(source) {
  24951. super.copy(source);
  24952. this.curves = [];
  24953. for (let i = 0, l = source.curves.length; i < l; i++) {
  24954. const curve = source.curves[i];
  24955. this.curves.push(curve.clone());
  24956. }
  24957. this.autoClose = source.autoClose;
  24958. return this;
  24959. }
  24960. toJSON() {
  24961. const data = super.toJSON();
  24962. data.autoClose = this.autoClose;
  24963. data.curves = [];
  24964. for (let i = 0, l = this.curves.length; i < l; i++) {
  24965. const curve = this.curves[i];
  24966. data.curves.push(curve.toJSON());
  24967. }
  24968. return data;
  24969. }
  24970. fromJSON(json) {
  24971. super.fromJSON(json);
  24972. this.autoClose = json.autoClose;
  24973. this.curves = [];
  24974. for (let i = 0, l = json.curves.length; i < l; i++) {
  24975. const curve = json.curves[i];
  24976. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  24977. }
  24978. return this;
  24979. }
  24980. }
  24981. class Path extends CurvePath {
  24982. constructor(points) {
  24983. super();
  24984. this.type = 'Path';
  24985. this.currentPoint = new Vector2();
  24986. if (points) {
  24987. this.setFromPoints(points);
  24988. }
  24989. }
  24990. setFromPoints(points) {
  24991. this.moveTo(points[0].x, points[0].y);
  24992. for (let i = 1, l = points.length; i < l; i++) {
  24993. this.lineTo(points[i].x, points[i].y);
  24994. }
  24995. return this;
  24996. }
  24997. moveTo(x, y) {
  24998. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  24999. return this;
  25000. }
  25001. lineTo(x, y) {
  25002. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  25003. this.curves.push(curve);
  25004. this.currentPoint.set(x, y);
  25005. return this;
  25006. }
  25007. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  25008. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  25009. this.curves.push(curve);
  25010. this.currentPoint.set(aX, aY);
  25011. return this;
  25012. }
  25013. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25014. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  25015. this.curves.push(curve);
  25016. this.currentPoint.set(aX, aY);
  25017. return this;
  25018. }
  25019. splineThru(pts
  25020. /*Array of Vector*/
  25021. ) {
  25022. const npts = [this.currentPoint.clone()].concat(pts);
  25023. const curve = new SplineCurve(npts);
  25024. this.curves.push(curve);
  25025. this.currentPoint.copy(pts[pts.length - 1]);
  25026. return this;
  25027. }
  25028. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  25029. const x0 = this.currentPoint.x;
  25030. const y0 = this.currentPoint.y;
  25031. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  25032. return this;
  25033. }
  25034. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  25035. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  25036. return this;
  25037. }
  25038. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  25039. const x0 = this.currentPoint.x;
  25040. const y0 = this.currentPoint.y;
  25041. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  25042. return this;
  25043. }
  25044. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  25045. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  25046. if (this.curves.length > 0) {
  25047. // if a previous curve is present, attempt to join
  25048. const firstPoint = curve.getPoint(0);
  25049. if (!firstPoint.equals(this.currentPoint)) {
  25050. this.lineTo(firstPoint.x, firstPoint.y);
  25051. }
  25052. }
  25053. this.curves.push(curve);
  25054. const lastPoint = curve.getPoint(1);
  25055. this.currentPoint.copy(lastPoint);
  25056. return this;
  25057. }
  25058. copy(source) {
  25059. super.copy(source);
  25060. this.currentPoint.copy(source.currentPoint);
  25061. return this;
  25062. }
  25063. toJSON() {
  25064. const data = super.toJSON();
  25065. data.currentPoint = this.currentPoint.toArray();
  25066. return data;
  25067. }
  25068. fromJSON(json) {
  25069. super.fromJSON(json);
  25070. this.currentPoint.fromArray(json.currentPoint);
  25071. return this;
  25072. }
  25073. }
  25074. class Shape extends Path {
  25075. constructor(points) {
  25076. super(points);
  25077. this.uuid = generateUUID();
  25078. this.type = 'Shape';
  25079. this.holes = [];
  25080. }
  25081. getPointsHoles(divisions) {
  25082. const holesPts = [];
  25083. for (let i = 0, l = this.holes.length; i < l; i++) {
  25084. holesPts[i] = this.holes[i].getPoints(divisions);
  25085. }
  25086. return holesPts;
  25087. } // get points of shape and holes (keypoints based on segments parameter)
  25088. extractPoints(divisions) {
  25089. return {
  25090. shape: this.getPoints(divisions),
  25091. holes: this.getPointsHoles(divisions)
  25092. };
  25093. }
  25094. copy(source) {
  25095. super.copy(source);
  25096. this.holes = [];
  25097. for (let i = 0, l = source.holes.length; i < l; i++) {
  25098. const hole = source.holes[i];
  25099. this.holes.push(hole.clone());
  25100. }
  25101. return this;
  25102. }
  25103. toJSON() {
  25104. const data = super.toJSON();
  25105. data.uuid = this.uuid;
  25106. data.holes = [];
  25107. for (let i = 0, l = this.holes.length; i < l; i++) {
  25108. const hole = this.holes[i];
  25109. data.holes.push(hole.toJSON());
  25110. }
  25111. return data;
  25112. }
  25113. fromJSON(json) {
  25114. super.fromJSON(json);
  25115. this.uuid = json.uuid;
  25116. this.holes = [];
  25117. for (let i = 0, l = json.holes.length; i < l; i++) {
  25118. const hole = json.holes[i];
  25119. this.holes.push(new Path().fromJSON(hole));
  25120. }
  25121. return this;
  25122. }
  25123. }
  25124. /**
  25125. * Port from https://github.com/mapbox/earcut (v2.2.2)
  25126. */
  25127. const Earcut = {
  25128. triangulate: function (data, holeIndices, dim = 2) {
  25129. const hasHoles = holeIndices && holeIndices.length;
  25130. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25131. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25132. const triangles = [];
  25133. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25134. let minX, minY, maxX, maxY, x, y, invSize;
  25135. 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
  25136. if (data.length > 80 * dim) {
  25137. minX = maxX = data[0];
  25138. minY = maxY = data[1];
  25139. for (let i = dim; i < outerLen; i += dim) {
  25140. x = data[i];
  25141. y = data[i + 1];
  25142. if (x < minX) minX = x;
  25143. if (y < minY) minY = y;
  25144. if (x > maxX) maxX = x;
  25145. if (y > maxY) maxY = y;
  25146. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25147. invSize = Math.max(maxX - minX, maxY - minY);
  25148. invSize = invSize !== 0 ? 1 / invSize : 0;
  25149. }
  25150. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  25151. return triangles;
  25152. }
  25153. }; // create a circular doubly linked list from polygon points in the specified winding order
  25154. function linkedList(data, start, end, dim, clockwise) {
  25155. let i, last;
  25156. if (clockwise === signedArea(data, start, end, dim) > 0) {
  25157. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  25158. } else {
  25159. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  25160. }
  25161. if (last && equals(last, last.next)) {
  25162. removeNode(last);
  25163. last = last.next;
  25164. }
  25165. return last;
  25166. } // eliminate colinear or duplicate points
  25167. function filterPoints(start, end) {
  25168. if (!start) return start;
  25169. if (!end) end = start;
  25170. let p = start,
  25171. again;
  25172. do {
  25173. again = false;
  25174. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25175. removeNode(p);
  25176. p = end = p.prev;
  25177. if (p === p.next) break;
  25178. again = true;
  25179. } else {
  25180. p = p.next;
  25181. }
  25182. } while (again || p !== end);
  25183. return end;
  25184. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  25185. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25186. if (!ear) return; // interlink polygon nodes in z-order
  25187. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25188. let stop = ear,
  25189. prev,
  25190. next; // iterate through ears, slicing them one by one
  25191. while (ear.prev !== ear.next) {
  25192. prev = ear.prev;
  25193. next = ear.next;
  25194. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25195. // cut off the triangle
  25196. triangles.push(prev.i / dim);
  25197. triangles.push(ear.i / dim);
  25198. triangles.push(next.i / dim);
  25199. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  25200. ear = next.next;
  25201. stop = next.next;
  25202. continue;
  25203. }
  25204. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  25205. if (ear === stop) {
  25206. // try filtering points and slicing again
  25207. if (!pass) {
  25208. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  25209. } else if (pass === 1) {
  25210. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  25211. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  25212. } else if (pass === 2) {
  25213. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25214. }
  25215. break;
  25216. }
  25217. }
  25218. } // check whether a polygon node forms a valid ear with adjacent nodes
  25219. function isEar(ear) {
  25220. const a = ear.prev,
  25221. b = ear,
  25222. c = ear.next;
  25223. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25224. // now make sure we don't have other points inside the potential ear
  25225. let p = ear.next.next;
  25226. while (p !== ear.prev) {
  25227. 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;
  25228. p = p.next;
  25229. }
  25230. return true;
  25231. }
  25232. function isEarHashed(ear, minX, minY, invSize) {
  25233. const a = ear.prev,
  25234. b = ear,
  25235. c = ear.next;
  25236. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25237. // triangle bbox; min & max are calculated like this for speed
  25238. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  25239. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  25240. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  25241. 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;
  25242. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  25243. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  25244. let p = ear.prevZ,
  25245. n = ear.nextZ; // look for points inside the triangle in both directions
  25246. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25247. 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;
  25248. p = p.prevZ;
  25249. 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;
  25250. n = n.nextZ;
  25251. } // look for remaining points in decreasing z-order
  25252. while (p && p.z >= minZ) {
  25253. 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;
  25254. p = p.prevZ;
  25255. } // look for remaining points in increasing z-order
  25256. while (n && n.z <= maxZ) {
  25257. 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;
  25258. n = n.nextZ;
  25259. }
  25260. return true;
  25261. } // go through all polygon nodes and cure small local self-intersections
  25262. function cureLocalIntersections(start, triangles, dim) {
  25263. let p = start;
  25264. do {
  25265. const a = p.prev,
  25266. b = p.next.next;
  25267. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25268. triangles.push(a.i / dim);
  25269. triangles.push(p.i / dim);
  25270. triangles.push(b.i / dim); // remove two nodes involved
  25271. removeNode(p);
  25272. removeNode(p.next);
  25273. p = start = b;
  25274. }
  25275. p = p.next;
  25276. } while (p !== start);
  25277. return filterPoints(p);
  25278. } // try splitting polygon into two and triangulate them independently
  25279. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25280. // look for a valid diagonal that divides the polygon into two
  25281. let a = start;
  25282. do {
  25283. let b = a.next.next;
  25284. while (b !== a.prev) {
  25285. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25286. // split the polygon in two by the diagonal
  25287. let c = splitPolygon(a, b); // filter colinear points around the cuts
  25288. a = filterPoints(a, a.next);
  25289. c = filterPoints(c, c.next); // run earcut on each half
  25290. earcutLinked(a, triangles, dim, minX, minY, invSize);
  25291. earcutLinked(c, triangles, dim, minX, minY, invSize);
  25292. return;
  25293. }
  25294. b = b.next;
  25295. }
  25296. a = a.next;
  25297. } while (a !== start);
  25298. } // link every hole into the outer loop, producing a single-ring polygon without holes
  25299. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25300. const queue = [];
  25301. let i, len, start, end, list;
  25302. for (i = 0, len = holeIndices.length; i < len; i++) {
  25303. start = holeIndices[i] * dim;
  25304. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25305. list = linkedList(data, start, end, dim, false);
  25306. if (list === list.next) list.steiner = true;
  25307. queue.push(getLeftmost(list));
  25308. }
  25309. queue.sort(compareX); // process holes from left to right
  25310. for (i = 0; i < queue.length; i++) {
  25311. eliminateHole(queue[i], outerNode);
  25312. outerNode = filterPoints(outerNode, outerNode.next);
  25313. }
  25314. return outerNode;
  25315. }
  25316. function compareX(a, b) {
  25317. return a.x - b.x;
  25318. } // find a bridge between vertices that connects hole with an outer ring and and link it
  25319. function eliminateHole(hole, outerNode) {
  25320. outerNode = findHoleBridge(hole, outerNode);
  25321. if (outerNode) {
  25322. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  25323. filterPoints(outerNode, outerNode.next);
  25324. filterPoints(b, b.next);
  25325. }
  25326. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25327. function findHoleBridge(hole, outerNode) {
  25328. let p = outerNode;
  25329. const hx = hole.x;
  25330. const hy = hole.y;
  25331. let qx = -Infinity,
  25332. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  25333. // segment's endpoint with lesser x will be potential connection point
  25334. do {
  25335. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25336. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25337. if (x <= hx && x > qx) {
  25338. qx = x;
  25339. if (x === hx) {
  25340. if (hy === p.y) return p;
  25341. if (hy === p.next.y) return p.next;
  25342. }
  25343. m = p.x < p.next.x ? p : p.next;
  25344. }
  25345. }
  25346. p = p.next;
  25347. } while (p !== outerNode);
  25348. if (!m) return null;
  25349. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  25350. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25351. // if there are no points found, we have a valid connection;
  25352. // otherwise choose the point of the minimum angle with the ray as connection point
  25353. const stop = m,
  25354. mx = m.x,
  25355. my = m.y;
  25356. let tanMin = Infinity,
  25357. tan;
  25358. p = m;
  25359. do {
  25360. 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)) {
  25361. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25362. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  25363. m = p;
  25364. tanMin = tan;
  25365. }
  25366. }
  25367. p = p.next;
  25368. } while (p !== stop);
  25369. return m;
  25370. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  25371. function sectorContainsSector(m, p) {
  25372. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25373. } // interlink polygon nodes in z-order
  25374. function indexCurve(start, minX, minY, invSize) {
  25375. let p = start;
  25376. do {
  25377. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25378. p.prevZ = p.prev;
  25379. p.nextZ = p.next;
  25380. p = p.next;
  25381. } while (p !== start);
  25382. p.prevZ.nextZ = null;
  25383. p.prevZ = null;
  25384. sortLinked(p);
  25385. } // Simon Tatham's linked list merge sort algorithm
  25386. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25387. function sortLinked(list) {
  25388. let i,
  25389. p,
  25390. q,
  25391. e,
  25392. tail,
  25393. numMerges,
  25394. pSize,
  25395. qSize,
  25396. inSize = 1;
  25397. do {
  25398. p = list;
  25399. list = null;
  25400. tail = null;
  25401. numMerges = 0;
  25402. while (p) {
  25403. numMerges++;
  25404. q = p;
  25405. pSize = 0;
  25406. for (i = 0; i < inSize; i++) {
  25407. pSize++;
  25408. q = q.nextZ;
  25409. if (!q) break;
  25410. }
  25411. qSize = inSize;
  25412. while (pSize > 0 || qSize > 0 && q) {
  25413. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25414. e = p;
  25415. p = p.nextZ;
  25416. pSize--;
  25417. } else {
  25418. e = q;
  25419. q = q.nextZ;
  25420. qSize--;
  25421. }
  25422. if (tail) tail.nextZ = e;else list = e;
  25423. e.prevZ = tail;
  25424. tail = e;
  25425. }
  25426. p = q;
  25427. }
  25428. tail.nextZ = null;
  25429. inSize *= 2;
  25430. } while (numMerges > 1);
  25431. return list;
  25432. } // z-order of a point given coords and inverse of the longer side of data bbox
  25433. function zOrder(x, y, minX, minY, invSize) {
  25434. // coords are transformed into non-negative 15-bit integer range
  25435. x = 32767 * (x - minX) * invSize;
  25436. y = 32767 * (y - minY) * invSize;
  25437. x = (x | x << 8) & 0x00FF00FF;
  25438. x = (x | x << 4) & 0x0F0F0F0F;
  25439. x = (x | x << 2) & 0x33333333;
  25440. x = (x | x << 1) & 0x55555555;
  25441. y = (y | y << 8) & 0x00FF00FF;
  25442. y = (y | y << 4) & 0x0F0F0F0F;
  25443. y = (y | y << 2) & 0x33333333;
  25444. y = (y | y << 1) & 0x55555555;
  25445. return x | y << 1;
  25446. } // find the leftmost node of a polygon ring
  25447. function getLeftmost(start) {
  25448. let p = start,
  25449. leftmost = start;
  25450. do {
  25451. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  25452. p = p.next;
  25453. } while (p !== start);
  25454. return leftmost;
  25455. } // check if a point lies within a convex triangle
  25456. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25457. 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;
  25458. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25459. function isValidDiagonal(a, b) {
  25460. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25461. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25462. } // signed area of a triangle
  25463. function area(p, q, r) {
  25464. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25465. } // check if two points are equal
  25466. function equals(p1, p2) {
  25467. return p1.x === p2.x && p1.y === p2.y;
  25468. } // check if two segments intersect
  25469. function intersects(p1, q1, p2, q2) {
  25470. const o1 = sign(area(p1, q1, p2));
  25471. const o2 = sign(area(p1, q1, q2));
  25472. const o3 = sign(area(p2, q2, p1));
  25473. const o4 = sign(area(p2, q2, q1));
  25474. if (o1 !== o2 && o3 !== o4) return true; // general case
  25475. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25476. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25477. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25478. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25479. return false;
  25480. } // for collinear points p, q, r, check if point q lies on segment pr
  25481. function onSegment(p, q, r) {
  25482. 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);
  25483. }
  25484. function sign(num) {
  25485. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25486. } // check if a polygon diagonal intersects any polygon segments
  25487. function intersectsPolygon(a, b) {
  25488. let p = a;
  25489. do {
  25490. 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;
  25491. p = p.next;
  25492. } while (p !== a);
  25493. return false;
  25494. } // check if a polygon diagonal is locally inside the polygon
  25495. function locallyInside(a, b) {
  25496. 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;
  25497. } // check if the middle point of a polygon diagonal is inside the polygon
  25498. function middleInside(a, b) {
  25499. let p = a,
  25500. inside = false;
  25501. const px = (a.x + b.x) / 2,
  25502. py = (a.y + b.y) / 2;
  25503. do {
  25504. 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;
  25505. p = p.next;
  25506. } while (p !== a);
  25507. return inside;
  25508. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25509. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25510. function splitPolygon(a, b) {
  25511. const a2 = new Node(a.i, a.x, a.y),
  25512. b2 = new Node(b.i, b.x, b.y),
  25513. an = a.next,
  25514. bp = b.prev;
  25515. a.next = b;
  25516. b.prev = a;
  25517. a2.next = an;
  25518. an.prev = a2;
  25519. b2.next = a2;
  25520. a2.prev = b2;
  25521. bp.next = b2;
  25522. b2.prev = bp;
  25523. return b2;
  25524. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  25525. function insertNode(i, x, y, last) {
  25526. const p = new Node(i, x, y);
  25527. if (!last) {
  25528. p.prev = p;
  25529. p.next = p;
  25530. } else {
  25531. p.next = last.next;
  25532. p.prev = last;
  25533. last.next.prev = p;
  25534. last.next = p;
  25535. }
  25536. return p;
  25537. }
  25538. function removeNode(p) {
  25539. p.next.prev = p.prev;
  25540. p.prev.next = p.next;
  25541. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25542. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25543. }
  25544. function Node(i, x, y) {
  25545. // vertex index in coordinates array
  25546. this.i = i; // vertex coordinates
  25547. this.x = x;
  25548. this.y = y; // previous and next vertex nodes in a polygon ring
  25549. this.prev = null;
  25550. this.next = null; // z-order curve value
  25551. this.z = null; // previous and next nodes in z-order
  25552. this.prevZ = null;
  25553. this.nextZ = null; // indicates whether this is a steiner point
  25554. this.steiner = false;
  25555. }
  25556. function signedArea(data, start, end, dim) {
  25557. let sum = 0;
  25558. for (let i = start, j = end - dim; i < end; i += dim) {
  25559. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25560. j = i;
  25561. }
  25562. return sum;
  25563. }
  25564. class ShapeUtils {
  25565. // calculate area of the contour polygon
  25566. static area(contour) {
  25567. const n = contour.length;
  25568. let a = 0.0;
  25569. for (let p = n - 1, q = 0; q < n; p = q++) {
  25570. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  25571. }
  25572. return a * 0.5;
  25573. }
  25574. static isClockWise(pts) {
  25575. return ShapeUtils.area(pts) < 0;
  25576. }
  25577. static triangulateShape(contour, holes) {
  25578. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25579. const holeIndices = []; // array of hole indices
  25580. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25581. removeDupEndPts(contour);
  25582. addContour(vertices, contour); //
  25583. let holeIndex = contour.length;
  25584. holes.forEach(removeDupEndPts);
  25585. for (let i = 0; i < holes.length; i++) {
  25586. holeIndices.push(holeIndex);
  25587. holeIndex += holes[i].length;
  25588. addContour(vertices, holes[i]);
  25589. } //
  25590. const triangles = Earcut.triangulate(vertices, holeIndices); //
  25591. for (let i = 0; i < triangles.length; i += 3) {
  25592. faces.push(triangles.slice(i, i + 3));
  25593. }
  25594. return faces;
  25595. }
  25596. }
  25597. function removeDupEndPts(points) {
  25598. const l = points.length;
  25599. if (l > 2 && points[l - 1].equals(points[0])) {
  25600. points.pop();
  25601. }
  25602. }
  25603. function addContour(vertices, contour) {
  25604. for (let i = 0; i < contour.length; i++) {
  25605. vertices.push(contour[i].x);
  25606. vertices.push(contour[i].y);
  25607. }
  25608. }
  25609. /**
  25610. * Creates extruded geometry from a path shape.
  25611. *
  25612. * parameters = {
  25613. *
  25614. * curveSegments: <int>, // number of points on the curves
  25615. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  25616. * depth: <float>, // Depth to extrude the shape
  25617. *
  25618. * bevelEnabled: <bool>, // turn on bevel
  25619. * bevelThickness: <float>, // how deep into the original shape bevel goes
  25620. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  25621. * bevelOffset: <float>, // how far from shape outline does bevel start
  25622. * bevelSegments: <int>, // number of bevel layers
  25623. *
  25624. * extrudePath: <THREE.Curve> // curve to extrude shape along
  25625. *
  25626. * UVGenerator: <Object> // object that provides UV generator functions
  25627. *
  25628. * }
  25629. */
  25630. class ExtrudeGeometry extends BufferGeometry {
  25631. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  25632. super();
  25633. this.type = 'ExtrudeGeometry';
  25634. this.parameters = {
  25635. shapes: shapes,
  25636. options: options
  25637. };
  25638. shapes = Array.isArray(shapes) ? shapes : [shapes];
  25639. const scope = this;
  25640. const verticesArray = [];
  25641. const uvArray = [];
  25642. for (let i = 0, l = shapes.length; i < l; i++) {
  25643. const shape = shapes[i];
  25644. addShape(shape);
  25645. } // build geometry
  25646. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  25647. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  25648. this.computeVertexNormals(); // functions
  25649. function addShape(shape) {
  25650. const placeholder = []; // options
  25651. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25652. const steps = options.steps !== undefined ? options.steps : 1;
  25653. let depth = options.depth !== undefined ? options.depth : 1;
  25654. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25655. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25656. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25657. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25658. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25659. const extrudePath = options.extrudePath;
  25660. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  25661. if (options.amount !== undefined) {
  25662. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  25663. depth = options.amount;
  25664. } //
  25665. let extrudePts,
  25666. extrudeByPath = false;
  25667. let splineTube, binormal, normal, position2;
  25668. if (extrudePath) {
  25669. extrudePts = extrudePath.getSpacedPoints(steps);
  25670. extrudeByPath = true;
  25671. bevelEnabled = false; // bevels not supported for path extrusion
  25672. // SETUP TNB variables
  25673. // TODO1 - have a .isClosed in spline?
  25674. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25675. binormal = new Vector3();
  25676. normal = new Vector3();
  25677. position2 = new Vector3();
  25678. } // Safeguards if bevels are not enabled
  25679. if (!bevelEnabled) {
  25680. bevelSegments = 0;
  25681. bevelThickness = 0;
  25682. bevelSize = 0;
  25683. bevelOffset = 0;
  25684. } // Variables initialization
  25685. const shapePoints = shape.extractPoints(curveSegments);
  25686. let vertices = shapePoints.shape;
  25687. const holes = shapePoints.holes;
  25688. const reverse = !ShapeUtils.isClockWise(vertices);
  25689. if (reverse) {
  25690. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25691. for (let h = 0, hl = holes.length; h < hl; h++) {
  25692. const ahole = holes[h];
  25693. if (ShapeUtils.isClockWise(ahole)) {
  25694. holes[h] = ahole.reverse();
  25695. }
  25696. }
  25697. }
  25698. const faces = ShapeUtils.triangulateShape(vertices, holes);
  25699. /* Vertices */
  25700. const contour = vertices; // vertices has all points but contour has only points of circumference
  25701. for (let h = 0, hl = holes.length; h < hl; h++) {
  25702. const ahole = holes[h];
  25703. vertices = vertices.concat(ahole);
  25704. }
  25705. function scalePt2(pt, vec, size) {
  25706. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  25707. return vec.clone().multiplyScalar(size).add(pt);
  25708. }
  25709. const vlen = vertices.length,
  25710. flen = faces.length; // Find directions for point movement
  25711. function getBevelVec(inPt, inPrev, inNext) {
  25712. // computes for inPt the corresponding point inPt' on a new contour
  25713. // shifted by 1 unit (length of normalized vector) to the left
  25714. // if we walk along contour clockwise, this new contour is outside the old one
  25715. //
  25716. // inPt' is the intersection of the two lines parallel to the two
  25717. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25718. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25719. // good reading for geometry algorithms (here: line-line intersection)
  25720. // http://geomalgorithms.com/a05-_intersect-1.html
  25721. const v_prev_x = inPt.x - inPrev.x,
  25722. v_prev_y = inPt.y - inPrev.y;
  25723. const v_next_x = inNext.x - inPt.x,
  25724. v_next_y = inNext.y - inPt.y;
  25725. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  25726. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  25727. if (Math.abs(collinear0) > Number.EPSILON) {
  25728. // not collinear
  25729. // length of vectors for normalizing
  25730. const v_prev_len = Math.sqrt(v_prev_lensq);
  25731. const 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
  25732. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  25733. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  25734. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  25735. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  25736. const 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
  25737. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  25738. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  25739. // but prevent crazy spikes
  25740. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  25741. if (v_trans_lensq <= 2) {
  25742. return new Vector2(v_trans_x, v_trans_y);
  25743. } else {
  25744. shrink_by = Math.sqrt(v_trans_lensq / 2);
  25745. }
  25746. } else {
  25747. // handle special case of collinear edges
  25748. let direction_eq = false; // assumes: opposite
  25749. if (v_prev_x > Number.EPSILON) {
  25750. if (v_next_x > Number.EPSILON) {
  25751. direction_eq = true;
  25752. }
  25753. } else {
  25754. if (v_prev_x < -Number.EPSILON) {
  25755. if (v_next_x < -Number.EPSILON) {
  25756. direction_eq = true;
  25757. }
  25758. } else {
  25759. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  25760. direction_eq = true;
  25761. }
  25762. }
  25763. }
  25764. if (direction_eq) {
  25765. // console.log("Warning: lines are a straight sequence");
  25766. v_trans_x = -v_prev_y;
  25767. v_trans_y = v_prev_x;
  25768. shrink_by = Math.sqrt(v_prev_lensq);
  25769. } else {
  25770. // console.log("Warning: lines are a straight spike");
  25771. v_trans_x = v_prev_x;
  25772. v_trans_y = v_prev_y;
  25773. shrink_by = Math.sqrt(v_prev_lensq / 2);
  25774. }
  25775. }
  25776. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  25777. }
  25778. const contourMovements = [];
  25779. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  25780. if (j === il) j = 0;
  25781. if (k === il) k = 0; // (j)---(i)---(k)
  25782. // console.log('i,j,k', i, j , k)
  25783. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  25784. }
  25785. const holesMovements = [];
  25786. let oneHoleMovements,
  25787. verticesMovements = contourMovements.concat();
  25788. for (let h = 0, hl = holes.length; h < hl; h++) {
  25789. const ahole = holes[h];
  25790. oneHoleMovements = [];
  25791. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  25792. if (j === il) j = 0;
  25793. if (k === il) k = 0; // (j)---(i)---(k)
  25794. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  25795. }
  25796. holesMovements.push(oneHoleMovements);
  25797. verticesMovements = verticesMovements.concat(oneHoleMovements);
  25798. } // Loop bevelSegments, 1 for the front, 1 for the back
  25799. for (let b = 0; b < bevelSegments; b++) {
  25800. //for ( b = bevelSegments; b > 0; b -- ) {
  25801. const t = b / bevelSegments;
  25802. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  25803. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  25804. for (let i = 0, il = contour.length; i < il; i++) {
  25805. const vert = scalePt2(contour[i], contourMovements[i], bs);
  25806. v(vert.x, vert.y, -z);
  25807. } // expand holes
  25808. for (let h = 0, hl = holes.length; h < hl; h++) {
  25809. const ahole = holes[h];
  25810. oneHoleMovements = holesMovements[h];
  25811. for (let i = 0, il = ahole.length; i < il; i++) {
  25812. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  25813. v(vert.x, vert.y, -z);
  25814. }
  25815. }
  25816. }
  25817. const bs = bevelSize + bevelOffset; // Back facing vertices
  25818. for (let i = 0; i < vlen; i++) {
  25819. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  25820. if (!extrudeByPath) {
  25821. v(vert.x, vert.y, 0);
  25822. } else {
  25823. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25824. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  25825. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  25826. position2.copy(extrudePts[0]).add(normal).add(binormal);
  25827. v(position2.x, position2.y, position2.z);
  25828. }
  25829. } // Add stepped vertices...
  25830. // Including front facing vertices
  25831. for (let s = 1; s <= steps; s++) {
  25832. for (let i = 0; i < vlen; i++) {
  25833. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  25834. if (!extrudeByPath) {
  25835. v(vert.x, vert.y, depth / steps * s);
  25836. } else {
  25837. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25838. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  25839. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  25840. position2.copy(extrudePts[s]).add(normal).add(binormal);
  25841. v(position2.x, position2.y, position2.z);
  25842. }
  25843. }
  25844. } // Add bevel segments planes
  25845. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25846. for (let b = bevelSegments - 1; b >= 0; b--) {
  25847. const t = b / bevelSegments;
  25848. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  25849. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  25850. for (let i = 0, il = contour.length; i < il; i++) {
  25851. const vert = scalePt2(contour[i], contourMovements[i], bs);
  25852. v(vert.x, vert.y, depth + z);
  25853. } // expand holes
  25854. for (let h = 0, hl = holes.length; h < hl; h++) {
  25855. const ahole = holes[h];
  25856. oneHoleMovements = holesMovements[h];
  25857. for (let i = 0, il = ahole.length; i < il; i++) {
  25858. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  25859. if (!extrudeByPath) {
  25860. v(vert.x, vert.y, depth + z);
  25861. } else {
  25862. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  25863. }
  25864. }
  25865. }
  25866. }
  25867. /* Faces */
  25868. // Top and bottom faces
  25869. buildLidFaces(); // Sides faces
  25870. buildSideFaces(); ///// Internal functions
  25871. function buildLidFaces() {
  25872. const start = verticesArray.length / 3;
  25873. if (bevelEnabled) {
  25874. let layer = 0; // steps + 1
  25875. let offset = vlen * layer; // Bottom faces
  25876. for (let i = 0; i < flen; i++) {
  25877. const face = faces[i];
  25878. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  25879. }
  25880. layer = steps + bevelSegments * 2;
  25881. offset = vlen * layer; // Top faces
  25882. for (let i = 0; i < flen; i++) {
  25883. const face = faces[i];
  25884. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  25885. }
  25886. } else {
  25887. // Bottom faces
  25888. for (let i = 0; i < flen; i++) {
  25889. const face = faces[i];
  25890. f3(face[2], face[1], face[0]);
  25891. } // Top faces
  25892. for (let i = 0; i < flen; i++) {
  25893. const face = faces[i];
  25894. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  25895. }
  25896. }
  25897. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  25898. } // Create faces for the z-sides of the shape
  25899. function buildSideFaces() {
  25900. const start = verticesArray.length / 3;
  25901. let layeroffset = 0;
  25902. sidewalls(contour, layeroffset);
  25903. layeroffset += contour.length;
  25904. for (let h = 0, hl = holes.length; h < hl; h++) {
  25905. const ahole = holes[h];
  25906. sidewalls(ahole, layeroffset); //, true
  25907. layeroffset += ahole.length;
  25908. }
  25909. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  25910. }
  25911. function sidewalls(contour, layeroffset) {
  25912. let i = contour.length;
  25913. while (--i >= 0) {
  25914. const j = i;
  25915. let k = i - 1;
  25916. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  25917. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  25918. const slen1 = vlen * s;
  25919. const slen2 = vlen * (s + 1);
  25920. const a = layeroffset + j + slen1,
  25921. b = layeroffset + k + slen1,
  25922. c = layeroffset + k + slen2,
  25923. d = layeroffset + j + slen2;
  25924. f4(a, b, c, d);
  25925. }
  25926. }
  25927. }
  25928. function v(x, y, z) {
  25929. placeholder.push(x);
  25930. placeholder.push(y);
  25931. placeholder.push(z);
  25932. }
  25933. function f3(a, b, c) {
  25934. addVertex(a);
  25935. addVertex(b);
  25936. addVertex(c);
  25937. const nextIndex = verticesArray.length / 3;
  25938. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  25939. addUV(uvs[0]);
  25940. addUV(uvs[1]);
  25941. addUV(uvs[2]);
  25942. }
  25943. function f4(a, b, c, d) {
  25944. addVertex(a);
  25945. addVertex(b);
  25946. addVertex(d);
  25947. addVertex(b);
  25948. addVertex(c);
  25949. addVertex(d);
  25950. const nextIndex = verticesArray.length / 3;
  25951. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  25952. addUV(uvs[0]);
  25953. addUV(uvs[1]);
  25954. addUV(uvs[3]);
  25955. addUV(uvs[1]);
  25956. addUV(uvs[2]);
  25957. addUV(uvs[3]);
  25958. }
  25959. function addVertex(index) {
  25960. verticesArray.push(placeholder[index * 3 + 0]);
  25961. verticesArray.push(placeholder[index * 3 + 1]);
  25962. verticesArray.push(placeholder[index * 3 + 2]);
  25963. }
  25964. function addUV(vector2) {
  25965. uvArray.push(vector2.x);
  25966. uvArray.push(vector2.y);
  25967. }
  25968. }
  25969. }
  25970. toJSON() {
  25971. const data = super.toJSON();
  25972. const shapes = this.parameters.shapes;
  25973. const options = this.parameters.options;
  25974. return toJSON$1(shapes, options, data);
  25975. }
  25976. static fromJSON(data, shapes) {
  25977. const geometryShapes = [];
  25978. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  25979. const shape = shapes[data.shapes[j]];
  25980. geometryShapes.push(shape);
  25981. }
  25982. const extrudePath = data.options.extrudePath;
  25983. if (extrudePath !== undefined) {
  25984. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  25985. }
  25986. return new ExtrudeGeometry(geometryShapes, data.options);
  25987. }
  25988. }
  25989. const WorldUVGenerator = {
  25990. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  25991. const a_x = vertices[indexA * 3];
  25992. const a_y = vertices[indexA * 3 + 1];
  25993. const b_x = vertices[indexB * 3];
  25994. const b_y = vertices[indexB * 3 + 1];
  25995. const c_x = vertices[indexC * 3];
  25996. const c_y = vertices[indexC * 3 + 1];
  25997. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  25998. },
  25999. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  26000. const a_x = vertices[indexA * 3];
  26001. const a_y = vertices[indexA * 3 + 1];
  26002. const a_z = vertices[indexA * 3 + 2];
  26003. const b_x = vertices[indexB * 3];
  26004. const b_y = vertices[indexB * 3 + 1];
  26005. const b_z = vertices[indexB * 3 + 2];
  26006. const c_x = vertices[indexC * 3];
  26007. const c_y = vertices[indexC * 3 + 1];
  26008. const c_z = vertices[indexC * 3 + 2];
  26009. const d_x = vertices[indexD * 3];
  26010. const d_y = vertices[indexD * 3 + 1];
  26011. const d_z = vertices[indexD * 3 + 2];
  26012. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  26013. 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)];
  26014. } else {
  26015. 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)];
  26016. }
  26017. }
  26018. };
  26019. function toJSON$1(shapes, options, data) {
  26020. data.shapes = [];
  26021. if (Array.isArray(shapes)) {
  26022. for (let i = 0, l = shapes.length; i < l; i++) {
  26023. const shape = shapes[i];
  26024. data.shapes.push(shape.uuid);
  26025. }
  26026. } else {
  26027. data.shapes.push(shapes.uuid);
  26028. }
  26029. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  26030. return data;
  26031. }
  26032. class IcosahedronGeometry extends PolyhedronGeometry {
  26033. constructor(radius = 1, detail = 0) {
  26034. const t = (1 + Math.sqrt(5)) / 2;
  26035. const 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];
  26036. const 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];
  26037. super(vertices, indices, radius, detail);
  26038. this.type = 'IcosahedronGeometry';
  26039. this.parameters = {
  26040. radius: radius,
  26041. detail: detail
  26042. };
  26043. }
  26044. static fromJSON(data) {
  26045. return new IcosahedronGeometry(data.radius, data.detail);
  26046. }
  26047. }
  26048. class LatheGeometry extends BufferGeometry {
  26049. constructor(points = [new Vector2(0, 0.5), new Vector2(0.5, 0), new Vector2(0, -0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  26050. super();
  26051. this.type = 'LatheGeometry';
  26052. this.parameters = {
  26053. points: points,
  26054. segments: segments,
  26055. phiStart: phiStart,
  26056. phiLength: phiLength
  26057. };
  26058. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  26059. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  26060. const indices = [];
  26061. const vertices = [];
  26062. const uvs = []; // helper variables
  26063. const inverseSegments = 1.0 / segments;
  26064. const vertex = new Vector3();
  26065. const uv = new Vector2(); // generate vertices and uvs
  26066. for (let i = 0; i <= segments; i++) {
  26067. const phi = phiStart + i * inverseSegments * phiLength;
  26068. const sin = Math.sin(phi);
  26069. const cos = Math.cos(phi);
  26070. for (let j = 0; j <= points.length - 1; j++) {
  26071. // vertex
  26072. vertex.x = points[j].x * sin;
  26073. vertex.y = points[j].y;
  26074. vertex.z = points[j].x * cos;
  26075. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  26076. uv.x = i / segments;
  26077. uv.y = j / (points.length - 1);
  26078. uvs.push(uv.x, uv.y);
  26079. }
  26080. } // indices
  26081. for (let i = 0; i < segments; i++) {
  26082. for (let j = 0; j < points.length - 1; j++) {
  26083. const base = j + i * points.length;
  26084. const a = base;
  26085. const b = base + points.length;
  26086. const c = base + points.length + 1;
  26087. const d = base + 1; // faces
  26088. indices.push(a, b, d);
  26089. indices.push(b, c, d);
  26090. }
  26091. } // build geometry
  26092. this.setIndex(indices);
  26093. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26094. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  26095. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  26096. // because the corresponding vertices are identical (but still have different UVs).
  26097. if (phiLength === Math.PI * 2) {
  26098. const normals = this.attributes.normal.array;
  26099. const n1 = new Vector3();
  26100. const n2 = new Vector3();
  26101. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  26102. const base = segments * points.length * 3;
  26103. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  26104. // select the normal of the vertex in the first line
  26105. n1.x = normals[j + 0];
  26106. n1.y = normals[j + 1];
  26107. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  26108. n2.x = normals[base + j + 0];
  26109. n2.y = normals[base + j + 1];
  26110. n2.z = normals[base + j + 2]; // average normals
  26111. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  26112. normals[j + 0] = normals[base + j + 0] = n.x;
  26113. normals[j + 1] = normals[base + j + 1] = n.y;
  26114. normals[j + 2] = normals[base + j + 2] = n.z;
  26115. }
  26116. }
  26117. }
  26118. static fromJSON(data) {
  26119. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  26120. }
  26121. }
  26122. class OctahedronGeometry extends PolyhedronGeometry {
  26123. constructor(radius = 1, detail = 0) {
  26124. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  26125. const 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];
  26126. super(vertices, indices, radius, detail);
  26127. this.type = 'OctahedronGeometry';
  26128. this.parameters = {
  26129. radius: radius,
  26130. detail: detail
  26131. };
  26132. }
  26133. static fromJSON(data) {
  26134. return new OctahedronGeometry(data.radius, data.detail);
  26135. }
  26136. }
  26137. class RingGeometry extends BufferGeometry {
  26138. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  26139. super();
  26140. this.type = 'RingGeometry';
  26141. this.parameters = {
  26142. innerRadius: innerRadius,
  26143. outerRadius: outerRadius,
  26144. thetaSegments: thetaSegments,
  26145. phiSegments: phiSegments,
  26146. thetaStart: thetaStart,
  26147. thetaLength: thetaLength
  26148. };
  26149. thetaSegments = Math.max(3, thetaSegments);
  26150. phiSegments = Math.max(1, phiSegments); // buffers
  26151. const indices = [];
  26152. const vertices = [];
  26153. const normals = [];
  26154. const uvs = []; // some helper variables
  26155. let radius = innerRadius;
  26156. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  26157. const vertex = new Vector3();
  26158. const uv = new Vector2(); // generate vertices, normals and uvs
  26159. for (let j = 0; j <= phiSegments; j++) {
  26160. for (let i = 0; i <= thetaSegments; i++) {
  26161. // values are generate from the inside of the ring to the outside
  26162. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  26163. vertex.x = radius * Math.cos(segment);
  26164. vertex.y = radius * Math.sin(segment);
  26165. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  26166. normals.push(0, 0, 1); // uv
  26167. uv.x = (vertex.x / outerRadius + 1) / 2;
  26168. uv.y = (vertex.y / outerRadius + 1) / 2;
  26169. uvs.push(uv.x, uv.y);
  26170. } // increase the radius for next row of vertices
  26171. radius += radiusStep;
  26172. } // indices
  26173. for (let j = 0; j < phiSegments; j++) {
  26174. const thetaSegmentLevel = j * (thetaSegments + 1);
  26175. for (let i = 0; i < thetaSegments; i++) {
  26176. const segment = i + thetaSegmentLevel;
  26177. const a = segment;
  26178. const b = segment + thetaSegments + 1;
  26179. const c = segment + thetaSegments + 2;
  26180. const d = segment + 1; // faces
  26181. indices.push(a, b, d);
  26182. indices.push(b, c, d);
  26183. }
  26184. } // build geometry
  26185. this.setIndex(indices);
  26186. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26187. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26188. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  26189. }
  26190. static fromJSON(data) {
  26191. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  26192. }
  26193. }
  26194. class ShapeGeometry extends BufferGeometry {
  26195. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  26196. super();
  26197. this.type = 'ShapeGeometry';
  26198. this.parameters = {
  26199. shapes: shapes,
  26200. curveSegments: curveSegments
  26201. }; // buffers
  26202. const indices = [];
  26203. const vertices = [];
  26204. const normals = [];
  26205. const uvs = []; // helper variables
  26206. let groupStart = 0;
  26207. let groupCount = 0; // allow single and array values for "shapes" parameter
  26208. if (Array.isArray(shapes) === false) {
  26209. addShape(shapes);
  26210. } else {
  26211. for (let i = 0; i < shapes.length; i++) {
  26212. addShape(shapes[i]);
  26213. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  26214. groupStart += groupCount;
  26215. groupCount = 0;
  26216. }
  26217. } // build geometry
  26218. this.setIndex(indices);
  26219. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26220. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26221. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  26222. function addShape(shape) {
  26223. const indexOffset = vertices.length / 3;
  26224. const points = shape.extractPoints(curveSegments);
  26225. let shapeVertices = points.shape;
  26226. const shapeHoles = points.holes; // check direction of vertices
  26227. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  26228. shapeVertices = shapeVertices.reverse();
  26229. }
  26230. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  26231. const shapeHole = shapeHoles[i];
  26232. if (ShapeUtils.isClockWise(shapeHole) === true) {
  26233. shapeHoles[i] = shapeHole.reverse();
  26234. }
  26235. }
  26236. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  26237. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  26238. const shapeHole = shapeHoles[i];
  26239. shapeVertices = shapeVertices.concat(shapeHole);
  26240. } // vertices, normals, uvs
  26241. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  26242. const vertex = shapeVertices[i];
  26243. vertices.push(vertex.x, vertex.y, 0);
  26244. normals.push(0, 0, 1);
  26245. uvs.push(vertex.x, vertex.y); // world uvs
  26246. } // incides
  26247. for (let i = 0, l = faces.length; i < l; i++) {
  26248. const face = faces[i];
  26249. const a = face[0] + indexOffset;
  26250. const b = face[1] + indexOffset;
  26251. const c = face[2] + indexOffset;
  26252. indices.push(a, b, c);
  26253. groupCount += 3;
  26254. }
  26255. }
  26256. }
  26257. toJSON() {
  26258. const data = super.toJSON();
  26259. const shapes = this.parameters.shapes;
  26260. return toJSON(shapes, data);
  26261. }
  26262. static fromJSON(data, shapes) {
  26263. const geometryShapes = [];
  26264. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  26265. const shape = shapes[data.shapes[j]];
  26266. geometryShapes.push(shape);
  26267. }
  26268. return new ShapeGeometry(geometryShapes, data.curveSegments);
  26269. }
  26270. }
  26271. function toJSON(shapes, data) {
  26272. data.shapes = [];
  26273. if (Array.isArray(shapes)) {
  26274. for (let i = 0, l = shapes.length; i < l; i++) {
  26275. const shape = shapes[i];
  26276. data.shapes.push(shape.uuid);
  26277. }
  26278. } else {
  26279. data.shapes.push(shapes.uuid);
  26280. }
  26281. return data;
  26282. }
  26283. class SphereGeometry extends BufferGeometry {
  26284. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  26285. super();
  26286. this.type = 'SphereGeometry';
  26287. this.parameters = {
  26288. radius: radius,
  26289. widthSegments: widthSegments,
  26290. heightSegments: heightSegments,
  26291. phiStart: phiStart,
  26292. phiLength: phiLength,
  26293. thetaStart: thetaStart,
  26294. thetaLength: thetaLength
  26295. };
  26296. widthSegments = Math.max(3, Math.floor(widthSegments));
  26297. heightSegments = Math.max(2, Math.floor(heightSegments));
  26298. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  26299. let index = 0;
  26300. const grid = [];
  26301. const vertex = new Vector3();
  26302. const normal = new Vector3(); // buffers
  26303. const indices = [];
  26304. const vertices = [];
  26305. const normals = [];
  26306. const uvs = []; // generate vertices, normals and uvs
  26307. for (let iy = 0; iy <= heightSegments; iy++) {
  26308. const verticesRow = [];
  26309. const v = iy / heightSegments; // special case for the poles
  26310. let uOffset = 0;
  26311. if (iy == 0 && thetaStart == 0) {
  26312. uOffset = 0.5 / widthSegments;
  26313. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  26314. uOffset = -0.5 / widthSegments;
  26315. }
  26316. for (let ix = 0; ix <= widthSegments; ix++) {
  26317. const u = ix / widthSegments; // vertex
  26318. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  26319. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  26320. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  26321. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  26322. normal.copy(vertex).normalize();
  26323. normals.push(normal.x, normal.y, normal.z); // uv
  26324. uvs.push(u + uOffset, 1 - v);
  26325. verticesRow.push(index++);
  26326. }
  26327. grid.push(verticesRow);
  26328. } // indices
  26329. for (let iy = 0; iy < heightSegments; iy++) {
  26330. for (let ix = 0; ix < widthSegments; ix++) {
  26331. const a = grid[iy][ix + 1];
  26332. const b = grid[iy][ix];
  26333. const c = grid[iy + 1][ix];
  26334. const d = grid[iy + 1][ix + 1];
  26335. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  26336. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  26337. }
  26338. } // build geometry
  26339. this.setIndex(indices);
  26340. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26341. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26342. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  26343. }
  26344. static fromJSON(data) {
  26345. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  26346. }
  26347. }
  26348. class TetrahedronGeometry extends PolyhedronGeometry {
  26349. constructor(radius = 1, detail = 0) {
  26350. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  26351. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  26352. super(vertices, indices, radius, detail);
  26353. this.type = 'TetrahedronGeometry';
  26354. this.parameters = {
  26355. radius: radius,
  26356. detail: detail
  26357. };
  26358. }
  26359. static fromJSON(data) {
  26360. return new TetrahedronGeometry(data.radius, data.detail);
  26361. }
  26362. }
  26363. class TorusGeometry extends BufferGeometry {
  26364. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  26365. super();
  26366. this.type = 'TorusGeometry';
  26367. this.parameters = {
  26368. radius: radius,
  26369. tube: tube,
  26370. radialSegments: radialSegments,
  26371. tubularSegments: tubularSegments,
  26372. arc: arc
  26373. };
  26374. radialSegments = Math.floor(radialSegments);
  26375. tubularSegments = Math.floor(tubularSegments); // buffers
  26376. const indices = [];
  26377. const vertices = [];
  26378. const normals = [];
  26379. const uvs = []; // helper variables
  26380. const center = new Vector3();
  26381. const vertex = new Vector3();
  26382. const normal = new Vector3(); // generate vertices, normals and uvs
  26383. for (let j = 0; j <= radialSegments; j++) {
  26384. for (let i = 0; i <= tubularSegments; i++) {
  26385. const u = i / tubularSegments * arc;
  26386. const v = j / radialSegments * Math.PI * 2; // vertex
  26387. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  26388. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  26389. vertex.z = tube * Math.sin(v);
  26390. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  26391. center.x = radius * Math.cos(u);
  26392. center.y = radius * Math.sin(u);
  26393. normal.subVectors(vertex, center).normalize();
  26394. normals.push(normal.x, normal.y, normal.z); // uv
  26395. uvs.push(i / tubularSegments);
  26396. uvs.push(j / radialSegments);
  26397. }
  26398. } // generate indices
  26399. for (let j = 1; j <= radialSegments; j++) {
  26400. for (let i = 1; i <= tubularSegments; i++) {
  26401. // indices
  26402. const a = (tubularSegments + 1) * j + i - 1;
  26403. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  26404. const c = (tubularSegments + 1) * (j - 1) + i;
  26405. const d = (tubularSegments + 1) * j + i; // faces
  26406. indices.push(a, b, d);
  26407. indices.push(b, c, d);
  26408. }
  26409. } // build geometry
  26410. this.setIndex(indices);
  26411. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26412. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26413. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  26414. }
  26415. static fromJSON(data) {
  26416. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  26417. }
  26418. }
  26419. class TorusKnotGeometry extends BufferGeometry {
  26420. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  26421. super();
  26422. this.type = 'TorusKnotGeometry';
  26423. this.parameters = {
  26424. radius: radius,
  26425. tube: tube,
  26426. tubularSegments: tubularSegments,
  26427. radialSegments: radialSegments,
  26428. p: p,
  26429. q: q
  26430. };
  26431. tubularSegments = Math.floor(tubularSegments);
  26432. radialSegments = Math.floor(radialSegments); // buffers
  26433. const indices = [];
  26434. const vertices = [];
  26435. const normals = [];
  26436. const uvs = []; // helper variables
  26437. const vertex = new Vector3();
  26438. const normal = new Vector3();
  26439. const P1 = new Vector3();
  26440. const P2 = new Vector3();
  26441. const B = new Vector3();
  26442. const T = new Vector3();
  26443. const N = new Vector3(); // generate vertices, normals and uvs
  26444. for (let i = 0; i <= tubularSegments; ++i) {
  26445. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  26446. const 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.
  26447. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26448. calculatePositionOnCurve(u, p, q, radius, P1);
  26449. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  26450. T.subVectors(P2, P1);
  26451. N.addVectors(P2, P1);
  26452. B.crossVectors(T, N);
  26453. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  26454. B.normalize();
  26455. N.normalize();
  26456. for (let j = 0; j <= radialSegments; ++j) {
  26457. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26458. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26459. const v = j / radialSegments * Math.PI * 2;
  26460. const cx = -tube * Math.cos(v);
  26461. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  26462. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  26463. vertex.x = P1.x + (cx * N.x + cy * B.x);
  26464. vertex.y = P1.y + (cx * N.y + cy * B.y);
  26465. vertex.z = P1.z + (cx * N.z + cy * B.z);
  26466. 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)
  26467. normal.subVectors(vertex, P1).normalize();
  26468. normals.push(normal.x, normal.y, normal.z); // uv
  26469. uvs.push(i / tubularSegments);
  26470. uvs.push(j / radialSegments);
  26471. }
  26472. } // generate indices
  26473. for (let j = 1; j <= tubularSegments; j++) {
  26474. for (let i = 1; i <= radialSegments; i++) {
  26475. // indices
  26476. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  26477. const b = (radialSegments + 1) * j + (i - 1);
  26478. const c = (radialSegments + 1) * j + i;
  26479. const d = (radialSegments + 1) * (j - 1) + i; // faces
  26480. indices.push(a, b, d);
  26481. indices.push(b, c, d);
  26482. }
  26483. } // build geometry
  26484. this.setIndex(indices);
  26485. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26486. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26487. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  26488. function calculatePositionOnCurve(u, p, q, radius, position) {
  26489. const cu = Math.cos(u);
  26490. const su = Math.sin(u);
  26491. const quOverP = q / p * u;
  26492. const cs = Math.cos(quOverP);
  26493. position.x = radius * (2 + cs) * 0.5 * cu;
  26494. position.y = radius * (2 + cs) * su * 0.5;
  26495. position.z = radius * Math.sin(quOverP) * 0.5;
  26496. }
  26497. }
  26498. static fromJSON(data) {
  26499. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  26500. }
  26501. }
  26502. class TubeGeometry extends BufferGeometry {
  26503. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  26504. super();
  26505. this.type = 'TubeGeometry';
  26506. this.parameters = {
  26507. path: path,
  26508. tubularSegments: tubularSegments,
  26509. radius: radius,
  26510. radialSegments: radialSegments,
  26511. closed: closed
  26512. };
  26513. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  26514. this.tangents = frames.tangents;
  26515. this.normals = frames.normals;
  26516. this.binormals = frames.binormals; // helper variables
  26517. const vertex = new Vector3();
  26518. const normal = new Vector3();
  26519. const uv = new Vector2();
  26520. let P = new Vector3(); // buffer
  26521. const vertices = [];
  26522. const normals = [];
  26523. const uvs = [];
  26524. const indices = []; // create buffer data
  26525. generateBufferData(); // build geometry
  26526. this.setIndex(indices);
  26527. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26528. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  26529. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  26530. function generateBufferData() {
  26531. for (let i = 0; i < tubularSegments; i++) {
  26532. generateSegment(i);
  26533. } // if the geometry is not closed, generate the last row of vertices and normals
  26534. // at the regular position on the given path
  26535. //
  26536. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26537. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  26538. // this makes it easy compute correct values for closed geometries
  26539. generateUVs(); // finally create faces
  26540. generateIndices();
  26541. }
  26542. function generateSegment(i) {
  26543. // we use getPointAt to sample evenly distributed points from the given path
  26544. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  26545. const N = frames.normals[i];
  26546. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  26547. for (let j = 0; j <= radialSegments; j++) {
  26548. const v = j / radialSegments * Math.PI * 2;
  26549. const sin = Math.sin(v);
  26550. const cos = -Math.cos(v); // normal
  26551. normal.x = cos * N.x + sin * B.x;
  26552. normal.y = cos * N.y + sin * B.y;
  26553. normal.z = cos * N.z + sin * B.z;
  26554. normal.normalize();
  26555. normals.push(normal.x, normal.y, normal.z); // vertex
  26556. vertex.x = P.x + radius * normal.x;
  26557. vertex.y = P.y + radius * normal.y;
  26558. vertex.z = P.z + radius * normal.z;
  26559. vertices.push(vertex.x, vertex.y, vertex.z);
  26560. }
  26561. }
  26562. function generateIndices() {
  26563. for (let j = 1; j <= tubularSegments; j++) {
  26564. for (let i = 1; i <= radialSegments; i++) {
  26565. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  26566. const b = (radialSegments + 1) * j + (i - 1);
  26567. const c = (radialSegments + 1) * j + i;
  26568. const d = (radialSegments + 1) * (j - 1) + i; // faces
  26569. indices.push(a, b, d);
  26570. indices.push(b, c, d);
  26571. }
  26572. }
  26573. }
  26574. function generateUVs() {
  26575. for (let i = 0; i <= tubularSegments; i++) {
  26576. for (let j = 0; j <= radialSegments; j++) {
  26577. uv.x = i / tubularSegments;
  26578. uv.y = j / radialSegments;
  26579. uvs.push(uv.x, uv.y);
  26580. }
  26581. }
  26582. }
  26583. }
  26584. toJSON() {
  26585. const data = super.toJSON();
  26586. data.path = this.parameters.path.toJSON();
  26587. return data;
  26588. }
  26589. static fromJSON(data) {
  26590. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26591. // User defined curves or instances of CurvePath will not be deserialized.
  26592. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  26593. }
  26594. }
  26595. class WireframeGeometry extends BufferGeometry {
  26596. constructor(geometry = null) {
  26597. super();
  26598. this.type = 'WireframeGeometry';
  26599. this.parameters = {
  26600. geometry: geometry
  26601. };
  26602. if (geometry !== null) {
  26603. // buffer
  26604. const vertices = [];
  26605. const edges = new Set(); // helper variables
  26606. const start = new Vector3();
  26607. const end = new Vector3();
  26608. if (geometry.index !== null) {
  26609. // indexed BufferGeometry
  26610. const position = geometry.attributes.position;
  26611. const indices = geometry.index;
  26612. let groups = geometry.groups;
  26613. if (groups.length === 0) {
  26614. groups = [{
  26615. start: 0,
  26616. count: indices.count,
  26617. materialIndex: 0
  26618. }];
  26619. } // create a data structure that contains all eges without duplicates
  26620. for (let o = 0, ol = groups.length; o < ol; ++o) {
  26621. const group = groups[o];
  26622. const groupStart = group.start;
  26623. const groupCount = group.count;
  26624. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  26625. for (let j = 0; j < 3; j++) {
  26626. const index1 = indices.getX(i + j);
  26627. const index2 = indices.getX(i + (j + 1) % 3);
  26628. start.fromBufferAttribute(position, index1);
  26629. end.fromBufferAttribute(position, index2);
  26630. if (isUniqueEdge(start, end, edges) === true) {
  26631. vertices.push(start.x, start.y, start.z);
  26632. vertices.push(end.x, end.y, end.z);
  26633. }
  26634. }
  26635. }
  26636. }
  26637. } else {
  26638. // non-indexed BufferGeometry
  26639. const position = geometry.attributes.position;
  26640. for (let i = 0, l = position.count / 3; i < l; i++) {
  26641. for (let j = 0; j < 3; j++) {
  26642. // three edges per triangle, an edge is represented as (index1, index2)
  26643. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26644. const index1 = 3 * i + j;
  26645. const index2 = 3 * i + (j + 1) % 3;
  26646. start.fromBufferAttribute(position, index1);
  26647. end.fromBufferAttribute(position, index2);
  26648. if (isUniqueEdge(start, end, edges) === true) {
  26649. vertices.push(start.x, start.y, start.z);
  26650. vertices.push(end.x, end.y, end.z);
  26651. }
  26652. }
  26653. }
  26654. } // build geometry
  26655. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26656. }
  26657. }
  26658. }
  26659. function isUniqueEdge(start, end, edges) {
  26660. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26661. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26662. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  26663. return false;
  26664. } else {
  26665. edges.add(hash1, hash2);
  26666. return true;
  26667. }
  26668. }
  26669. var Geometries = /*#__PURE__*/Object.freeze({
  26670. __proto__: null,
  26671. BoxGeometry: BoxGeometry,
  26672. BoxBufferGeometry: BoxGeometry,
  26673. CircleGeometry: CircleGeometry,
  26674. CircleBufferGeometry: CircleGeometry,
  26675. ConeGeometry: ConeGeometry,
  26676. ConeBufferGeometry: ConeGeometry,
  26677. CylinderGeometry: CylinderGeometry,
  26678. CylinderBufferGeometry: CylinderGeometry,
  26679. DodecahedronGeometry: DodecahedronGeometry,
  26680. DodecahedronBufferGeometry: DodecahedronGeometry,
  26681. EdgesGeometry: EdgesGeometry,
  26682. ExtrudeGeometry: ExtrudeGeometry,
  26683. ExtrudeBufferGeometry: ExtrudeGeometry,
  26684. IcosahedronGeometry: IcosahedronGeometry,
  26685. IcosahedronBufferGeometry: IcosahedronGeometry,
  26686. LatheGeometry: LatheGeometry,
  26687. LatheBufferGeometry: LatheGeometry,
  26688. OctahedronGeometry: OctahedronGeometry,
  26689. OctahedronBufferGeometry: OctahedronGeometry,
  26690. PlaneGeometry: PlaneGeometry,
  26691. PlaneBufferGeometry: PlaneGeometry,
  26692. PolyhedronGeometry: PolyhedronGeometry,
  26693. PolyhedronBufferGeometry: PolyhedronGeometry,
  26694. RingGeometry: RingGeometry,
  26695. RingBufferGeometry: RingGeometry,
  26696. ShapeGeometry: ShapeGeometry,
  26697. ShapeBufferGeometry: ShapeGeometry,
  26698. SphereGeometry: SphereGeometry,
  26699. SphereBufferGeometry: SphereGeometry,
  26700. TetrahedronGeometry: TetrahedronGeometry,
  26701. TetrahedronBufferGeometry: TetrahedronGeometry,
  26702. TorusGeometry: TorusGeometry,
  26703. TorusBufferGeometry: TorusGeometry,
  26704. TorusKnotGeometry: TorusKnotGeometry,
  26705. TorusKnotBufferGeometry: TorusKnotGeometry,
  26706. TubeGeometry: TubeGeometry,
  26707. TubeBufferGeometry: TubeGeometry,
  26708. WireframeGeometry: WireframeGeometry
  26709. });
  26710. /**
  26711. * parameters = {
  26712. * color: <THREE.Color>
  26713. * }
  26714. */
  26715. class ShadowMaterial extends Material {
  26716. constructor(parameters) {
  26717. super();
  26718. this.type = 'ShadowMaterial';
  26719. this.color = new Color(0x000000);
  26720. this.transparent = true;
  26721. this.setValues(parameters);
  26722. }
  26723. copy(source) {
  26724. super.copy(source);
  26725. this.color.copy(source.color);
  26726. return this;
  26727. }
  26728. }
  26729. ShadowMaterial.prototype.isShadowMaterial = true;
  26730. /**
  26731. * parameters = {
  26732. * color: <hex>,
  26733. * roughness: <float>,
  26734. * metalness: <float>,
  26735. * opacity: <float>,
  26736. *
  26737. * map: new THREE.Texture( <Image> ),
  26738. *
  26739. * lightMap: new THREE.Texture( <Image> ),
  26740. * lightMapIntensity: <float>
  26741. *
  26742. * aoMap: new THREE.Texture( <Image> ),
  26743. * aoMapIntensity: <float>
  26744. *
  26745. * emissive: <hex>,
  26746. * emissiveIntensity: <float>
  26747. * emissiveMap: new THREE.Texture( <Image> ),
  26748. *
  26749. * bumpMap: new THREE.Texture( <Image> ),
  26750. * bumpScale: <float>,
  26751. *
  26752. * normalMap: new THREE.Texture( <Image> ),
  26753. * normalMapType: THREE.TangentSpaceNormalMap,
  26754. * normalScale: <Vector2>,
  26755. *
  26756. * displacementMap: new THREE.Texture( <Image> ),
  26757. * displacementScale: <float>,
  26758. * displacementBias: <float>,
  26759. *
  26760. * roughnessMap: new THREE.Texture( <Image> ),
  26761. *
  26762. * metalnessMap: new THREE.Texture( <Image> ),
  26763. *
  26764. * alphaMap: new THREE.Texture( <Image> ),
  26765. *
  26766. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  26767. * envMapIntensity: <float>
  26768. *
  26769. * refractionRatio: <float>,
  26770. *
  26771. * wireframe: <boolean>,
  26772. * wireframeLinewidth: <float>,
  26773. *
  26774. * flatShading: <bool>
  26775. * }
  26776. */
  26777. class MeshStandardMaterial extends Material {
  26778. constructor(parameters) {
  26779. super();
  26780. this.defines = {
  26781. 'STANDARD': ''
  26782. };
  26783. this.type = 'MeshStandardMaterial';
  26784. this.color = new Color(0xffffff); // diffuse
  26785. this.roughness = 1.0;
  26786. this.metalness = 0.0;
  26787. this.map = null;
  26788. this.lightMap = null;
  26789. this.lightMapIntensity = 1.0;
  26790. this.aoMap = null;
  26791. this.aoMapIntensity = 1.0;
  26792. this.emissive = new Color(0x000000);
  26793. this.emissiveIntensity = 1.0;
  26794. this.emissiveMap = null;
  26795. this.bumpMap = null;
  26796. this.bumpScale = 1;
  26797. this.normalMap = null;
  26798. this.normalMapType = TangentSpaceNormalMap;
  26799. this.normalScale = new Vector2(1, 1);
  26800. this.displacementMap = null;
  26801. this.displacementScale = 1;
  26802. this.displacementBias = 0;
  26803. this.roughnessMap = null;
  26804. this.metalnessMap = null;
  26805. this.alphaMap = null;
  26806. this.envMap = null;
  26807. this.envMapIntensity = 1.0;
  26808. this.refractionRatio = 0.98;
  26809. this.wireframe = false;
  26810. this.wireframeLinewidth = 1;
  26811. this.wireframeLinecap = 'round';
  26812. this.wireframeLinejoin = 'round';
  26813. this.flatShading = false;
  26814. this.setValues(parameters);
  26815. }
  26816. copy(source) {
  26817. super.copy(source);
  26818. this.defines = {
  26819. 'STANDARD': ''
  26820. };
  26821. this.color.copy(source.color);
  26822. this.roughness = source.roughness;
  26823. this.metalness = source.metalness;
  26824. this.map = source.map;
  26825. this.lightMap = source.lightMap;
  26826. this.lightMapIntensity = source.lightMapIntensity;
  26827. this.aoMap = source.aoMap;
  26828. this.aoMapIntensity = source.aoMapIntensity;
  26829. this.emissive.copy(source.emissive);
  26830. this.emissiveMap = source.emissiveMap;
  26831. this.emissiveIntensity = source.emissiveIntensity;
  26832. this.bumpMap = source.bumpMap;
  26833. this.bumpScale = source.bumpScale;
  26834. this.normalMap = source.normalMap;
  26835. this.normalMapType = source.normalMapType;
  26836. this.normalScale.copy(source.normalScale);
  26837. this.displacementMap = source.displacementMap;
  26838. this.displacementScale = source.displacementScale;
  26839. this.displacementBias = source.displacementBias;
  26840. this.roughnessMap = source.roughnessMap;
  26841. this.metalnessMap = source.metalnessMap;
  26842. this.alphaMap = source.alphaMap;
  26843. this.envMap = source.envMap;
  26844. this.envMapIntensity = source.envMapIntensity;
  26845. this.refractionRatio = source.refractionRatio;
  26846. this.wireframe = source.wireframe;
  26847. this.wireframeLinewidth = source.wireframeLinewidth;
  26848. this.wireframeLinecap = source.wireframeLinecap;
  26849. this.wireframeLinejoin = source.wireframeLinejoin;
  26850. this.flatShading = source.flatShading;
  26851. return this;
  26852. }
  26853. }
  26854. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  26855. /**
  26856. * parameters = {
  26857. * clearcoat: <float>,
  26858. * clearcoatMap: new THREE.Texture( <Image> ),
  26859. * clearcoatRoughness: <float>,
  26860. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  26861. * clearcoatNormalScale: <Vector2>,
  26862. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  26863. *
  26864. * ior: <float>,
  26865. * reflectivity: <float>,
  26866. *
  26867. * sheen: <float>,
  26868. * sheenTint: <Color>,
  26869. * sheenRoughness: <float>,
  26870. *
  26871. * transmission: <float>,
  26872. * transmissionMap: new THREE.Texture( <Image> ),
  26873. *
  26874. * thickness: <float>,
  26875. * thicknessMap: new THREE.Texture( <Image> ),
  26876. * attenuationDistance: <float>,
  26877. * attenuationTint: <Color>,
  26878. *
  26879. * specularIntensity: <float>,
  26880. * specularIntensityhMap: new THREE.Texture( <Image> ),
  26881. * specularTint: <Color>,
  26882. * specularTintMap: new THREE.Texture( <Image> )
  26883. * }
  26884. */
  26885. class MeshPhysicalMaterial extends MeshStandardMaterial {
  26886. constructor(parameters) {
  26887. super();
  26888. this.defines = {
  26889. 'STANDARD': '',
  26890. 'PHYSICAL': ''
  26891. };
  26892. this.type = 'MeshPhysicalMaterial';
  26893. this.clearcoatMap = null;
  26894. this.clearcoatRoughness = 0.0;
  26895. this.clearcoatRoughnessMap = null;
  26896. this.clearcoatNormalScale = new Vector2(1, 1);
  26897. this.clearcoatNormalMap = null;
  26898. this.ior = 1.5;
  26899. Object.defineProperty(this, 'reflectivity', {
  26900. get: function () {
  26901. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  26902. },
  26903. set: function (reflectivity) {
  26904. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  26905. }
  26906. });
  26907. this.sheenTint = new Color(0x000000);
  26908. this.sheenRoughness = 1.0;
  26909. this.transmissionMap = null;
  26910. this.thickness = 0.01;
  26911. this.thicknessMap = null;
  26912. this.attenuationDistance = 0.0;
  26913. this.attenuationTint = new Color(1, 1, 1);
  26914. this.specularIntensity = 1.0;
  26915. this.specularIntensityMap = null;
  26916. this.specularTint = new Color(1, 1, 1);
  26917. this.specularTintMap = null;
  26918. this._sheen = 0.0;
  26919. this._clearcoat = 0;
  26920. this._transmission = 0;
  26921. this.setValues(parameters);
  26922. }
  26923. get sheen() {
  26924. return this._sheen;
  26925. }
  26926. set sheen(value) {
  26927. if (this._sheen > 0 !== value > 0) {
  26928. this.version++;
  26929. }
  26930. this._sheen = value;
  26931. }
  26932. get clearcoat() {
  26933. return this._clearcoat;
  26934. }
  26935. set clearcoat(value) {
  26936. if (this._clearcoat > 0 !== value > 0) {
  26937. this.version++;
  26938. }
  26939. this._clearcoat = value;
  26940. }
  26941. get transmission() {
  26942. return this._transmission;
  26943. }
  26944. set transmission(value) {
  26945. if (this._transmission > 0 !== value > 0) {
  26946. this.version++;
  26947. }
  26948. this._transmission = value;
  26949. }
  26950. copy(source) {
  26951. super.copy(source);
  26952. this.defines = {
  26953. 'STANDARD': '',
  26954. 'PHYSICAL': ''
  26955. };
  26956. this.clearcoat = source.clearcoat;
  26957. this.clearcoatMap = source.clearcoatMap;
  26958. this.clearcoatRoughness = source.clearcoatRoughness;
  26959. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  26960. this.clearcoatNormalMap = source.clearcoatNormalMap;
  26961. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  26962. this.ior = source.ior;
  26963. this.sheen = source.sheen;
  26964. this.sheenTint.copy(source.sheenTint);
  26965. this.sheenRoughness = source.sheenRoughness;
  26966. this.transmission = source.transmission;
  26967. this.transmissionMap = source.transmissionMap;
  26968. this.thickness = source.thickness;
  26969. this.thicknessMap = source.thicknessMap;
  26970. this.attenuationDistance = source.attenuationDistance;
  26971. this.attenuationTint.copy(source.attenuationTint);
  26972. this.specularIntensity = source.specularIntensity;
  26973. this.specularIntensityMap = source.specularIntensityMap;
  26974. this.specularTint.copy(source.specularTint);
  26975. this.specularTintMap = source.specularTintMap;
  26976. return this;
  26977. }
  26978. }
  26979. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  26980. /**
  26981. * parameters = {
  26982. * color: <hex>,
  26983. * specular: <hex>,
  26984. * shininess: <float>,
  26985. * opacity: <float>,
  26986. *
  26987. * map: new THREE.Texture( <Image> ),
  26988. *
  26989. * lightMap: new THREE.Texture( <Image> ),
  26990. * lightMapIntensity: <float>
  26991. *
  26992. * aoMap: new THREE.Texture( <Image> ),
  26993. * aoMapIntensity: <float>
  26994. *
  26995. * emissive: <hex>,
  26996. * emissiveIntensity: <float>
  26997. * emissiveMap: new THREE.Texture( <Image> ),
  26998. *
  26999. * bumpMap: new THREE.Texture( <Image> ),
  27000. * bumpScale: <float>,
  27001. *
  27002. * normalMap: new THREE.Texture( <Image> ),
  27003. * normalMapType: THREE.TangentSpaceNormalMap,
  27004. * normalScale: <Vector2>,
  27005. *
  27006. * displacementMap: new THREE.Texture( <Image> ),
  27007. * displacementScale: <float>,
  27008. * displacementBias: <float>,
  27009. *
  27010. * specularMap: new THREE.Texture( <Image> ),
  27011. *
  27012. * alphaMap: new THREE.Texture( <Image> ),
  27013. *
  27014. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  27015. * combine: THREE.MultiplyOperation,
  27016. * reflectivity: <float>,
  27017. * refractionRatio: <float>,
  27018. *
  27019. * wireframe: <boolean>,
  27020. * wireframeLinewidth: <float>,
  27021. *
  27022. * flatShading: <bool>
  27023. * }
  27024. */
  27025. class MeshPhongMaterial extends Material {
  27026. constructor(parameters) {
  27027. super();
  27028. this.type = 'MeshPhongMaterial';
  27029. this.color = new Color(0xffffff); // diffuse
  27030. this.specular = new Color(0x111111);
  27031. this.shininess = 30;
  27032. this.map = null;
  27033. this.lightMap = null;
  27034. this.lightMapIntensity = 1.0;
  27035. this.aoMap = null;
  27036. this.aoMapIntensity = 1.0;
  27037. this.emissive = new Color(0x000000);
  27038. this.emissiveIntensity = 1.0;
  27039. this.emissiveMap = null;
  27040. this.bumpMap = null;
  27041. this.bumpScale = 1;
  27042. this.normalMap = null;
  27043. this.normalMapType = TangentSpaceNormalMap;
  27044. this.normalScale = new Vector2(1, 1);
  27045. this.displacementMap = null;
  27046. this.displacementScale = 1;
  27047. this.displacementBias = 0;
  27048. this.specularMap = null;
  27049. this.alphaMap = null;
  27050. this.envMap = null;
  27051. this.combine = MultiplyOperation;
  27052. this.reflectivity = 1;
  27053. this.refractionRatio = 0.98;
  27054. this.wireframe = false;
  27055. this.wireframeLinewidth = 1;
  27056. this.wireframeLinecap = 'round';
  27057. this.wireframeLinejoin = 'round';
  27058. this.flatShading = false;
  27059. this.setValues(parameters);
  27060. }
  27061. copy(source) {
  27062. super.copy(source);
  27063. this.color.copy(source.color);
  27064. this.specular.copy(source.specular);
  27065. this.shininess = source.shininess;
  27066. this.map = source.map;
  27067. this.lightMap = source.lightMap;
  27068. this.lightMapIntensity = source.lightMapIntensity;
  27069. this.aoMap = source.aoMap;
  27070. this.aoMapIntensity = source.aoMapIntensity;
  27071. this.emissive.copy(source.emissive);
  27072. this.emissiveMap = source.emissiveMap;
  27073. this.emissiveIntensity = source.emissiveIntensity;
  27074. this.bumpMap = source.bumpMap;
  27075. this.bumpScale = source.bumpScale;
  27076. this.normalMap = source.normalMap;
  27077. this.normalMapType = source.normalMapType;
  27078. this.normalScale.copy(source.normalScale);
  27079. this.displacementMap = source.displacementMap;
  27080. this.displacementScale = source.displacementScale;
  27081. this.displacementBias = source.displacementBias;
  27082. this.specularMap = source.specularMap;
  27083. this.alphaMap = source.alphaMap;
  27084. this.envMap = source.envMap;
  27085. this.combine = source.combine;
  27086. this.reflectivity = source.reflectivity;
  27087. this.refractionRatio = source.refractionRatio;
  27088. this.wireframe = source.wireframe;
  27089. this.wireframeLinewidth = source.wireframeLinewidth;
  27090. this.wireframeLinecap = source.wireframeLinecap;
  27091. this.wireframeLinejoin = source.wireframeLinejoin;
  27092. this.flatShading = source.flatShading;
  27093. return this;
  27094. }
  27095. }
  27096. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  27097. /**
  27098. * parameters = {
  27099. * color: <hex>,
  27100. *
  27101. * map: new THREE.Texture( <Image> ),
  27102. * gradientMap: new THREE.Texture( <Image> ),
  27103. *
  27104. * lightMap: new THREE.Texture( <Image> ),
  27105. * lightMapIntensity: <float>
  27106. *
  27107. * aoMap: new THREE.Texture( <Image> ),
  27108. * aoMapIntensity: <float>
  27109. *
  27110. * emissive: <hex>,
  27111. * emissiveIntensity: <float>
  27112. * emissiveMap: new THREE.Texture( <Image> ),
  27113. *
  27114. * bumpMap: new THREE.Texture( <Image> ),
  27115. * bumpScale: <float>,
  27116. *
  27117. * normalMap: new THREE.Texture( <Image> ),
  27118. * normalMapType: THREE.TangentSpaceNormalMap,
  27119. * normalScale: <Vector2>,
  27120. *
  27121. * displacementMap: new THREE.Texture( <Image> ),
  27122. * displacementScale: <float>,
  27123. * displacementBias: <float>,
  27124. *
  27125. * alphaMap: new THREE.Texture( <Image> ),
  27126. *
  27127. * wireframe: <boolean>,
  27128. * wireframeLinewidth: <float>,
  27129. *
  27130. * }
  27131. */
  27132. class MeshToonMaterial extends Material {
  27133. constructor(parameters) {
  27134. super();
  27135. this.defines = {
  27136. 'TOON': ''
  27137. };
  27138. this.type = 'MeshToonMaterial';
  27139. this.color = new Color(0xffffff);
  27140. this.map = null;
  27141. this.gradientMap = null;
  27142. this.lightMap = null;
  27143. this.lightMapIntensity = 1.0;
  27144. this.aoMap = null;
  27145. this.aoMapIntensity = 1.0;
  27146. this.emissive = new Color(0x000000);
  27147. this.emissiveIntensity = 1.0;
  27148. this.emissiveMap = null;
  27149. this.bumpMap = null;
  27150. this.bumpScale = 1;
  27151. this.normalMap = null;
  27152. this.normalMapType = TangentSpaceNormalMap;
  27153. this.normalScale = new Vector2(1, 1);
  27154. this.displacementMap = null;
  27155. this.displacementScale = 1;
  27156. this.displacementBias = 0;
  27157. this.alphaMap = null;
  27158. this.wireframe = false;
  27159. this.wireframeLinewidth = 1;
  27160. this.wireframeLinecap = 'round';
  27161. this.wireframeLinejoin = 'round';
  27162. this.setValues(parameters);
  27163. }
  27164. copy(source) {
  27165. super.copy(source);
  27166. this.color.copy(source.color);
  27167. this.map = source.map;
  27168. this.gradientMap = source.gradientMap;
  27169. this.lightMap = source.lightMap;
  27170. this.lightMapIntensity = source.lightMapIntensity;
  27171. this.aoMap = source.aoMap;
  27172. this.aoMapIntensity = source.aoMapIntensity;
  27173. this.emissive.copy(source.emissive);
  27174. this.emissiveMap = source.emissiveMap;
  27175. this.emissiveIntensity = source.emissiveIntensity;
  27176. this.bumpMap = source.bumpMap;
  27177. this.bumpScale = source.bumpScale;
  27178. this.normalMap = source.normalMap;
  27179. this.normalMapType = source.normalMapType;
  27180. this.normalScale.copy(source.normalScale);
  27181. this.displacementMap = source.displacementMap;
  27182. this.displacementScale = source.displacementScale;
  27183. this.displacementBias = source.displacementBias;
  27184. this.alphaMap = source.alphaMap;
  27185. this.wireframe = source.wireframe;
  27186. this.wireframeLinewidth = source.wireframeLinewidth;
  27187. this.wireframeLinecap = source.wireframeLinecap;
  27188. this.wireframeLinejoin = source.wireframeLinejoin;
  27189. return this;
  27190. }
  27191. }
  27192. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  27193. /**
  27194. * parameters = {
  27195. * opacity: <float>,
  27196. *
  27197. * bumpMap: new THREE.Texture( <Image> ),
  27198. * bumpScale: <float>,
  27199. *
  27200. * normalMap: new THREE.Texture( <Image> ),
  27201. * normalMapType: THREE.TangentSpaceNormalMap,
  27202. * normalScale: <Vector2>,
  27203. *
  27204. * displacementMap: new THREE.Texture( <Image> ),
  27205. * displacementScale: <float>,
  27206. * displacementBias: <float>,
  27207. *
  27208. * wireframe: <boolean>,
  27209. * wireframeLinewidth: <float>
  27210. *
  27211. * flatShading: <bool>
  27212. * }
  27213. */
  27214. class MeshNormalMaterial extends Material {
  27215. constructor(parameters) {
  27216. super();
  27217. this.type = 'MeshNormalMaterial';
  27218. this.bumpMap = null;
  27219. this.bumpScale = 1;
  27220. this.normalMap = null;
  27221. this.normalMapType = TangentSpaceNormalMap;
  27222. this.normalScale = new Vector2(1, 1);
  27223. this.displacementMap = null;
  27224. this.displacementScale = 1;
  27225. this.displacementBias = 0;
  27226. this.wireframe = false;
  27227. this.wireframeLinewidth = 1;
  27228. this.fog = false;
  27229. this.flatShading = false;
  27230. this.setValues(parameters);
  27231. }
  27232. copy(source) {
  27233. super.copy(source);
  27234. this.bumpMap = source.bumpMap;
  27235. this.bumpScale = source.bumpScale;
  27236. this.normalMap = source.normalMap;
  27237. this.normalMapType = source.normalMapType;
  27238. this.normalScale.copy(source.normalScale);
  27239. this.displacementMap = source.displacementMap;
  27240. this.displacementScale = source.displacementScale;
  27241. this.displacementBias = source.displacementBias;
  27242. this.wireframe = source.wireframe;
  27243. this.wireframeLinewidth = source.wireframeLinewidth;
  27244. this.flatShading = source.flatShading;
  27245. return this;
  27246. }
  27247. }
  27248. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  27249. /**
  27250. * parameters = {
  27251. * color: <hex>,
  27252. * opacity: <float>,
  27253. *
  27254. * map: new THREE.Texture( <Image> ),
  27255. *
  27256. * lightMap: new THREE.Texture( <Image> ),
  27257. * lightMapIntensity: <float>
  27258. *
  27259. * aoMap: new THREE.Texture( <Image> ),
  27260. * aoMapIntensity: <float>
  27261. *
  27262. * emissive: <hex>,
  27263. * emissiveIntensity: <float>
  27264. * emissiveMap: new THREE.Texture( <Image> ),
  27265. *
  27266. * specularMap: new THREE.Texture( <Image> ),
  27267. *
  27268. * alphaMap: new THREE.Texture( <Image> ),
  27269. *
  27270. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  27271. * combine: THREE.Multiply,
  27272. * reflectivity: <float>,
  27273. * refractionRatio: <float>,
  27274. *
  27275. * wireframe: <boolean>,
  27276. * wireframeLinewidth: <float>,
  27277. *
  27278. * }
  27279. */
  27280. class MeshLambertMaterial extends Material {
  27281. constructor(parameters) {
  27282. super();
  27283. this.type = 'MeshLambertMaterial';
  27284. this.color = new Color(0xffffff); // diffuse
  27285. this.map = null;
  27286. this.lightMap = null;
  27287. this.lightMapIntensity = 1.0;
  27288. this.aoMap = null;
  27289. this.aoMapIntensity = 1.0;
  27290. this.emissive = new Color(0x000000);
  27291. this.emissiveIntensity = 1.0;
  27292. this.emissiveMap = null;
  27293. this.specularMap = null;
  27294. this.alphaMap = null;
  27295. this.envMap = null;
  27296. this.combine = MultiplyOperation;
  27297. this.reflectivity = 1;
  27298. this.refractionRatio = 0.98;
  27299. this.wireframe = false;
  27300. this.wireframeLinewidth = 1;
  27301. this.wireframeLinecap = 'round';
  27302. this.wireframeLinejoin = 'round';
  27303. this.setValues(parameters);
  27304. }
  27305. copy(source) {
  27306. super.copy(source);
  27307. this.color.copy(source.color);
  27308. this.map = source.map;
  27309. this.lightMap = source.lightMap;
  27310. this.lightMapIntensity = source.lightMapIntensity;
  27311. this.aoMap = source.aoMap;
  27312. this.aoMapIntensity = source.aoMapIntensity;
  27313. this.emissive.copy(source.emissive);
  27314. this.emissiveMap = source.emissiveMap;
  27315. this.emissiveIntensity = source.emissiveIntensity;
  27316. this.specularMap = source.specularMap;
  27317. this.alphaMap = source.alphaMap;
  27318. this.envMap = source.envMap;
  27319. this.combine = source.combine;
  27320. this.reflectivity = source.reflectivity;
  27321. this.refractionRatio = source.refractionRatio;
  27322. this.wireframe = source.wireframe;
  27323. this.wireframeLinewidth = source.wireframeLinewidth;
  27324. this.wireframeLinecap = source.wireframeLinecap;
  27325. this.wireframeLinejoin = source.wireframeLinejoin;
  27326. return this;
  27327. }
  27328. }
  27329. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  27330. /**
  27331. * parameters = {
  27332. * color: <hex>,
  27333. * opacity: <float>,
  27334. *
  27335. * matcap: new THREE.Texture( <Image> ),
  27336. *
  27337. * map: new THREE.Texture( <Image> ),
  27338. *
  27339. * bumpMap: new THREE.Texture( <Image> ),
  27340. * bumpScale: <float>,
  27341. *
  27342. * normalMap: new THREE.Texture( <Image> ),
  27343. * normalMapType: THREE.TangentSpaceNormalMap,
  27344. * normalScale: <Vector2>,
  27345. *
  27346. * displacementMap: new THREE.Texture( <Image> ),
  27347. * displacementScale: <float>,
  27348. * displacementBias: <float>,
  27349. *
  27350. * alphaMap: new THREE.Texture( <Image> ),
  27351. *
  27352. * flatShading: <bool>
  27353. * }
  27354. */
  27355. class MeshMatcapMaterial extends Material {
  27356. constructor(parameters) {
  27357. super();
  27358. this.defines = {
  27359. 'MATCAP': ''
  27360. };
  27361. this.type = 'MeshMatcapMaterial';
  27362. this.color = new Color(0xffffff); // diffuse
  27363. this.matcap = null;
  27364. this.map = null;
  27365. this.bumpMap = null;
  27366. this.bumpScale = 1;
  27367. this.normalMap = null;
  27368. this.normalMapType = TangentSpaceNormalMap;
  27369. this.normalScale = new Vector2(1, 1);
  27370. this.displacementMap = null;
  27371. this.displacementScale = 1;
  27372. this.displacementBias = 0;
  27373. this.alphaMap = null;
  27374. this.flatShading = false;
  27375. this.setValues(parameters);
  27376. }
  27377. copy(source) {
  27378. super.copy(source);
  27379. this.defines = {
  27380. 'MATCAP': ''
  27381. };
  27382. this.color.copy(source.color);
  27383. this.matcap = source.matcap;
  27384. this.map = source.map;
  27385. this.bumpMap = source.bumpMap;
  27386. this.bumpScale = source.bumpScale;
  27387. this.normalMap = source.normalMap;
  27388. this.normalMapType = source.normalMapType;
  27389. this.normalScale.copy(source.normalScale);
  27390. this.displacementMap = source.displacementMap;
  27391. this.displacementScale = source.displacementScale;
  27392. this.displacementBias = source.displacementBias;
  27393. this.alphaMap = source.alphaMap;
  27394. this.flatShading = source.flatShading;
  27395. return this;
  27396. }
  27397. }
  27398. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  27399. /**
  27400. * parameters = {
  27401. * color: <hex>,
  27402. * opacity: <float>,
  27403. *
  27404. * linewidth: <float>,
  27405. *
  27406. * scale: <float>,
  27407. * dashSize: <float>,
  27408. * gapSize: <float>
  27409. * }
  27410. */
  27411. class LineDashedMaterial extends LineBasicMaterial {
  27412. constructor(parameters) {
  27413. super();
  27414. this.type = 'LineDashedMaterial';
  27415. this.scale = 1;
  27416. this.dashSize = 3;
  27417. this.gapSize = 1;
  27418. this.setValues(parameters);
  27419. }
  27420. copy(source) {
  27421. super.copy(source);
  27422. this.scale = source.scale;
  27423. this.dashSize = source.dashSize;
  27424. this.gapSize = source.gapSize;
  27425. return this;
  27426. }
  27427. }
  27428. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  27429. var Materials = /*#__PURE__*/Object.freeze({
  27430. __proto__: null,
  27431. ShadowMaterial: ShadowMaterial,
  27432. SpriteMaterial: SpriteMaterial,
  27433. RawShaderMaterial: RawShaderMaterial,
  27434. ShaderMaterial: ShaderMaterial,
  27435. PointsMaterial: PointsMaterial,
  27436. MeshPhysicalMaterial: MeshPhysicalMaterial,
  27437. MeshStandardMaterial: MeshStandardMaterial,
  27438. MeshPhongMaterial: MeshPhongMaterial,
  27439. MeshToonMaterial: MeshToonMaterial,
  27440. MeshNormalMaterial: MeshNormalMaterial,
  27441. MeshLambertMaterial: MeshLambertMaterial,
  27442. MeshDepthMaterial: MeshDepthMaterial,
  27443. MeshDistanceMaterial: MeshDistanceMaterial,
  27444. MeshBasicMaterial: MeshBasicMaterial,
  27445. MeshMatcapMaterial: MeshMatcapMaterial,
  27446. LineDashedMaterial: LineDashedMaterial,
  27447. LineBasicMaterial: LineBasicMaterial,
  27448. Material: Material
  27449. });
  27450. const AnimationUtils = {
  27451. // same as Array.prototype.slice, but also works on typed arrays
  27452. arraySlice: function (array, from, to) {
  27453. if (AnimationUtils.isTypedArray(array)) {
  27454. // in ios9 array.subarray(from, undefined) will return empty array
  27455. // but array.subarray(from) or array.subarray(from, len) is correct
  27456. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  27457. }
  27458. return array.slice(from, to);
  27459. },
  27460. // converts an array to a specific type
  27461. convertArray: function (array, type, forceClone) {
  27462. if (!array || // let 'undefined' and 'null' pass
  27463. !forceClone && array.constructor === type) return array;
  27464. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  27465. return new type(array); // create typed array
  27466. }
  27467. return Array.prototype.slice.call(array); // create Array
  27468. },
  27469. isTypedArray: function (object) {
  27470. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  27471. },
  27472. // returns an array by which times and values can be sorted
  27473. getKeyframeOrder: function (times) {
  27474. function compareTime(i, j) {
  27475. return times[i] - times[j];
  27476. }
  27477. const n = times.length;
  27478. const result = new Array(n);
  27479. for (let i = 0; i !== n; ++i) result[i] = i;
  27480. result.sort(compareTime);
  27481. return result;
  27482. },
  27483. // uses the array previously returned by 'getKeyframeOrder' to sort data
  27484. sortedArray: function (values, stride, order) {
  27485. const nValues = values.length;
  27486. const result = new values.constructor(nValues);
  27487. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  27488. const srcOffset = order[i] * stride;
  27489. for (let j = 0; j !== stride; ++j) {
  27490. result[dstOffset++] = values[srcOffset + j];
  27491. }
  27492. }
  27493. return result;
  27494. },
  27495. // function for parsing AOS keyframe formats
  27496. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  27497. let i = 1,
  27498. key = jsonKeys[0];
  27499. while (key !== undefined && key[valuePropertyName] === undefined) {
  27500. key = jsonKeys[i++];
  27501. }
  27502. if (key === undefined) return; // no data
  27503. let value = key[valuePropertyName];
  27504. if (value === undefined) return; // no data
  27505. if (Array.isArray(value)) {
  27506. do {
  27507. value = key[valuePropertyName];
  27508. if (value !== undefined) {
  27509. times.push(key.time);
  27510. values.push.apply(values, value); // push all elements
  27511. }
  27512. key = jsonKeys[i++];
  27513. } while (key !== undefined);
  27514. } else if (value.toArray !== undefined) {
  27515. // ...assume THREE.Math-ish
  27516. do {
  27517. value = key[valuePropertyName];
  27518. if (value !== undefined) {
  27519. times.push(key.time);
  27520. value.toArray(values, values.length);
  27521. }
  27522. key = jsonKeys[i++];
  27523. } while (key !== undefined);
  27524. } else {
  27525. // otherwise push as-is
  27526. do {
  27527. value = key[valuePropertyName];
  27528. if (value !== undefined) {
  27529. times.push(key.time);
  27530. values.push(value);
  27531. }
  27532. key = jsonKeys[i++];
  27533. } while (key !== undefined);
  27534. }
  27535. },
  27536. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  27537. const clip = sourceClip.clone();
  27538. clip.name = name;
  27539. const tracks = [];
  27540. for (let i = 0; i < clip.tracks.length; ++i) {
  27541. const track = clip.tracks[i];
  27542. const valueSize = track.getValueSize();
  27543. const times = [];
  27544. const values = [];
  27545. for (let j = 0; j < track.times.length; ++j) {
  27546. const frame = track.times[j] * fps;
  27547. if (frame < startFrame || frame >= endFrame) continue;
  27548. times.push(track.times[j]);
  27549. for (let k = 0; k < valueSize; ++k) {
  27550. values.push(track.values[j * valueSize + k]);
  27551. }
  27552. }
  27553. if (times.length === 0) continue;
  27554. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  27555. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  27556. tracks.push(track);
  27557. }
  27558. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  27559. let minStartTime = Infinity;
  27560. for (let i = 0; i < clip.tracks.length; ++i) {
  27561. if (minStartTime > clip.tracks[i].times[0]) {
  27562. minStartTime = clip.tracks[i].times[0];
  27563. }
  27564. } // shift all tracks such that clip begins at t=0
  27565. for (let i = 0; i < clip.tracks.length; ++i) {
  27566. clip.tracks[i].shift(-1 * minStartTime);
  27567. }
  27568. clip.resetDuration();
  27569. return clip;
  27570. },
  27571. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  27572. if (fps <= 0) fps = 30;
  27573. const numTracks = referenceClip.tracks.length;
  27574. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  27575. for (let i = 0; i < numTracks; ++i) {
  27576. const referenceTrack = referenceClip.tracks[i];
  27577. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  27578. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  27579. const targetTrack = targetClip.tracks.find(function (track) {
  27580. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  27581. });
  27582. if (targetTrack === undefined) continue;
  27583. let referenceOffset = 0;
  27584. const referenceValueSize = referenceTrack.getValueSize();
  27585. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  27586. referenceOffset = referenceValueSize / 3;
  27587. }
  27588. let targetOffset = 0;
  27589. const targetValueSize = targetTrack.getValueSize();
  27590. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  27591. targetOffset = targetValueSize / 3;
  27592. }
  27593. const lastIndex = referenceTrack.times.length - 1;
  27594. let referenceValue; // Find the value to subtract out of the track
  27595. if (referenceTime <= referenceTrack.times[0]) {
  27596. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  27597. const startIndex = referenceOffset;
  27598. const endIndex = referenceValueSize - referenceOffset;
  27599. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  27600. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  27601. // Reference frame is after the last keyframe, so just use the last keyframe
  27602. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  27603. const endIndex = startIndex + referenceValueSize - referenceOffset;
  27604. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  27605. } else {
  27606. // Interpolate to the reference value
  27607. const interpolant = referenceTrack.createInterpolant();
  27608. const startIndex = referenceOffset;
  27609. const endIndex = referenceValueSize - referenceOffset;
  27610. interpolant.evaluate(referenceTime);
  27611. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  27612. } // Conjugate the quaternion
  27613. if (referenceTrackType === 'quaternion') {
  27614. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  27615. referenceQuat.toArray(referenceValue);
  27616. } // Subtract the reference value from all of the track values
  27617. const numTimes = targetTrack.times.length;
  27618. for (let j = 0; j < numTimes; ++j) {
  27619. const valueStart = j * targetValueSize + targetOffset;
  27620. if (referenceTrackType === 'quaternion') {
  27621. // Multiply the conjugate for quaternion track types
  27622. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  27623. } else {
  27624. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  27625. for (let k = 0; k < valueEnd; ++k) {
  27626. targetTrack.values[valueStart + k] -= referenceValue[k];
  27627. }
  27628. }
  27629. }
  27630. }
  27631. targetClip.blendMode = AdditiveAnimationBlendMode;
  27632. return targetClip;
  27633. }
  27634. };
  27635. /**
  27636. * Abstract base class of interpolants over parametric samples.
  27637. *
  27638. * The parameter domain is one dimensional, typically the time or a path
  27639. * along a curve defined by the data.
  27640. *
  27641. * The sample values can have any dimensionality and derived classes may
  27642. * apply special interpretations to the data.
  27643. *
  27644. * This class provides the interval seek in a Template Method, deferring
  27645. * the actual interpolation to derived classes.
  27646. *
  27647. * Time complexity is O(1) for linear access crossing at most two points
  27648. * and O(log N) for random access, where N is the number of positions.
  27649. *
  27650. * References:
  27651. *
  27652. * http://www.oodesign.com/template-method-pattern.html
  27653. *
  27654. */
  27655. class Interpolant {
  27656. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27657. this.parameterPositions = parameterPositions;
  27658. this._cachedIndex = 0;
  27659. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  27660. this.sampleValues = sampleValues;
  27661. this.valueSize = sampleSize;
  27662. this.settings = null;
  27663. this.DefaultSettings_ = {};
  27664. }
  27665. evaluate(t) {
  27666. const pp = this.parameterPositions;
  27667. let i1 = this._cachedIndex,
  27668. t1 = pp[i1],
  27669. t0 = pp[i1 - 1];
  27670. validate_interval: {
  27671. seek: {
  27672. let right;
  27673. linear_scan: {
  27674. //- See http://jsperf.com/comparison-to-undefined/3
  27675. //- slower code:
  27676. //-
  27677. //- if ( t >= t1 || t1 === undefined ) {
  27678. forward_scan: if (!(t < t1)) {
  27679. for (let giveUpAt = i1 + 2;;) {
  27680. if (t1 === undefined) {
  27681. if (t < t0) break forward_scan; // after end
  27682. i1 = pp.length;
  27683. this._cachedIndex = i1;
  27684. return this.afterEnd_(i1 - 1, t, t0);
  27685. }
  27686. if (i1 === giveUpAt) break; // this loop
  27687. t0 = t1;
  27688. t1 = pp[++i1];
  27689. if (t < t1) {
  27690. // we have arrived at the sought interval
  27691. break seek;
  27692. }
  27693. } // prepare binary search on the right side of the index
  27694. right = pp.length;
  27695. break linear_scan;
  27696. } //- slower code:
  27697. //- if ( t < t0 || t0 === undefined ) {
  27698. if (!(t >= t0)) {
  27699. // looping?
  27700. const t1global = pp[1];
  27701. if (t < t1global) {
  27702. i1 = 2; // + 1, using the scan for the details
  27703. t0 = t1global;
  27704. } // linear reverse scan
  27705. for (let giveUpAt = i1 - 2;;) {
  27706. if (t0 === undefined) {
  27707. // before start
  27708. this._cachedIndex = 0;
  27709. return this.beforeStart_(0, t, t1);
  27710. }
  27711. if (i1 === giveUpAt) break; // this loop
  27712. t1 = t0;
  27713. t0 = pp[--i1 - 1];
  27714. if (t >= t0) {
  27715. // we have arrived at the sought interval
  27716. break seek;
  27717. }
  27718. } // prepare binary search on the left side of the index
  27719. right = i1;
  27720. i1 = 0;
  27721. break linear_scan;
  27722. } // the interval is valid
  27723. break validate_interval;
  27724. } // linear scan
  27725. // binary search
  27726. while (i1 < right) {
  27727. const mid = i1 + right >>> 1;
  27728. if (t < pp[mid]) {
  27729. right = mid;
  27730. } else {
  27731. i1 = mid + 1;
  27732. }
  27733. }
  27734. t1 = pp[i1];
  27735. t0 = pp[i1 - 1]; // check boundary cases, again
  27736. if (t0 === undefined) {
  27737. this._cachedIndex = 0;
  27738. return this.beforeStart_(0, t, t1);
  27739. }
  27740. if (t1 === undefined) {
  27741. i1 = pp.length;
  27742. this._cachedIndex = i1;
  27743. return this.afterEnd_(i1 - 1, t0, t);
  27744. }
  27745. } // seek
  27746. this._cachedIndex = i1;
  27747. this.intervalChanged_(i1, t0, t1);
  27748. } // validate_interval
  27749. return this.interpolate_(i1, t0, t, t1);
  27750. }
  27751. getSettings_() {
  27752. return this.settings || this.DefaultSettings_;
  27753. }
  27754. copySampleValue_(index) {
  27755. // copies a sample value to the result buffer
  27756. const result = this.resultBuffer,
  27757. values = this.sampleValues,
  27758. stride = this.valueSize,
  27759. offset = index * stride;
  27760. for (let i = 0; i !== stride; ++i) {
  27761. result[i] = values[offset + i];
  27762. }
  27763. return result;
  27764. } // Template methods for derived classes:
  27765. interpolate_() {
  27766. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  27767. }
  27768. intervalChanged_() {// empty
  27769. }
  27770. } // ALIAS DEFINITIONS
  27771. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  27772. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  27773. /**
  27774. * Fast and simple cubic spline interpolant.
  27775. *
  27776. * It was derived from a Hermitian construction setting the first derivative
  27777. * at each sample position to the linear slope between neighboring positions
  27778. * over their parameter interval.
  27779. */
  27780. class CubicInterpolant extends Interpolant {
  27781. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27782. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  27783. this._weightPrev = -0;
  27784. this._offsetPrev = -0;
  27785. this._weightNext = -0;
  27786. this._offsetNext = -0;
  27787. this.DefaultSettings_ = {
  27788. endingStart: ZeroCurvatureEnding,
  27789. endingEnd: ZeroCurvatureEnding
  27790. };
  27791. }
  27792. intervalChanged_(i1, t0, t1) {
  27793. const pp = this.parameterPositions;
  27794. let iPrev = i1 - 2,
  27795. iNext = i1 + 1,
  27796. tPrev = pp[iPrev],
  27797. tNext = pp[iNext];
  27798. if (tPrev === undefined) {
  27799. switch (this.getSettings_().endingStart) {
  27800. case ZeroSlopeEnding:
  27801. // f'(t0) = 0
  27802. iPrev = i1;
  27803. tPrev = 2 * t0 - t1;
  27804. break;
  27805. case WrapAroundEnding:
  27806. // use the other end of the curve
  27807. iPrev = pp.length - 2;
  27808. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  27809. break;
  27810. default:
  27811. // ZeroCurvatureEnding
  27812. // f''(t0) = 0 a.k.a. Natural Spline
  27813. iPrev = i1;
  27814. tPrev = t1;
  27815. }
  27816. }
  27817. if (tNext === undefined) {
  27818. switch (this.getSettings_().endingEnd) {
  27819. case ZeroSlopeEnding:
  27820. // f'(tN) = 0
  27821. iNext = i1;
  27822. tNext = 2 * t1 - t0;
  27823. break;
  27824. case WrapAroundEnding:
  27825. // use the other end of the curve
  27826. iNext = 1;
  27827. tNext = t1 + pp[1] - pp[0];
  27828. break;
  27829. default:
  27830. // ZeroCurvatureEnding
  27831. // f''(tN) = 0, a.k.a. Natural Spline
  27832. iNext = i1 - 1;
  27833. tNext = t0;
  27834. }
  27835. }
  27836. const halfDt = (t1 - t0) * 0.5,
  27837. stride = this.valueSize;
  27838. this._weightPrev = halfDt / (t0 - tPrev);
  27839. this._weightNext = halfDt / (tNext - t1);
  27840. this._offsetPrev = iPrev * stride;
  27841. this._offsetNext = iNext * stride;
  27842. }
  27843. interpolate_(i1, t0, t, t1) {
  27844. const result = this.resultBuffer,
  27845. values = this.sampleValues,
  27846. stride = this.valueSize,
  27847. o1 = i1 * stride,
  27848. o0 = o1 - stride,
  27849. oP = this._offsetPrev,
  27850. oN = this._offsetNext,
  27851. wP = this._weightPrev,
  27852. wN = this._weightNext,
  27853. p = (t - t0) / (t1 - t0),
  27854. pp = p * p,
  27855. ppp = pp * p; // evaluate polynomials
  27856. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  27857. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  27858. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  27859. const sN = wN * ppp - wN * pp; // combine data linearly
  27860. for (let i = 0; i !== stride; ++i) {
  27861. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  27862. }
  27863. return result;
  27864. }
  27865. }
  27866. class LinearInterpolant extends Interpolant {
  27867. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27868. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  27869. }
  27870. interpolate_(i1, t0, t, t1) {
  27871. const result = this.resultBuffer,
  27872. values = this.sampleValues,
  27873. stride = this.valueSize,
  27874. offset1 = i1 * stride,
  27875. offset0 = offset1 - stride,
  27876. weight1 = (t - t0) / (t1 - t0),
  27877. weight0 = 1 - weight1;
  27878. for (let i = 0; i !== stride; ++i) {
  27879. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  27880. }
  27881. return result;
  27882. }
  27883. }
  27884. /**
  27885. *
  27886. * Interpolant that evaluates to the sample value at the position preceeding
  27887. * the parameter.
  27888. */
  27889. class DiscreteInterpolant extends Interpolant {
  27890. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  27891. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  27892. }
  27893. interpolate_(i1
  27894. /*, t0, t, t1 */
  27895. ) {
  27896. return this.copySampleValue_(i1 - 1);
  27897. }
  27898. }
  27899. class KeyframeTrack {
  27900. constructor(name, times, values, interpolation) {
  27901. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  27902. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  27903. this.name = name;
  27904. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  27905. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  27906. this.setInterpolation(interpolation || this.DefaultInterpolation);
  27907. } // Serialization (in static context, because of constructor invocation
  27908. // and automatic invocation of .toJSON):
  27909. static toJSON(track) {
  27910. const trackType = track.constructor;
  27911. let json; // derived classes can define a static toJSON method
  27912. if (trackType.toJSON !== this.toJSON) {
  27913. json = trackType.toJSON(track);
  27914. } else {
  27915. // by default, we assume the data can be serialized as-is
  27916. json = {
  27917. 'name': track.name,
  27918. 'times': AnimationUtils.convertArray(track.times, Array),
  27919. 'values': AnimationUtils.convertArray(track.values, Array)
  27920. };
  27921. const interpolation = track.getInterpolation();
  27922. if (interpolation !== track.DefaultInterpolation) {
  27923. json.interpolation = interpolation;
  27924. }
  27925. }
  27926. json.type = track.ValueTypeName; // mandatory
  27927. return json;
  27928. }
  27929. InterpolantFactoryMethodDiscrete(result) {
  27930. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  27931. }
  27932. InterpolantFactoryMethodLinear(result) {
  27933. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  27934. }
  27935. InterpolantFactoryMethodSmooth(result) {
  27936. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  27937. }
  27938. setInterpolation(interpolation) {
  27939. let factoryMethod;
  27940. switch (interpolation) {
  27941. case InterpolateDiscrete:
  27942. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  27943. break;
  27944. case InterpolateLinear:
  27945. factoryMethod = this.InterpolantFactoryMethodLinear;
  27946. break;
  27947. case InterpolateSmooth:
  27948. factoryMethod = this.InterpolantFactoryMethodSmooth;
  27949. break;
  27950. }
  27951. if (factoryMethod === undefined) {
  27952. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  27953. if (this.createInterpolant === undefined) {
  27954. // fall back to default, unless the default itself is messed up
  27955. if (interpolation !== this.DefaultInterpolation) {
  27956. this.setInterpolation(this.DefaultInterpolation);
  27957. } else {
  27958. throw new Error(message); // fatal, in this case
  27959. }
  27960. }
  27961. console.warn('THREE.KeyframeTrack:', message);
  27962. return this;
  27963. }
  27964. this.createInterpolant = factoryMethod;
  27965. return this;
  27966. }
  27967. getInterpolation() {
  27968. switch (this.createInterpolant) {
  27969. case this.InterpolantFactoryMethodDiscrete:
  27970. return InterpolateDiscrete;
  27971. case this.InterpolantFactoryMethodLinear:
  27972. return InterpolateLinear;
  27973. case this.InterpolantFactoryMethodSmooth:
  27974. return InterpolateSmooth;
  27975. }
  27976. }
  27977. getValueSize() {
  27978. return this.values.length / this.times.length;
  27979. } // move all keyframes either forwards or backwards in time
  27980. shift(timeOffset) {
  27981. if (timeOffset !== 0.0) {
  27982. const times = this.times;
  27983. for (let i = 0, n = times.length; i !== n; ++i) {
  27984. times[i] += timeOffset;
  27985. }
  27986. }
  27987. return this;
  27988. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  27989. scale(timeScale) {
  27990. if (timeScale !== 1.0) {
  27991. const times = this.times;
  27992. for (let i = 0, n = times.length; i !== n; ++i) {
  27993. times[i] *= timeScale;
  27994. }
  27995. }
  27996. return this;
  27997. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  27998. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  27999. trim(startTime, endTime) {
  28000. const times = this.times,
  28001. nKeys = times.length;
  28002. let from = 0,
  28003. to = nKeys - 1;
  28004. while (from !== nKeys && times[from] < startTime) {
  28005. ++from;
  28006. }
  28007. while (to !== -1 && times[to] > endTime) {
  28008. --to;
  28009. }
  28010. ++to; // inclusive -> exclusive bound
  28011. if (from !== 0 || to !== nKeys) {
  28012. // empty tracks are forbidden, so keep at least one keyframe
  28013. if (from >= to) {
  28014. to = Math.max(to, 1);
  28015. from = to - 1;
  28016. }
  28017. const stride = this.getValueSize();
  28018. this.times = AnimationUtils.arraySlice(times, from, to);
  28019. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  28020. }
  28021. return this;
  28022. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  28023. validate() {
  28024. let valid = true;
  28025. const valueSize = this.getValueSize();
  28026. if (valueSize - Math.floor(valueSize) !== 0) {
  28027. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  28028. valid = false;
  28029. }
  28030. const times = this.times,
  28031. values = this.values,
  28032. nKeys = times.length;
  28033. if (nKeys === 0) {
  28034. console.error('THREE.KeyframeTrack: Track is empty.', this);
  28035. valid = false;
  28036. }
  28037. let prevTime = null;
  28038. for (let i = 0; i !== nKeys; i++) {
  28039. const currTime = times[i];
  28040. if (typeof currTime === 'number' && isNaN(currTime)) {
  28041. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  28042. valid = false;
  28043. break;
  28044. }
  28045. if (prevTime !== null && prevTime > currTime) {
  28046. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  28047. valid = false;
  28048. break;
  28049. }
  28050. prevTime = currTime;
  28051. }
  28052. if (values !== undefined) {
  28053. if (AnimationUtils.isTypedArray(values)) {
  28054. for (let i = 0, n = values.length; i !== n; ++i) {
  28055. const value = values[i];
  28056. if (isNaN(value)) {
  28057. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  28058. valid = false;
  28059. break;
  28060. }
  28061. }
  28062. }
  28063. }
  28064. return valid;
  28065. } // removes equivalent sequential keys as common in morph target sequences
  28066. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  28067. optimize() {
  28068. // times or values may be shared with other tracks, so overwriting is unsafe
  28069. const times = AnimationUtils.arraySlice(this.times),
  28070. values = AnimationUtils.arraySlice(this.values),
  28071. stride = this.getValueSize(),
  28072. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  28073. lastIndex = times.length - 1;
  28074. let writeIndex = 1;
  28075. for (let i = 1; i < lastIndex; ++i) {
  28076. let keep = false;
  28077. const time = times[i];
  28078. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  28079. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  28080. if (!smoothInterpolation) {
  28081. // remove unnecessary keyframes same as their neighbors
  28082. const offset = i * stride,
  28083. offsetP = offset - stride,
  28084. offsetN = offset + stride;
  28085. for (let j = 0; j !== stride; ++j) {
  28086. const value = values[offset + j];
  28087. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  28088. keep = true;
  28089. break;
  28090. }
  28091. }
  28092. } else {
  28093. keep = true;
  28094. }
  28095. } // in-place compaction
  28096. if (keep) {
  28097. if (i !== writeIndex) {
  28098. times[writeIndex] = times[i];
  28099. const readOffset = i * stride,
  28100. writeOffset = writeIndex * stride;
  28101. for (let j = 0; j !== stride; ++j) {
  28102. values[writeOffset + j] = values[readOffset + j];
  28103. }
  28104. }
  28105. ++writeIndex;
  28106. }
  28107. } // flush last keyframe (compaction looks ahead)
  28108. if (lastIndex > 0) {
  28109. times[writeIndex] = times[lastIndex];
  28110. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  28111. values[writeOffset + j] = values[readOffset + j];
  28112. }
  28113. ++writeIndex;
  28114. }
  28115. if (writeIndex !== times.length) {
  28116. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  28117. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  28118. } else {
  28119. this.times = times;
  28120. this.values = values;
  28121. }
  28122. return this;
  28123. }
  28124. clone() {
  28125. const times = AnimationUtils.arraySlice(this.times, 0);
  28126. const values = AnimationUtils.arraySlice(this.values, 0);
  28127. const TypedKeyframeTrack = this.constructor;
  28128. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  28129. track.createInterpolant = this.createInterpolant;
  28130. return track;
  28131. }
  28132. }
  28133. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  28134. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  28135. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  28136. /**
  28137. * A Track of Boolean keyframe values.
  28138. */
  28139. class BooleanKeyframeTrack extends KeyframeTrack {}
  28140. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  28141. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  28142. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  28143. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  28144. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  28145. /**
  28146. * A Track of keyframe values that represent color.
  28147. */
  28148. class ColorKeyframeTrack extends KeyframeTrack {}
  28149. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  28150. /**
  28151. * A Track of numeric keyframe values.
  28152. */
  28153. class NumberKeyframeTrack extends KeyframeTrack {}
  28154. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  28155. /**
  28156. * Spherical linear unit quaternion interpolant.
  28157. */
  28158. class QuaternionLinearInterpolant extends Interpolant {
  28159. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  28160. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  28161. }
  28162. interpolate_(i1, t0, t, t1) {
  28163. const result = this.resultBuffer,
  28164. values = this.sampleValues,
  28165. stride = this.valueSize,
  28166. alpha = (t - t0) / (t1 - t0);
  28167. let offset = i1 * stride;
  28168. for (let end = offset + stride; offset !== end; offset += 4) {
  28169. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  28170. }
  28171. return result;
  28172. }
  28173. }
  28174. /**
  28175. * A Track of quaternion keyframe values.
  28176. */
  28177. class QuaternionKeyframeTrack extends KeyframeTrack {
  28178. InterpolantFactoryMethodLinear(result) {
  28179. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  28180. }
  28181. }
  28182. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  28183. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  28184. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  28185. /**
  28186. * A Track that interpolates Strings
  28187. */
  28188. class StringKeyframeTrack extends KeyframeTrack {}
  28189. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  28190. StringKeyframeTrack.prototype.ValueBufferType = Array;
  28191. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  28192. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  28193. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  28194. /**
  28195. * A Track of vectored keyframe values.
  28196. */
  28197. class VectorKeyframeTrack extends KeyframeTrack {}
  28198. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  28199. class AnimationClip {
  28200. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  28201. this.name = name;
  28202. this.tracks = tracks;
  28203. this.duration = duration;
  28204. this.blendMode = blendMode;
  28205. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  28206. if (this.duration < 0) {
  28207. this.resetDuration();
  28208. }
  28209. }
  28210. static parse(json) {
  28211. const tracks = [],
  28212. jsonTracks = json.tracks,
  28213. frameTime = 1.0 / (json.fps || 1.0);
  28214. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  28215. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  28216. }
  28217. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  28218. clip.uuid = json.uuid;
  28219. return clip;
  28220. }
  28221. static toJSON(clip) {
  28222. const tracks = [],
  28223. clipTracks = clip.tracks;
  28224. const json = {
  28225. 'name': clip.name,
  28226. 'duration': clip.duration,
  28227. 'tracks': tracks,
  28228. 'uuid': clip.uuid,
  28229. 'blendMode': clip.blendMode
  28230. };
  28231. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  28232. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  28233. }
  28234. return json;
  28235. }
  28236. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  28237. const numMorphTargets = morphTargetSequence.length;
  28238. const tracks = [];
  28239. for (let i = 0; i < numMorphTargets; i++) {
  28240. let times = [];
  28241. let values = [];
  28242. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  28243. values.push(0, 1, 0);
  28244. const order = AnimationUtils.getKeyframeOrder(times);
  28245. times = AnimationUtils.sortedArray(times, 1, order);
  28246. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  28247. // last frame as well for perfect loop.
  28248. if (!noLoop && times[0] === 0) {
  28249. times.push(numMorphTargets);
  28250. values.push(values[0]);
  28251. }
  28252. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  28253. }
  28254. return new this(name, -1, tracks);
  28255. }
  28256. static findByName(objectOrClipArray, name) {
  28257. let clipArray = objectOrClipArray;
  28258. if (!Array.isArray(objectOrClipArray)) {
  28259. const o = objectOrClipArray;
  28260. clipArray = o.geometry && o.geometry.animations || o.animations;
  28261. }
  28262. for (let i = 0; i < clipArray.length; i++) {
  28263. if (clipArray[i].name === name) {
  28264. return clipArray[i];
  28265. }
  28266. }
  28267. return null;
  28268. }
  28269. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  28270. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  28271. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  28272. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  28273. // patterns like Walk_001, Walk_002, Run_001, Run_002
  28274. for (let i = 0, il = morphTargets.length; i < il; i++) {
  28275. const morphTarget = morphTargets[i];
  28276. const parts = morphTarget.name.match(pattern);
  28277. if (parts && parts.length > 1) {
  28278. const name = parts[1];
  28279. let animationMorphTargets = animationToMorphTargets[name];
  28280. if (!animationMorphTargets) {
  28281. animationToMorphTargets[name] = animationMorphTargets = [];
  28282. }
  28283. animationMorphTargets.push(morphTarget);
  28284. }
  28285. }
  28286. const clips = [];
  28287. for (const name in animationToMorphTargets) {
  28288. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  28289. }
  28290. return clips;
  28291. } // parse the animation.hierarchy format
  28292. static parseAnimation(animation, bones) {
  28293. if (!animation) {
  28294. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  28295. return null;
  28296. }
  28297. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  28298. // only return track if there are actually keys.
  28299. if (animationKeys.length !== 0) {
  28300. const times = [];
  28301. const values = [];
  28302. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  28303. if (times.length !== 0) {
  28304. destTracks.push(new trackType(trackName, times, values));
  28305. }
  28306. }
  28307. };
  28308. const tracks = [];
  28309. const clipName = animation.name || 'default';
  28310. const fps = animation.fps || 30;
  28311. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  28312. let duration = animation.length || -1;
  28313. const hierarchyTracks = animation.hierarchy || [];
  28314. for (let h = 0; h < hierarchyTracks.length; h++) {
  28315. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  28316. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  28317. if (animationKeys[0].morphTargets) {
  28318. // figure out all morph targets used in this track
  28319. const morphTargetNames = {};
  28320. let k;
  28321. for (k = 0; k < animationKeys.length; k++) {
  28322. if (animationKeys[k].morphTargets) {
  28323. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  28324. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  28325. }
  28326. }
  28327. } // create a track for each morph target with all zero
  28328. // morphTargetInfluences except for the keys in which
  28329. // the morphTarget is named.
  28330. for (const morphTargetName in morphTargetNames) {
  28331. const times = [];
  28332. const values = [];
  28333. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  28334. const animationKey = animationKeys[k];
  28335. times.push(animationKey.time);
  28336. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  28337. }
  28338. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  28339. }
  28340. duration = morphTargetNames.length * (fps || 1.0);
  28341. } else {
  28342. // ...assume skeletal animation
  28343. const boneName = '.bones[' + bones[h].name + ']';
  28344. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  28345. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  28346. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  28347. }
  28348. }
  28349. if (tracks.length === 0) {
  28350. return null;
  28351. }
  28352. const clip = new this(clipName, duration, tracks, blendMode);
  28353. return clip;
  28354. }
  28355. resetDuration() {
  28356. const tracks = this.tracks;
  28357. let duration = 0;
  28358. for (let i = 0, n = tracks.length; i !== n; ++i) {
  28359. const track = this.tracks[i];
  28360. duration = Math.max(duration, track.times[track.times.length - 1]);
  28361. }
  28362. this.duration = duration;
  28363. return this;
  28364. }
  28365. trim() {
  28366. for (let i = 0; i < this.tracks.length; i++) {
  28367. this.tracks[i].trim(0, this.duration);
  28368. }
  28369. return this;
  28370. }
  28371. validate() {
  28372. let valid = true;
  28373. for (let i = 0; i < this.tracks.length; i++) {
  28374. valid = valid && this.tracks[i].validate();
  28375. }
  28376. return valid;
  28377. }
  28378. optimize() {
  28379. for (let i = 0; i < this.tracks.length; i++) {
  28380. this.tracks[i].optimize();
  28381. }
  28382. return this;
  28383. }
  28384. clone() {
  28385. const tracks = [];
  28386. for (let i = 0; i < this.tracks.length; i++) {
  28387. tracks.push(this.tracks[i].clone());
  28388. }
  28389. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  28390. }
  28391. toJSON() {
  28392. return this.constructor.toJSON(this);
  28393. }
  28394. }
  28395. function getTrackTypeForValueTypeName(typeName) {
  28396. switch (typeName.toLowerCase()) {
  28397. case 'scalar':
  28398. case 'double':
  28399. case 'float':
  28400. case 'number':
  28401. case 'integer':
  28402. return NumberKeyframeTrack;
  28403. case 'vector':
  28404. case 'vector2':
  28405. case 'vector3':
  28406. case 'vector4':
  28407. return VectorKeyframeTrack;
  28408. case 'color':
  28409. return ColorKeyframeTrack;
  28410. case 'quaternion':
  28411. return QuaternionKeyframeTrack;
  28412. case 'bool':
  28413. case 'boolean':
  28414. return BooleanKeyframeTrack;
  28415. case 'string':
  28416. return StringKeyframeTrack;
  28417. }
  28418. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  28419. }
  28420. function parseKeyframeTrack(json) {
  28421. if (json.type === undefined) {
  28422. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  28423. }
  28424. const trackType = getTrackTypeForValueTypeName(json.type);
  28425. if (json.times === undefined) {
  28426. const times = [],
  28427. values = [];
  28428. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  28429. json.times = times;
  28430. json.values = values;
  28431. } // derived classes can define a static parse method
  28432. if (trackType.parse !== undefined) {
  28433. return trackType.parse(json);
  28434. } else {
  28435. // by default, we assume a constructor compatible with the base
  28436. return new trackType(json.name, json.times, json.values, json.interpolation);
  28437. }
  28438. }
  28439. const Cache = {
  28440. enabled: false,
  28441. files: {},
  28442. add: function (key, file) {
  28443. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  28444. this.files[key] = file;
  28445. },
  28446. get: function (key) {
  28447. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  28448. return this.files[key];
  28449. },
  28450. remove: function (key) {
  28451. delete this.files[key];
  28452. },
  28453. clear: function () {
  28454. this.files = {};
  28455. }
  28456. };
  28457. class LoadingManager {
  28458. constructor(onLoad, onProgress, onError) {
  28459. const scope = this;
  28460. let isLoading = false;
  28461. let itemsLoaded = 0;
  28462. let itemsTotal = 0;
  28463. let urlModifier = undefined;
  28464. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  28465. // in the constructor
  28466. this.onStart = undefined;
  28467. this.onLoad = onLoad;
  28468. this.onProgress = onProgress;
  28469. this.onError = onError;
  28470. this.itemStart = function (url) {
  28471. itemsTotal++;
  28472. if (isLoading === false) {
  28473. if (scope.onStart !== undefined) {
  28474. scope.onStart(url, itemsLoaded, itemsTotal);
  28475. }
  28476. }
  28477. isLoading = true;
  28478. };
  28479. this.itemEnd = function (url) {
  28480. itemsLoaded++;
  28481. if (scope.onProgress !== undefined) {
  28482. scope.onProgress(url, itemsLoaded, itemsTotal);
  28483. }
  28484. if (itemsLoaded === itemsTotal) {
  28485. isLoading = false;
  28486. if (scope.onLoad !== undefined) {
  28487. scope.onLoad();
  28488. }
  28489. }
  28490. };
  28491. this.itemError = function (url) {
  28492. if (scope.onError !== undefined) {
  28493. scope.onError(url);
  28494. }
  28495. };
  28496. this.resolveURL = function (url) {
  28497. if (urlModifier) {
  28498. return urlModifier(url);
  28499. }
  28500. return url;
  28501. };
  28502. this.setURLModifier = function (transform) {
  28503. urlModifier = transform;
  28504. return this;
  28505. };
  28506. this.addHandler = function (regex, loader) {
  28507. handlers.push(regex, loader);
  28508. return this;
  28509. };
  28510. this.removeHandler = function (regex) {
  28511. const index = handlers.indexOf(regex);
  28512. if (index !== -1) {
  28513. handlers.splice(index, 2);
  28514. }
  28515. return this;
  28516. };
  28517. this.getHandler = function (file) {
  28518. for (let i = 0, l = handlers.length; i < l; i += 2) {
  28519. const regex = handlers[i];
  28520. const loader = handlers[i + 1];
  28521. if (regex.global) regex.lastIndex = 0; // see #17920
  28522. if (regex.test(file)) {
  28523. return loader;
  28524. }
  28525. }
  28526. return null;
  28527. };
  28528. }
  28529. }
  28530. const DefaultLoadingManager = new LoadingManager();
  28531. class Loader {
  28532. constructor(manager) {
  28533. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  28534. this.crossOrigin = 'anonymous';
  28535. this.withCredentials = false;
  28536. this.path = '';
  28537. this.resourcePath = '';
  28538. this.requestHeader = {};
  28539. }
  28540. load() {}
  28541. loadAsync(url, onProgress) {
  28542. const scope = this;
  28543. return new Promise(function (resolve, reject) {
  28544. scope.load(url, resolve, onProgress, reject);
  28545. });
  28546. }
  28547. parse() {}
  28548. setCrossOrigin(crossOrigin) {
  28549. this.crossOrigin = crossOrigin;
  28550. return this;
  28551. }
  28552. setWithCredentials(value) {
  28553. this.withCredentials = value;
  28554. return this;
  28555. }
  28556. setPath(path) {
  28557. this.path = path;
  28558. return this;
  28559. }
  28560. setResourcePath(resourcePath) {
  28561. this.resourcePath = resourcePath;
  28562. return this;
  28563. }
  28564. setRequestHeader(requestHeader) {
  28565. this.requestHeader = requestHeader;
  28566. return this;
  28567. }
  28568. }
  28569. const loading = {};
  28570. class FileLoader extends Loader {
  28571. constructor(manager) {
  28572. super(manager);
  28573. }
  28574. load(url, onLoad, onProgress, onError) {
  28575. if (url === undefined) url = '';
  28576. if (this.path !== undefined) url = this.path + url;
  28577. url = this.manager.resolveURL(url);
  28578. const scope = this;
  28579. const cached = Cache.get(url);
  28580. if (cached !== undefined) {
  28581. scope.manager.itemStart(url);
  28582. setTimeout(function () {
  28583. if (onLoad) onLoad(cached);
  28584. scope.manager.itemEnd(url);
  28585. }, 0);
  28586. return cached;
  28587. } // Check if request is duplicate
  28588. if (loading[url] !== undefined) {
  28589. loading[url].push({
  28590. onLoad: onLoad,
  28591. onProgress: onProgress,
  28592. onError: onError
  28593. });
  28594. return;
  28595. } // Check for data: URI
  28596. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  28597. const dataUriRegexResult = url.match(dataUriRegex);
  28598. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  28599. if (dataUriRegexResult) {
  28600. const mimeType = dataUriRegexResult[1];
  28601. const isBase64 = !!dataUriRegexResult[2];
  28602. let data = dataUriRegexResult[3];
  28603. data = decodeURIComponent(data);
  28604. if (isBase64) data = atob(data);
  28605. try {
  28606. let response;
  28607. const responseType = (this.responseType || '').toLowerCase();
  28608. switch (responseType) {
  28609. case 'arraybuffer':
  28610. case 'blob':
  28611. const view = new Uint8Array(data.length);
  28612. for (let i = 0; i < data.length; i++) {
  28613. view[i] = data.charCodeAt(i);
  28614. }
  28615. if (responseType === 'blob') {
  28616. response = new Blob([view.buffer], {
  28617. type: mimeType
  28618. });
  28619. } else {
  28620. response = view.buffer;
  28621. }
  28622. break;
  28623. case 'document':
  28624. const parser = new DOMParser();
  28625. response = parser.parseFromString(data, mimeType);
  28626. break;
  28627. case 'json':
  28628. response = JSON.parse(data);
  28629. break;
  28630. default:
  28631. // 'text' or other
  28632. response = data;
  28633. break;
  28634. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  28635. setTimeout(function () {
  28636. if (onLoad) onLoad(response);
  28637. scope.manager.itemEnd(url);
  28638. }, 0);
  28639. } catch (error) {
  28640. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  28641. setTimeout(function () {
  28642. if (onError) onError(error);
  28643. scope.manager.itemError(url);
  28644. scope.manager.itemEnd(url);
  28645. }, 0);
  28646. }
  28647. } else {
  28648. // Initialise array for duplicate requests
  28649. loading[url] = [];
  28650. loading[url].push({
  28651. onLoad: onLoad,
  28652. onProgress: onProgress,
  28653. onError: onError
  28654. });
  28655. request = new XMLHttpRequest();
  28656. request.open('GET', url, true);
  28657. request.addEventListener('load', function (event) {
  28658. const response = this.response;
  28659. const callbacks = loading[url];
  28660. delete loading[url];
  28661. if (this.status === 200 || this.status === 0) {
  28662. // Some browsers return HTTP Status 0 when using non-http protocol
  28663. // e.g. 'file://' or 'data://'. Handle as success.
  28664. 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
  28665. // error response bodies as proper responses to requests.
  28666. Cache.add(url, response);
  28667. for (let i = 0, il = callbacks.length; i < il; i++) {
  28668. const callback = callbacks[i];
  28669. if (callback.onLoad) callback.onLoad(response);
  28670. }
  28671. scope.manager.itemEnd(url);
  28672. } else {
  28673. for (let i = 0, il = callbacks.length; i < il; i++) {
  28674. const callback = callbacks[i];
  28675. if (callback.onError) callback.onError(event);
  28676. }
  28677. scope.manager.itemError(url);
  28678. scope.manager.itemEnd(url);
  28679. }
  28680. }, false);
  28681. request.addEventListener('progress', function (event) {
  28682. const callbacks = loading[url];
  28683. for (let i = 0, il = callbacks.length; i < il; i++) {
  28684. const callback = callbacks[i];
  28685. if (callback.onProgress) callback.onProgress(event);
  28686. }
  28687. }, false);
  28688. request.addEventListener('error', function (event) {
  28689. const callbacks = loading[url];
  28690. delete loading[url];
  28691. for (let i = 0, il = callbacks.length; i < il; i++) {
  28692. const callback = callbacks[i];
  28693. if (callback.onError) callback.onError(event);
  28694. }
  28695. scope.manager.itemError(url);
  28696. scope.manager.itemEnd(url);
  28697. }, false);
  28698. request.addEventListener('abort', function (event) {
  28699. const callbacks = loading[url];
  28700. delete loading[url];
  28701. for (let i = 0, il = callbacks.length; i < il; i++) {
  28702. const callback = callbacks[i];
  28703. if (callback.onError) callback.onError(event);
  28704. }
  28705. scope.manager.itemError(url);
  28706. scope.manager.itemEnd(url);
  28707. }, false);
  28708. if (this.responseType !== undefined) request.responseType = this.responseType;
  28709. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  28710. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  28711. for (const header in this.requestHeader) {
  28712. request.setRequestHeader(header, this.requestHeader[header]);
  28713. }
  28714. request.send(null);
  28715. }
  28716. scope.manager.itemStart(url);
  28717. return request;
  28718. }
  28719. setResponseType(value) {
  28720. this.responseType = value;
  28721. return this;
  28722. }
  28723. setMimeType(value) {
  28724. this.mimeType = value;
  28725. return this;
  28726. }
  28727. }
  28728. class AnimationLoader extends Loader {
  28729. constructor(manager) {
  28730. super(manager);
  28731. }
  28732. load(url, onLoad, onProgress, onError) {
  28733. const scope = this;
  28734. const loader = new FileLoader(this.manager);
  28735. loader.setPath(this.path);
  28736. loader.setRequestHeader(this.requestHeader);
  28737. loader.setWithCredentials(this.withCredentials);
  28738. loader.load(url, function (text) {
  28739. try {
  28740. onLoad(scope.parse(JSON.parse(text)));
  28741. } catch (e) {
  28742. if (onError) {
  28743. onError(e);
  28744. } else {
  28745. console.error(e);
  28746. }
  28747. scope.manager.itemError(url);
  28748. }
  28749. }, onProgress, onError);
  28750. }
  28751. parse(json) {
  28752. const animations = [];
  28753. for (let i = 0; i < json.length; i++) {
  28754. const clip = AnimationClip.parse(json[i]);
  28755. animations.push(clip);
  28756. }
  28757. return animations;
  28758. }
  28759. }
  28760. /**
  28761. * Abstract Base class to block based textures loader (dds, pvr, ...)
  28762. *
  28763. * Sub classes have to implement the parse() method which will be used in load().
  28764. */
  28765. class CompressedTextureLoader extends Loader {
  28766. constructor(manager) {
  28767. super(manager);
  28768. }
  28769. load(url, onLoad, onProgress, onError) {
  28770. const scope = this;
  28771. const images = [];
  28772. const texture = new CompressedTexture();
  28773. const loader = new FileLoader(this.manager);
  28774. loader.setPath(this.path);
  28775. loader.setResponseType('arraybuffer');
  28776. loader.setRequestHeader(this.requestHeader);
  28777. loader.setWithCredentials(scope.withCredentials);
  28778. let loaded = 0;
  28779. function loadTexture(i) {
  28780. loader.load(url[i], function (buffer) {
  28781. const texDatas = scope.parse(buffer, true);
  28782. images[i] = {
  28783. width: texDatas.width,
  28784. height: texDatas.height,
  28785. format: texDatas.format,
  28786. mipmaps: texDatas.mipmaps
  28787. };
  28788. loaded += 1;
  28789. if (loaded === 6) {
  28790. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  28791. texture.image = images;
  28792. texture.format = texDatas.format;
  28793. texture.needsUpdate = true;
  28794. if (onLoad) onLoad(texture);
  28795. }
  28796. }, onProgress, onError);
  28797. }
  28798. if (Array.isArray(url)) {
  28799. for (let i = 0, il = url.length; i < il; ++i) {
  28800. loadTexture(i);
  28801. }
  28802. } else {
  28803. // compressed cubemap texture stored in a single DDS file
  28804. loader.load(url, function (buffer) {
  28805. const texDatas = scope.parse(buffer, true);
  28806. if (texDatas.isCubemap) {
  28807. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  28808. for (let f = 0; f < faces; f++) {
  28809. images[f] = {
  28810. mipmaps: []
  28811. };
  28812. for (let i = 0; i < texDatas.mipmapCount; i++) {
  28813. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  28814. images[f].format = texDatas.format;
  28815. images[f].width = texDatas.width;
  28816. images[f].height = texDatas.height;
  28817. }
  28818. }
  28819. texture.image = images;
  28820. } else {
  28821. texture.image.width = texDatas.width;
  28822. texture.image.height = texDatas.height;
  28823. texture.mipmaps = texDatas.mipmaps;
  28824. }
  28825. if (texDatas.mipmapCount === 1) {
  28826. texture.minFilter = LinearFilter;
  28827. }
  28828. texture.format = texDatas.format;
  28829. texture.needsUpdate = true;
  28830. if (onLoad) onLoad(texture);
  28831. }, onProgress, onError);
  28832. }
  28833. return texture;
  28834. }
  28835. }
  28836. class ImageLoader extends Loader {
  28837. constructor(manager) {
  28838. super(manager);
  28839. }
  28840. load(url, onLoad, onProgress, onError) {
  28841. if (this.path !== undefined) url = this.path + url;
  28842. url = this.manager.resolveURL(url);
  28843. const scope = this;
  28844. const cached = Cache.get(url);
  28845. if (cached !== undefined) {
  28846. scope.manager.itemStart(url);
  28847. setTimeout(function () {
  28848. if (onLoad) onLoad(cached);
  28849. scope.manager.itemEnd(url);
  28850. }, 0);
  28851. return cached;
  28852. }
  28853. const image = createElementNS('img');
  28854. function onImageLoad() {
  28855. image.removeEventListener('load', onImageLoad, false);
  28856. image.removeEventListener('error', onImageError, false);
  28857. Cache.add(url, this);
  28858. if (onLoad) onLoad(this);
  28859. scope.manager.itemEnd(url);
  28860. }
  28861. function onImageError(event) {
  28862. image.removeEventListener('load', onImageLoad, false);
  28863. image.removeEventListener('error', onImageError, false);
  28864. if (onError) onError(event);
  28865. scope.manager.itemError(url);
  28866. scope.manager.itemEnd(url);
  28867. }
  28868. image.addEventListener('load', onImageLoad, false);
  28869. image.addEventListener('error', onImageError, false);
  28870. if (url.substr(0, 5) !== 'data:') {
  28871. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  28872. }
  28873. scope.manager.itemStart(url);
  28874. image.src = url;
  28875. return image;
  28876. }
  28877. }
  28878. class CubeTextureLoader extends Loader {
  28879. constructor(manager) {
  28880. super(manager);
  28881. }
  28882. load(urls, onLoad, onProgress, onError) {
  28883. const texture = new CubeTexture();
  28884. const loader = new ImageLoader(this.manager);
  28885. loader.setCrossOrigin(this.crossOrigin);
  28886. loader.setPath(this.path);
  28887. let loaded = 0;
  28888. function loadTexture(i) {
  28889. loader.load(urls[i], function (image) {
  28890. texture.images[i] = image;
  28891. loaded++;
  28892. if (loaded === 6) {
  28893. texture.needsUpdate = true;
  28894. if (onLoad) onLoad(texture);
  28895. }
  28896. }, undefined, onError);
  28897. }
  28898. for (let i = 0; i < urls.length; ++i) {
  28899. loadTexture(i);
  28900. }
  28901. return texture;
  28902. }
  28903. }
  28904. /**
  28905. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  28906. *
  28907. * Sub classes have to implement the parse() method which will be used in load().
  28908. */
  28909. class DataTextureLoader extends Loader {
  28910. constructor(manager) {
  28911. super(manager);
  28912. }
  28913. load(url, onLoad, onProgress, onError) {
  28914. const scope = this;
  28915. const texture = new DataTexture();
  28916. const loader = new FileLoader(this.manager);
  28917. loader.setResponseType('arraybuffer');
  28918. loader.setRequestHeader(this.requestHeader);
  28919. loader.setPath(this.path);
  28920. loader.setWithCredentials(scope.withCredentials);
  28921. loader.load(url, function (buffer) {
  28922. const texData = scope.parse(buffer);
  28923. if (!texData) return;
  28924. if (texData.image !== undefined) {
  28925. texture.image = texData.image;
  28926. } else if (texData.data !== undefined) {
  28927. texture.image.width = texData.width;
  28928. texture.image.height = texData.height;
  28929. texture.image.data = texData.data;
  28930. }
  28931. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  28932. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  28933. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  28934. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  28935. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  28936. if (texData.encoding !== undefined) {
  28937. texture.encoding = texData.encoding;
  28938. }
  28939. if (texData.flipY !== undefined) {
  28940. texture.flipY = texData.flipY;
  28941. }
  28942. if (texData.format !== undefined) {
  28943. texture.format = texData.format;
  28944. }
  28945. if (texData.type !== undefined) {
  28946. texture.type = texData.type;
  28947. }
  28948. if (texData.mipmaps !== undefined) {
  28949. texture.mipmaps = texData.mipmaps;
  28950. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  28951. }
  28952. if (texData.mipmapCount === 1) {
  28953. texture.minFilter = LinearFilter;
  28954. }
  28955. if (texData.generateMipmaps !== undefined) {
  28956. texture.generateMipmaps = texData.generateMipmaps;
  28957. }
  28958. texture.needsUpdate = true;
  28959. if (onLoad) onLoad(texture, texData);
  28960. }, onProgress, onError);
  28961. return texture;
  28962. }
  28963. }
  28964. class TextureLoader extends Loader {
  28965. constructor(manager) {
  28966. super(manager);
  28967. }
  28968. load(url, onLoad, onProgress, onError) {
  28969. const texture = new Texture();
  28970. const loader = new ImageLoader(this.manager);
  28971. loader.setCrossOrigin(this.crossOrigin);
  28972. loader.setPath(this.path);
  28973. loader.load(url, function (image) {
  28974. texture.image = image;
  28975. texture.needsUpdate = true;
  28976. if (onLoad !== undefined) {
  28977. onLoad(texture);
  28978. }
  28979. }, onProgress, onError);
  28980. return texture;
  28981. }
  28982. }
  28983. class Light extends Object3D {
  28984. constructor(color, intensity = 1) {
  28985. super();
  28986. this.type = 'Light';
  28987. this.color = new Color(color);
  28988. this.intensity = intensity;
  28989. }
  28990. dispose() {// Empty here in base class; some subclasses override.
  28991. }
  28992. copy(source) {
  28993. super.copy(source);
  28994. this.color.copy(source.color);
  28995. this.intensity = source.intensity;
  28996. return this;
  28997. }
  28998. toJSON(meta) {
  28999. const data = super.toJSON(meta);
  29000. data.object.color = this.color.getHex();
  29001. data.object.intensity = this.intensity;
  29002. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  29003. if (this.distance !== undefined) data.object.distance = this.distance;
  29004. if (this.angle !== undefined) data.object.angle = this.angle;
  29005. if (this.decay !== undefined) data.object.decay = this.decay;
  29006. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  29007. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  29008. return data;
  29009. }
  29010. }
  29011. Light.prototype.isLight = true;
  29012. class HemisphereLight extends Light {
  29013. constructor(skyColor, groundColor, intensity) {
  29014. super(skyColor, intensity);
  29015. this.type = 'HemisphereLight';
  29016. this.position.copy(Object3D.DefaultUp);
  29017. this.updateMatrix();
  29018. this.groundColor = new Color(groundColor);
  29019. }
  29020. copy(source) {
  29021. Light.prototype.copy.call(this, source);
  29022. this.groundColor.copy(source.groundColor);
  29023. return this;
  29024. }
  29025. }
  29026. HemisphereLight.prototype.isHemisphereLight = true;
  29027. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  29028. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  29029. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  29030. class LightShadow {
  29031. constructor(camera) {
  29032. this.camera = camera;
  29033. this.bias = 0;
  29034. this.normalBias = 0;
  29035. this.radius = 1;
  29036. this.blurSamples = 8;
  29037. this.mapSize = new Vector2(512, 512);
  29038. this.map = null;
  29039. this.mapPass = null;
  29040. this.matrix = new Matrix4();
  29041. this.autoUpdate = true;
  29042. this.needsUpdate = false;
  29043. this._frustum = new Frustum();
  29044. this._frameExtents = new Vector2(1, 1);
  29045. this._viewportCount = 1;
  29046. this._viewports = [new Vector4(0, 0, 1, 1)];
  29047. }
  29048. getViewportCount() {
  29049. return this._viewportCount;
  29050. }
  29051. getFrustum() {
  29052. return this._frustum;
  29053. }
  29054. updateMatrices(light) {
  29055. const shadowCamera = this.camera;
  29056. const shadowMatrix = this.matrix;
  29057. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  29058. shadowCamera.position.copy(_lightPositionWorld$1);
  29059. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  29060. shadowCamera.lookAt(_lookTarget$1);
  29061. shadowCamera.updateMatrixWorld();
  29062. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  29063. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  29064. 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);
  29065. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  29066. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  29067. }
  29068. getViewport(viewportIndex) {
  29069. return this._viewports[viewportIndex];
  29070. }
  29071. getFrameExtents() {
  29072. return this._frameExtents;
  29073. }
  29074. dispose() {
  29075. if (this.map) {
  29076. this.map.dispose();
  29077. }
  29078. if (this.mapPass) {
  29079. this.mapPass.dispose();
  29080. }
  29081. }
  29082. copy(source) {
  29083. this.camera = source.camera.clone();
  29084. this.bias = source.bias;
  29085. this.radius = source.radius;
  29086. this.mapSize.copy(source.mapSize);
  29087. return this;
  29088. }
  29089. clone() {
  29090. return new this.constructor().copy(this);
  29091. }
  29092. toJSON() {
  29093. const object = {};
  29094. if (this.bias !== 0) object.bias = this.bias;
  29095. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  29096. if (this.radius !== 1) object.radius = this.radius;
  29097. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  29098. object.camera = this.camera.toJSON(false).object;
  29099. delete object.camera.matrix;
  29100. return object;
  29101. }
  29102. }
  29103. class SpotLightShadow extends LightShadow {
  29104. constructor() {
  29105. super(new PerspectiveCamera(50, 1, 0.5, 500));
  29106. this.focus = 1;
  29107. }
  29108. updateMatrices(light) {
  29109. const camera = this.camera;
  29110. const fov = RAD2DEG * 2 * light.angle * this.focus;
  29111. const aspect = this.mapSize.width / this.mapSize.height;
  29112. const far = light.distance || camera.far;
  29113. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  29114. camera.fov = fov;
  29115. camera.aspect = aspect;
  29116. camera.far = far;
  29117. camera.updateProjectionMatrix();
  29118. }
  29119. super.updateMatrices(light);
  29120. }
  29121. copy(source) {
  29122. super.copy(source);
  29123. this.focus = source.focus;
  29124. return this;
  29125. }
  29126. }
  29127. SpotLightShadow.prototype.isSpotLightShadow = true;
  29128. class SpotLight extends Light {
  29129. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  29130. super(color, intensity);
  29131. this.type = 'SpotLight';
  29132. this.position.copy(Object3D.DefaultUp);
  29133. this.updateMatrix();
  29134. this.target = new Object3D();
  29135. this.distance = distance;
  29136. this.angle = angle;
  29137. this.penumbra = penumbra;
  29138. this.decay = decay; // for physically correct lights, should be 2.
  29139. this.shadow = new SpotLightShadow();
  29140. }
  29141. get power() {
  29142. // compute the light's luminous power (in lumens) from its intensity (in candela)
  29143. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  29144. return this.intensity * Math.PI;
  29145. }
  29146. set power(power) {
  29147. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  29148. this.intensity = power / Math.PI;
  29149. }
  29150. dispose() {
  29151. this.shadow.dispose();
  29152. }
  29153. copy(source) {
  29154. super.copy(source);
  29155. this.distance = source.distance;
  29156. this.angle = source.angle;
  29157. this.penumbra = source.penumbra;
  29158. this.decay = source.decay;
  29159. this.target = source.target.clone();
  29160. this.shadow = source.shadow.clone();
  29161. return this;
  29162. }
  29163. }
  29164. SpotLight.prototype.isSpotLight = true;
  29165. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  29166. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  29167. const _lookTarget = /*@__PURE__*/new Vector3();
  29168. class PointLightShadow extends LightShadow {
  29169. constructor() {
  29170. super(new PerspectiveCamera(90, 1, 0.5, 500));
  29171. this._frameExtents = new Vector2(4, 2);
  29172. this._viewportCount = 6;
  29173. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  29174. // following orientation:
  29175. //
  29176. // xzXZ
  29177. // y Y
  29178. //
  29179. // X - Positive x direction
  29180. // x - Negative x direction
  29181. // Y - Positive y direction
  29182. // y - Negative y direction
  29183. // Z - Positive z direction
  29184. // z - Negative z direction
  29185. // positive X
  29186. new Vector4(2, 1, 1, 1), // negative X
  29187. new Vector4(0, 1, 1, 1), // positive Z
  29188. new Vector4(3, 1, 1, 1), // negative Z
  29189. new Vector4(1, 1, 1, 1), // positive Y
  29190. new Vector4(3, 0, 1, 1), // negative Y
  29191. new Vector4(1, 0, 1, 1)];
  29192. 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)];
  29193. 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)];
  29194. }
  29195. updateMatrices(light, viewportIndex = 0) {
  29196. const camera = this.camera;
  29197. const shadowMatrix = this.matrix;
  29198. const far = light.distance || camera.far;
  29199. if (far !== camera.far) {
  29200. camera.far = far;
  29201. camera.updateProjectionMatrix();
  29202. }
  29203. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29204. camera.position.copy(_lightPositionWorld);
  29205. _lookTarget.copy(camera.position);
  29206. _lookTarget.add(this._cubeDirections[viewportIndex]);
  29207. camera.up.copy(this._cubeUps[viewportIndex]);
  29208. camera.lookAt(_lookTarget);
  29209. camera.updateMatrixWorld();
  29210. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  29211. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  29212. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  29213. }
  29214. }
  29215. PointLightShadow.prototype.isPointLightShadow = true;
  29216. class PointLight extends Light {
  29217. constructor(color, intensity, distance = 0, decay = 1) {
  29218. super(color, intensity);
  29219. this.type = 'PointLight';
  29220. this.distance = distance;
  29221. this.decay = decay; // for physically correct lights, should be 2.
  29222. this.shadow = new PointLightShadow();
  29223. }
  29224. get power() {
  29225. // compute the light's luminous power (in lumens) from its intensity (in candela)
  29226. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  29227. return this.intensity * 4 * Math.PI;
  29228. }
  29229. set power(power) {
  29230. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  29231. this.intensity = power / (4 * Math.PI);
  29232. }
  29233. dispose() {
  29234. this.shadow.dispose();
  29235. }
  29236. copy(source) {
  29237. super.copy(source);
  29238. this.distance = source.distance;
  29239. this.decay = source.decay;
  29240. this.shadow = source.shadow.clone();
  29241. return this;
  29242. }
  29243. }
  29244. PointLight.prototype.isPointLight = true;
  29245. class DirectionalLightShadow extends LightShadow {
  29246. constructor() {
  29247. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  29248. }
  29249. }
  29250. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  29251. class DirectionalLight extends Light {
  29252. constructor(color, intensity) {
  29253. super(color, intensity);
  29254. this.type = 'DirectionalLight';
  29255. this.position.copy(Object3D.DefaultUp);
  29256. this.updateMatrix();
  29257. this.target = new Object3D();
  29258. this.shadow = new DirectionalLightShadow();
  29259. }
  29260. dispose() {
  29261. this.shadow.dispose();
  29262. }
  29263. copy(source) {
  29264. super.copy(source);
  29265. this.target = source.target.clone();
  29266. this.shadow = source.shadow.clone();
  29267. return this;
  29268. }
  29269. }
  29270. DirectionalLight.prototype.isDirectionalLight = true;
  29271. class AmbientLight extends Light {
  29272. constructor(color, intensity) {
  29273. super(color, intensity);
  29274. this.type = 'AmbientLight';
  29275. }
  29276. }
  29277. AmbientLight.prototype.isAmbientLight = true;
  29278. class RectAreaLight extends Light {
  29279. constructor(color, intensity, width = 10, height = 10) {
  29280. super(color, intensity);
  29281. this.type = 'RectAreaLight';
  29282. this.width = width;
  29283. this.height = height;
  29284. }
  29285. get power() {
  29286. // compute the light's luminous power (in lumens) from its intensity (in nits)
  29287. return this.intensity * this.width * this.height * Math.PI;
  29288. }
  29289. set power(power) {
  29290. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  29291. this.intensity = power / (this.width * this.height * Math.PI);
  29292. }
  29293. copy(source) {
  29294. super.copy(source);
  29295. this.width = source.width;
  29296. this.height = source.height;
  29297. return this;
  29298. }
  29299. toJSON(meta) {
  29300. const data = super.toJSON(meta);
  29301. data.object.width = this.width;
  29302. data.object.height = this.height;
  29303. return data;
  29304. }
  29305. }
  29306. RectAreaLight.prototype.isRectAreaLight = true;
  29307. /**
  29308. * Primary reference:
  29309. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29310. *
  29311. * Secondary reference:
  29312. * https://www.ppsloan.org/publications/StupidSH36.pdf
  29313. */
  29314. // 3-band SH defined by 9 coefficients
  29315. class SphericalHarmonics3 {
  29316. constructor() {
  29317. this.coefficients = [];
  29318. for (let i = 0; i < 9; i++) {
  29319. this.coefficients.push(new Vector3());
  29320. }
  29321. }
  29322. set(coefficients) {
  29323. for (let i = 0; i < 9; i++) {
  29324. this.coefficients[i].copy(coefficients[i]);
  29325. }
  29326. return this;
  29327. }
  29328. zero() {
  29329. for (let i = 0; i < 9; i++) {
  29330. this.coefficients[i].set(0, 0, 0);
  29331. }
  29332. return this;
  29333. } // get the radiance in the direction of the normal
  29334. // target is a Vector3
  29335. getAt(normal, target) {
  29336. // normal is assumed to be unit length
  29337. const x = normal.x,
  29338. y = normal.y,
  29339. z = normal.z;
  29340. const coeff = this.coefficients; // band 0
  29341. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  29342. target.addScaledVector(coeff[1], 0.488603 * y);
  29343. target.addScaledVector(coeff[2], 0.488603 * z);
  29344. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  29345. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  29346. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  29347. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  29348. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  29349. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  29350. return target;
  29351. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  29352. // target is a Vector3
  29353. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29354. getIrradianceAt(normal, target) {
  29355. // normal is assumed to be unit length
  29356. const x = normal.x,
  29357. y = normal.y,
  29358. z = normal.z;
  29359. const coeff = this.coefficients; // band 0
  29360. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  29361. // band 1
  29362. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  29363. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  29364. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  29365. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  29366. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  29367. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  29368. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  29369. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  29370. return target;
  29371. }
  29372. add(sh) {
  29373. for (let i = 0; i < 9; i++) {
  29374. this.coefficients[i].add(sh.coefficients[i]);
  29375. }
  29376. return this;
  29377. }
  29378. addScaledSH(sh, s) {
  29379. for (let i = 0; i < 9; i++) {
  29380. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  29381. }
  29382. return this;
  29383. }
  29384. scale(s) {
  29385. for (let i = 0; i < 9; i++) {
  29386. this.coefficients[i].multiplyScalar(s);
  29387. }
  29388. return this;
  29389. }
  29390. lerp(sh, alpha) {
  29391. for (let i = 0; i < 9; i++) {
  29392. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  29393. }
  29394. return this;
  29395. }
  29396. equals(sh) {
  29397. for (let i = 0; i < 9; i++) {
  29398. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  29399. return false;
  29400. }
  29401. }
  29402. return true;
  29403. }
  29404. copy(sh) {
  29405. return this.set(sh.coefficients);
  29406. }
  29407. clone() {
  29408. return new this.constructor().copy(this);
  29409. }
  29410. fromArray(array, offset = 0) {
  29411. const coefficients = this.coefficients;
  29412. for (let i = 0; i < 9; i++) {
  29413. coefficients[i].fromArray(array, offset + i * 3);
  29414. }
  29415. return this;
  29416. }
  29417. toArray(array = [], offset = 0) {
  29418. const coefficients = this.coefficients;
  29419. for (let i = 0; i < 9; i++) {
  29420. coefficients[i].toArray(array, offset + i * 3);
  29421. }
  29422. return array;
  29423. } // evaluate the basis functions
  29424. // shBasis is an Array[ 9 ]
  29425. static getBasisAt(normal, shBasis) {
  29426. // normal is assumed to be unit length
  29427. const x = normal.x,
  29428. y = normal.y,
  29429. z = normal.z; // band 0
  29430. shBasis[0] = 0.282095; // band 1
  29431. shBasis[1] = 0.488603 * y;
  29432. shBasis[2] = 0.488603 * z;
  29433. shBasis[3] = 0.488603 * x; // band 2
  29434. shBasis[4] = 1.092548 * x * y;
  29435. shBasis[5] = 1.092548 * y * z;
  29436. shBasis[6] = 0.315392 * (3 * z * z - 1);
  29437. shBasis[7] = 1.092548 * x * z;
  29438. shBasis[8] = 0.546274 * (x * x - y * y);
  29439. }
  29440. }
  29441. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  29442. class LightProbe extends Light {
  29443. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  29444. super(undefined, intensity);
  29445. this.sh = sh;
  29446. }
  29447. copy(source) {
  29448. super.copy(source);
  29449. this.sh.copy(source.sh);
  29450. return this;
  29451. }
  29452. fromJSON(json) {
  29453. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  29454. this.sh.fromArray(json.sh);
  29455. return this;
  29456. }
  29457. toJSON(meta) {
  29458. const data = super.toJSON(meta);
  29459. data.object.sh = this.sh.toArray();
  29460. return data;
  29461. }
  29462. }
  29463. LightProbe.prototype.isLightProbe = true;
  29464. class MaterialLoader extends Loader {
  29465. constructor(manager) {
  29466. super(manager);
  29467. this.textures = {};
  29468. }
  29469. load(url, onLoad, onProgress, onError) {
  29470. const scope = this;
  29471. const loader = new FileLoader(scope.manager);
  29472. loader.setPath(scope.path);
  29473. loader.setRequestHeader(scope.requestHeader);
  29474. loader.setWithCredentials(scope.withCredentials);
  29475. loader.load(url, function (text) {
  29476. try {
  29477. onLoad(scope.parse(JSON.parse(text)));
  29478. } catch (e) {
  29479. if (onError) {
  29480. onError(e);
  29481. } else {
  29482. console.error(e);
  29483. }
  29484. scope.manager.itemError(url);
  29485. }
  29486. }, onProgress, onError);
  29487. }
  29488. parse(json) {
  29489. const textures = this.textures;
  29490. function getTexture(name) {
  29491. if (textures[name] === undefined) {
  29492. console.warn('THREE.MaterialLoader: Undefined texture', name);
  29493. }
  29494. return textures[name];
  29495. }
  29496. const material = new Materials[json.type]();
  29497. if (json.uuid !== undefined) material.uuid = json.uuid;
  29498. if (json.name !== undefined) material.name = json.name;
  29499. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  29500. if (json.roughness !== undefined) material.roughness = json.roughness;
  29501. if (json.metalness !== undefined) material.metalness = json.metalness;
  29502. if (json.sheen !== undefined) material.sheen = json.sheen;
  29503. if (json.sheenTint !== undefined) material.sheenTint = new Color().setHex(json.sheenTint);
  29504. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  29505. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  29506. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  29507. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  29508. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  29509. if (json.shininess !== undefined) material.shininess = json.shininess;
  29510. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  29511. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  29512. if (json.transmission !== undefined) material.transmission = json.transmission;
  29513. if (json.thickness !== undefined) material.thickness = json.thickness;
  29514. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  29515. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  29516. if (json.fog !== undefined) material.fog = json.fog;
  29517. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  29518. if (json.blending !== undefined) material.blending = json.blending;
  29519. if (json.combine !== undefined) material.combine = json.combine;
  29520. if (json.side !== undefined) material.side = json.side;
  29521. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  29522. if (json.opacity !== undefined) material.opacity = json.opacity;
  29523. if (json.format !== undefined) material.format = json.format;
  29524. if (json.transparent !== undefined) material.transparent = json.transparent;
  29525. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  29526. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  29527. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  29528. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  29529. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  29530. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  29531. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  29532. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  29533. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  29534. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  29535. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  29536. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  29537. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  29538. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  29539. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  29540. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  29541. if (json.rotation !== undefined) material.rotation = json.rotation;
  29542. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  29543. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  29544. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  29545. if (json.scale !== undefined) material.scale = json.scale;
  29546. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  29547. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  29548. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  29549. if (json.dithering !== undefined) material.dithering = json.dithering;
  29550. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  29551. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  29552. if (json.visible !== undefined) material.visible = json.visible;
  29553. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  29554. if (json.userData !== undefined) material.userData = json.userData;
  29555. if (json.vertexColors !== undefined) {
  29556. if (typeof json.vertexColors === 'number') {
  29557. material.vertexColors = json.vertexColors > 0 ? true : false;
  29558. } else {
  29559. material.vertexColors = json.vertexColors;
  29560. }
  29561. } // Shader Material
  29562. if (json.uniforms !== undefined) {
  29563. for (const name in json.uniforms) {
  29564. const uniform = json.uniforms[name];
  29565. material.uniforms[name] = {};
  29566. switch (uniform.type) {
  29567. case 't':
  29568. material.uniforms[name].value = getTexture(uniform.value);
  29569. break;
  29570. case 'c':
  29571. material.uniforms[name].value = new Color().setHex(uniform.value);
  29572. break;
  29573. case 'v2':
  29574. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  29575. break;
  29576. case 'v3':
  29577. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  29578. break;
  29579. case 'v4':
  29580. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  29581. break;
  29582. case 'm3':
  29583. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  29584. break;
  29585. case 'm4':
  29586. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  29587. break;
  29588. default:
  29589. material.uniforms[name].value = uniform.value;
  29590. }
  29591. }
  29592. }
  29593. if (json.defines !== undefined) material.defines = json.defines;
  29594. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  29595. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  29596. if (json.extensions !== undefined) {
  29597. for (const key in json.extensions) {
  29598. material.extensions[key] = json.extensions[key];
  29599. }
  29600. } // Deprecated
  29601. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  29602. // for PointsMaterial
  29603. if (json.size !== undefined) material.size = json.size;
  29604. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  29605. if (json.map !== undefined) material.map = getTexture(json.map);
  29606. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  29607. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  29608. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  29609. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  29610. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  29611. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  29612. if (json.normalScale !== undefined) {
  29613. let normalScale = json.normalScale;
  29614. if (Array.isArray(normalScale) === false) {
  29615. // Blender exporter used to export a scalar. See #7459
  29616. normalScale = [normalScale, normalScale];
  29617. }
  29618. material.normalScale = new Vector2().fromArray(normalScale);
  29619. }
  29620. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  29621. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  29622. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  29623. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  29624. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  29625. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  29626. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  29627. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  29628. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  29629. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  29630. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  29631. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  29632. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  29633. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  29634. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  29635. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  29636. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  29637. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  29638. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  29639. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  29640. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  29641. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  29642. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  29643. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  29644. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  29645. return material;
  29646. }
  29647. setTextures(value) {
  29648. this.textures = value;
  29649. return this;
  29650. }
  29651. }
  29652. class LoaderUtils {
  29653. static decodeText(array) {
  29654. if (typeof TextDecoder !== 'undefined') {
  29655. return new TextDecoder().decode(array);
  29656. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  29657. // throws a "maximum call stack size exceeded" error for large arrays.
  29658. let s = '';
  29659. for (let i = 0, il = array.length; i < il; i++) {
  29660. // Implicitly assumes little-endian.
  29661. s += String.fromCharCode(array[i]);
  29662. }
  29663. try {
  29664. // merges multi-byte utf-8 characters.
  29665. return decodeURIComponent(escape(s));
  29666. } catch (e) {
  29667. // see #16358
  29668. return s;
  29669. }
  29670. }
  29671. static extractUrlBase(url) {
  29672. const index = url.lastIndexOf('/');
  29673. if (index === -1) return './';
  29674. return url.substr(0, index + 1);
  29675. }
  29676. }
  29677. class InstancedBufferGeometry extends BufferGeometry {
  29678. constructor() {
  29679. super();
  29680. this.type = 'InstancedBufferGeometry';
  29681. this.instanceCount = Infinity;
  29682. }
  29683. copy(source) {
  29684. super.copy(source);
  29685. this.instanceCount = source.instanceCount;
  29686. return this;
  29687. }
  29688. clone() {
  29689. return new this.constructor().copy(this);
  29690. }
  29691. toJSON() {
  29692. const data = super.toJSON(this);
  29693. data.instanceCount = this.instanceCount;
  29694. data.isInstancedBufferGeometry = true;
  29695. return data;
  29696. }
  29697. }
  29698. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  29699. class BufferGeometryLoader extends Loader {
  29700. constructor(manager) {
  29701. super(manager);
  29702. }
  29703. load(url, onLoad, onProgress, onError) {
  29704. const scope = this;
  29705. const loader = new FileLoader(scope.manager);
  29706. loader.setPath(scope.path);
  29707. loader.setRequestHeader(scope.requestHeader);
  29708. loader.setWithCredentials(scope.withCredentials);
  29709. loader.load(url, function (text) {
  29710. try {
  29711. onLoad(scope.parse(JSON.parse(text)));
  29712. } catch (e) {
  29713. if (onError) {
  29714. onError(e);
  29715. } else {
  29716. console.error(e);
  29717. }
  29718. scope.manager.itemError(url);
  29719. }
  29720. }, onProgress, onError);
  29721. }
  29722. parse(json) {
  29723. const interleavedBufferMap = {};
  29724. const arrayBufferMap = {};
  29725. function getInterleavedBuffer(json, uuid) {
  29726. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  29727. const interleavedBuffers = json.interleavedBuffers;
  29728. const interleavedBuffer = interleavedBuffers[uuid];
  29729. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  29730. const array = getTypedArray(interleavedBuffer.type, buffer);
  29731. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  29732. ib.uuid = interleavedBuffer.uuid;
  29733. interleavedBufferMap[uuid] = ib;
  29734. return ib;
  29735. }
  29736. function getArrayBuffer(json, uuid) {
  29737. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  29738. const arrayBuffers = json.arrayBuffers;
  29739. const arrayBuffer = arrayBuffers[uuid];
  29740. const ab = new Uint32Array(arrayBuffer).buffer;
  29741. arrayBufferMap[uuid] = ab;
  29742. return ab;
  29743. }
  29744. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  29745. const index = json.data.index;
  29746. if (index !== undefined) {
  29747. const typedArray = getTypedArray(index.type, index.array);
  29748. geometry.setIndex(new BufferAttribute(typedArray, 1));
  29749. }
  29750. const attributes = json.data.attributes;
  29751. for (const key in attributes) {
  29752. const attribute = attributes[key];
  29753. let bufferAttribute;
  29754. if (attribute.isInterleavedBufferAttribute) {
  29755. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  29756. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  29757. } else {
  29758. const typedArray = getTypedArray(attribute.type, attribute.array);
  29759. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  29760. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  29761. }
  29762. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  29763. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  29764. if (attribute.updateRange !== undefined) {
  29765. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  29766. bufferAttribute.updateRange.count = attribute.updateRange.count;
  29767. }
  29768. geometry.setAttribute(key, bufferAttribute);
  29769. }
  29770. const morphAttributes = json.data.morphAttributes;
  29771. if (morphAttributes) {
  29772. for (const key in morphAttributes) {
  29773. const attributeArray = morphAttributes[key];
  29774. const array = [];
  29775. for (let i = 0, il = attributeArray.length; i < il; i++) {
  29776. const attribute = attributeArray[i];
  29777. let bufferAttribute;
  29778. if (attribute.isInterleavedBufferAttribute) {
  29779. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  29780. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  29781. } else {
  29782. const typedArray = getTypedArray(attribute.type, attribute.array);
  29783. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  29784. }
  29785. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  29786. array.push(bufferAttribute);
  29787. }
  29788. geometry.morphAttributes[key] = array;
  29789. }
  29790. }
  29791. const morphTargetsRelative = json.data.morphTargetsRelative;
  29792. if (morphTargetsRelative) {
  29793. geometry.morphTargetsRelative = true;
  29794. }
  29795. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  29796. if (groups !== undefined) {
  29797. for (let i = 0, n = groups.length; i !== n; ++i) {
  29798. const group = groups[i];
  29799. geometry.addGroup(group.start, group.count, group.materialIndex);
  29800. }
  29801. }
  29802. const boundingSphere = json.data.boundingSphere;
  29803. if (boundingSphere !== undefined) {
  29804. const center = new Vector3();
  29805. if (boundingSphere.center !== undefined) {
  29806. center.fromArray(boundingSphere.center);
  29807. }
  29808. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  29809. }
  29810. if (json.name) geometry.name = json.name;
  29811. if (json.userData) geometry.userData = json.userData;
  29812. return geometry;
  29813. }
  29814. }
  29815. class ObjectLoader extends Loader {
  29816. constructor(manager) {
  29817. super(manager);
  29818. }
  29819. load(url, onLoad, onProgress, onError) {
  29820. const scope = this;
  29821. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  29822. this.resourcePath = this.resourcePath || path;
  29823. const loader = new FileLoader(this.manager);
  29824. loader.setPath(this.path);
  29825. loader.setRequestHeader(this.requestHeader);
  29826. loader.setWithCredentials(this.withCredentials);
  29827. loader.load(url, function (text) {
  29828. let json = null;
  29829. try {
  29830. json = JSON.parse(text);
  29831. } catch (error) {
  29832. if (onError !== undefined) onError(error);
  29833. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  29834. return;
  29835. }
  29836. const metadata = json.metadata;
  29837. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  29838. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  29839. return;
  29840. }
  29841. scope.parse(json, onLoad);
  29842. }, onProgress, onError);
  29843. }
  29844. async loadAsync(url, onProgress) {
  29845. const scope = this;
  29846. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  29847. this.resourcePath = this.resourcePath || path;
  29848. const loader = new FileLoader(this.manager);
  29849. loader.setPath(this.path);
  29850. loader.setRequestHeader(this.requestHeader);
  29851. loader.setWithCredentials(this.withCredentials);
  29852. const text = await loader.loadAsync(url, onProgress);
  29853. const json = JSON.parse(text);
  29854. const metadata = json.metadata;
  29855. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  29856. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  29857. }
  29858. return await scope.parseAsync(json);
  29859. }
  29860. parse(json, onLoad) {
  29861. const animations = this.parseAnimations(json.animations);
  29862. const shapes = this.parseShapes(json.shapes);
  29863. const geometries = this.parseGeometries(json.geometries, shapes);
  29864. const images = this.parseImages(json.images, function () {
  29865. if (onLoad !== undefined) onLoad(object);
  29866. });
  29867. const textures = this.parseTextures(json.textures, images);
  29868. const materials = this.parseMaterials(json.materials, textures);
  29869. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  29870. const skeletons = this.parseSkeletons(json.skeletons, object);
  29871. this.bindSkeletons(object, skeletons); //
  29872. if (onLoad !== undefined) {
  29873. let hasImages = false;
  29874. for (const uuid in images) {
  29875. if (images[uuid] instanceof HTMLImageElement) {
  29876. hasImages = true;
  29877. break;
  29878. }
  29879. }
  29880. if (hasImages === false) onLoad(object);
  29881. }
  29882. return object;
  29883. }
  29884. async parseAsync(json) {
  29885. const animations = this.parseAnimations(json.animations);
  29886. const shapes = this.parseShapes(json.shapes);
  29887. const geometries = this.parseGeometries(json.geometries, shapes);
  29888. const images = await this.parseImagesAsync(json.images);
  29889. const textures = this.parseTextures(json.textures, images);
  29890. const materials = this.parseMaterials(json.materials, textures);
  29891. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  29892. const skeletons = this.parseSkeletons(json.skeletons, object);
  29893. this.bindSkeletons(object, skeletons);
  29894. return object;
  29895. }
  29896. parseShapes(json) {
  29897. const shapes = {};
  29898. if (json !== undefined) {
  29899. for (let i = 0, l = json.length; i < l; i++) {
  29900. const shape = new Shape().fromJSON(json[i]);
  29901. shapes[shape.uuid] = shape;
  29902. }
  29903. }
  29904. return shapes;
  29905. }
  29906. parseSkeletons(json, object) {
  29907. const skeletons = {};
  29908. const bones = {}; // generate bone lookup table
  29909. object.traverse(function (child) {
  29910. if (child.isBone) bones[child.uuid] = child;
  29911. }); // create skeletons
  29912. if (json !== undefined) {
  29913. for (let i = 0, l = json.length; i < l; i++) {
  29914. const skeleton = new Skeleton().fromJSON(json[i], bones);
  29915. skeletons[skeleton.uuid] = skeleton;
  29916. }
  29917. }
  29918. return skeletons;
  29919. }
  29920. parseGeometries(json, shapes) {
  29921. const geometries = {};
  29922. if (json !== undefined) {
  29923. const bufferGeometryLoader = new BufferGeometryLoader();
  29924. for (let i = 0, l = json.length; i < l; i++) {
  29925. let geometry;
  29926. const data = json[i];
  29927. switch (data.type) {
  29928. case 'BufferGeometry':
  29929. case 'InstancedBufferGeometry':
  29930. geometry = bufferGeometryLoader.parse(data);
  29931. break;
  29932. case 'Geometry':
  29933. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  29934. var geometryLoader = new THREE.LegacyJSONLoader();
  29935. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  29936. } else {
  29937. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  29938. }
  29939. break;
  29940. default:
  29941. if (data.type in Geometries) {
  29942. geometry = Geometries[data.type].fromJSON(data, shapes);
  29943. } else {
  29944. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  29945. }
  29946. }
  29947. geometry.uuid = data.uuid;
  29948. if (data.name !== undefined) geometry.name = data.name;
  29949. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  29950. geometries[data.uuid] = geometry;
  29951. }
  29952. }
  29953. return geometries;
  29954. }
  29955. parseMaterials(json, textures) {
  29956. const cache = {}; // MultiMaterial
  29957. const materials = {};
  29958. if (json !== undefined) {
  29959. const loader = new MaterialLoader();
  29960. loader.setTextures(textures);
  29961. for (let i = 0, l = json.length; i < l; i++) {
  29962. const data = json[i];
  29963. if (data.type === 'MultiMaterial') {
  29964. // Deprecated
  29965. const array = [];
  29966. for (let j = 0; j < data.materials.length; j++) {
  29967. const material = data.materials[j];
  29968. if (cache[material.uuid] === undefined) {
  29969. cache[material.uuid] = loader.parse(material);
  29970. }
  29971. array.push(cache[material.uuid]);
  29972. }
  29973. materials[data.uuid] = array;
  29974. } else {
  29975. if (cache[data.uuid] === undefined) {
  29976. cache[data.uuid] = loader.parse(data);
  29977. }
  29978. materials[data.uuid] = cache[data.uuid];
  29979. }
  29980. }
  29981. }
  29982. return materials;
  29983. }
  29984. parseAnimations(json) {
  29985. const animations = {};
  29986. if (json !== undefined) {
  29987. for (let i = 0; i < json.length; i++) {
  29988. const data = json[i];
  29989. const clip = AnimationClip.parse(data);
  29990. animations[clip.uuid] = clip;
  29991. }
  29992. }
  29993. return animations;
  29994. }
  29995. parseImages(json, onLoad) {
  29996. const scope = this;
  29997. const images = {};
  29998. let loader;
  29999. function loadImage(url) {
  30000. scope.manager.itemStart(url);
  30001. return loader.load(url, function () {
  30002. scope.manager.itemEnd(url);
  30003. }, undefined, function () {
  30004. scope.manager.itemError(url);
  30005. scope.manager.itemEnd(url);
  30006. });
  30007. }
  30008. function deserializeImage(image) {
  30009. if (typeof image === 'string') {
  30010. const url = image;
  30011. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  30012. return loadImage(path);
  30013. } else {
  30014. if (image.data) {
  30015. return {
  30016. data: getTypedArray(image.type, image.data),
  30017. width: image.width,
  30018. height: image.height
  30019. };
  30020. } else {
  30021. return null;
  30022. }
  30023. }
  30024. }
  30025. if (json !== undefined && json.length > 0) {
  30026. const manager = new LoadingManager(onLoad);
  30027. loader = new ImageLoader(manager);
  30028. loader.setCrossOrigin(this.crossOrigin);
  30029. for (let i = 0, il = json.length; i < il; i++) {
  30030. const image = json[i];
  30031. const url = image.url;
  30032. if (Array.isArray(url)) {
  30033. // load array of images e.g CubeTexture
  30034. images[image.uuid] = [];
  30035. for (let j = 0, jl = url.length; j < jl; j++) {
  30036. const currentUrl = url[j];
  30037. const deserializedImage = deserializeImage(currentUrl);
  30038. if (deserializedImage !== null) {
  30039. if (deserializedImage instanceof HTMLImageElement) {
  30040. images[image.uuid].push(deserializedImage);
  30041. } else {
  30042. // special case: handle array of data textures for cube textures
  30043. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  30044. }
  30045. }
  30046. }
  30047. } else {
  30048. // load single image
  30049. const deserializedImage = deserializeImage(image.url);
  30050. if (deserializedImage !== null) {
  30051. images[image.uuid] = deserializedImage;
  30052. }
  30053. }
  30054. }
  30055. }
  30056. return images;
  30057. }
  30058. async parseImagesAsync(json) {
  30059. const scope = this;
  30060. const images = {};
  30061. let loader;
  30062. async function deserializeImage(image) {
  30063. if (typeof image === 'string') {
  30064. const url = image;
  30065. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  30066. return await loader.loadAsync(path);
  30067. } else {
  30068. if (image.data) {
  30069. return {
  30070. data: getTypedArray(image.type, image.data),
  30071. width: image.width,
  30072. height: image.height
  30073. };
  30074. } else {
  30075. return null;
  30076. }
  30077. }
  30078. }
  30079. if (json !== undefined && json.length > 0) {
  30080. loader = new ImageLoader(this.manager);
  30081. loader.setCrossOrigin(this.crossOrigin);
  30082. for (let i = 0, il = json.length; i < il; i++) {
  30083. const image = json[i];
  30084. const url = image.url;
  30085. if (Array.isArray(url)) {
  30086. // load array of images e.g CubeTexture
  30087. images[image.uuid] = [];
  30088. for (let j = 0, jl = url.length; j < jl; j++) {
  30089. const currentUrl = url[j];
  30090. const deserializedImage = await deserializeImage(currentUrl);
  30091. if (deserializedImage !== null) {
  30092. if (deserializedImage instanceof HTMLImageElement) {
  30093. images[image.uuid].push(deserializedImage);
  30094. } else {
  30095. // special case: handle array of data textures for cube textures
  30096. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  30097. }
  30098. }
  30099. }
  30100. } else {
  30101. // load single image
  30102. const deserializedImage = await deserializeImage(image.url);
  30103. if (deserializedImage !== null) {
  30104. images[image.uuid] = deserializedImage;
  30105. }
  30106. }
  30107. }
  30108. }
  30109. return images;
  30110. }
  30111. parseTextures(json, images) {
  30112. function parseConstant(value, type) {
  30113. if (typeof value === 'number') return value;
  30114. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  30115. return type[value];
  30116. }
  30117. const textures = {};
  30118. if (json !== undefined) {
  30119. for (let i = 0, l = json.length; i < l; i++) {
  30120. const data = json[i];
  30121. if (data.image === undefined) {
  30122. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  30123. }
  30124. if (images[data.image] === undefined) {
  30125. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  30126. }
  30127. let texture;
  30128. const image = images[data.image];
  30129. if (Array.isArray(image)) {
  30130. texture = new CubeTexture(image);
  30131. if (image.length === 6) texture.needsUpdate = true;
  30132. } else {
  30133. if (image && image.data) {
  30134. texture = new DataTexture(image.data, image.width, image.height);
  30135. } else {
  30136. texture = new Texture(image);
  30137. }
  30138. if (image) texture.needsUpdate = true; // textures can have undefined image data
  30139. }
  30140. texture.uuid = data.uuid;
  30141. if (data.name !== undefined) texture.name = data.name;
  30142. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  30143. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  30144. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  30145. if (data.center !== undefined) texture.center.fromArray(data.center);
  30146. if (data.rotation !== undefined) texture.rotation = data.rotation;
  30147. if (data.wrap !== undefined) {
  30148. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  30149. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  30150. }
  30151. if (data.format !== undefined) texture.format = data.format;
  30152. if (data.type !== undefined) texture.type = data.type;
  30153. if (data.encoding !== undefined) texture.encoding = data.encoding;
  30154. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  30155. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  30156. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  30157. if (data.flipY !== undefined) texture.flipY = data.flipY;
  30158. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  30159. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  30160. textures[data.uuid] = texture;
  30161. }
  30162. }
  30163. return textures;
  30164. }
  30165. parseObject(data, geometries, materials, textures, animations) {
  30166. let object;
  30167. function getGeometry(name) {
  30168. if (geometries[name] === undefined) {
  30169. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  30170. }
  30171. return geometries[name];
  30172. }
  30173. function getMaterial(name) {
  30174. if (name === undefined) return undefined;
  30175. if (Array.isArray(name)) {
  30176. const array = [];
  30177. for (let i = 0, l = name.length; i < l; i++) {
  30178. const uuid = name[i];
  30179. if (materials[uuid] === undefined) {
  30180. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  30181. }
  30182. array.push(materials[uuid]);
  30183. }
  30184. return array;
  30185. }
  30186. if (materials[name] === undefined) {
  30187. console.warn('THREE.ObjectLoader: Undefined material', name);
  30188. }
  30189. return materials[name];
  30190. }
  30191. function getTexture(uuid) {
  30192. if (textures[uuid] === undefined) {
  30193. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  30194. }
  30195. return textures[uuid];
  30196. }
  30197. let geometry, material;
  30198. switch (data.type) {
  30199. case 'Scene':
  30200. object = new Scene();
  30201. if (data.background !== undefined) {
  30202. if (Number.isInteger(data.background)) {
  30203. object.background = new Color(data.background);
  30204. } else {
  30205. object.background = getTexture(data.background);
  30206. }
  30207. }
  30208. if (data.environment !== undefined) {
  30209. object.environment = getTexture(data.environment);
  30210. }
  30211. if (data.fog !== undefined) {
  30212. if (data.fog.type === 'Fog') {
  30213. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  30214. } else if (data.fog.type === 'FogExp2') {
  30215. object.fog = new FogExp2(data.fog.color, data.fog.density);
  30216. }
  30217. }
  30218. break;
  30219. case 'PerspectiveCamera':
  30220. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  30221. if (data.focus !== undefined) object.focus = data.focus;
  30222. if (data.zoom !== undefined) object.zoom = data.zoom;
  30223. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  30224. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  30225. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30226. break;
  30227. case 'OrthographicCamera':
  30228. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  30229. if (data.zoom !== undefined) object.zoom = data.zoom;
  30230. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30231. break;
  30232. case 'AmbientLight':
  30233. object = new AmbientLight(data.color, data.intensity);
  30234. break;
  30235. case 'DirectionalLight':
  30236. object = new DirectionalLight(data.color, data.intensity);
  30237. break;
  30238. case 'PointLight':
  30239. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  30240. break;
  30241. case 'RectAreaLight':
  30242. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  30243. break;
  30244. case 'SpotLight':
  30245. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  30246. break;
  30247. case 'HemisphereLight':
  30248. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  30249. break;
  30250. case 'LightProbe':
  30251. object = new LightProbe().fromJSON(data);
  30252. break;
  30253. case 'SkinnedMesh':
  30254. geometry = getGeometry(data.geometry);
  30255. material = getMaterial(data.material);
  30256. object = new SkinnedMesh(geometry, material);
  30257. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  30258. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  30259. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  30260. break;
  30261. case 'Mesh':
  30262. geometry = getGeometry(data.geometry);
  30263. material = getMaterial(data.material);
  30264. object = new Mesh(geometry, material);
  30265. break;
  30266. case 'InstancedMesh':
  30267. geometry = getGeometry(data.geometry);
  30268. material = getMaterial(data.material);
  30269. const count = data.count;
  30270. const instanceMatrix = data.instanceMatrix;
  30271. const instanceColor = data.instanceColor;
  30272. object = new InstancedMesh(geometry, material, count);
  30273. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  30274. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  30275. break;
  30276. case 'LOD':
  30277. object = new LOD();
  30278. break;
  30279. case 'Line':
  30280. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  30281. break;
  30282. case 'LineLoop':
  30283. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  30284. break;
  30285. case 'LineSegments':
  30286. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  30287. break;
  30288. case 'PointCloud':
  30289. case 'Points':
  30290. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  30291. break;
  30292. case 'Sprite':
  30293. object = new Sprite(getMaterial(data.material));
  30294. break;
  30295. case 'Group':
  30296. object = new Group();
  30297. break;
  30298. case 'Bone':
  30299. object = new Bone();
  30300. break;
  30301. default:
  30302. object = new Object3D();
  30303. }
  30304. object.uuid = data.uuid;
  30305. if (data.name !== undefined) object.name = data.name;
  30306. if (data.matrix !== undefined) {
  30307. object.matrix.fromArray(data.matrix);
  30308. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  30309. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  30310. } else {
  30311. if (data.position !== undefined) object.position.fromArray(data.position);
  30312. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  30313. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  30314. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  30315. }
  30316. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  30317. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  30318. if (data.shadow) {
  30319. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  30320. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  30321. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  30322. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  30323. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  30324. }
  30325. if (data.visible !== undefined) object.visible = data.visible;
  30326. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  30327. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  30328. if (data.userData !== undefined) object.userData = data.userData;
  30329. if (data.layers !== undefined) object.layers.mask = data.layers;
  30330. if (data.children !== undefined) {
  30331. const children = data.children;
  30332. for (let i = 0; i < children.length; i++) {
  30333. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  30334. }
  30335. }
  30336. if (data.animations !== undefined) {
  30337. const objectAnimations = data.animations;
  30338. for (let i = 0; i < objectAnimations.length; i++) {
  30339. const uuid = objectAnimations[i];
  30340. object.animations.push(animations[uuid]);
  30341. }
  30342. }
  30343. if (data.type === 'LOD') {
  30344. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  30345. const levels = data.levels;
  30346. for (let l = 0; l < levels.length; l++) {
  30347. const level = levels[l];
  30348. const child = object.getObjectByProperty('uuid', level.object);
  30349. if (child !== undefined) {
  30350. object.addLevel(child, level.distance);
  30351. }
  30352. }
  30353. }
  30354. return object;
  30355. }
  30356. bindSkeletons(object, skeletons) {
  30357. if (Object.keys(skeletons).length === 0) return;
  30358. object.traverse(function (child) {
  30359. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  30360. const skeleton = skeletons[child.skeleton];
  30361. if (skeleton === undefined) {
  30362. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  30363. } else {
  30364. child.bind(skeleton, child.bindMatrix);
  30365. }
  30366. }
  30367. });
  30368. }
  30369. /* DEPRECATED */
  30370. setTexturePath(value) {
  30371. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  30372. return this.setResourcePath(value);
  30373. }
  30374. }
  30375. const TEXTURE_MAPPING = {
  30376. UVMapping: UVMapping,
  30377. CubeReflectionMapping: CubeReflectionMapping,
  30378. CubeRefractionMapping: CubeRefractionMapping,
  30379. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30380. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30381. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30382. CubeUVRefractionMapping: CubeUVRefractionMapping
  30383. };
  30384. const TEXTURE_WRAPPING = {
  30385. RepeatWrapping: RepeatWrapping,
  30386. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30387. MirroredRepeatWrapping: MirroredRepeatWrapping
  30388. };
  30389. const TEXTURE_FILTER = {
  30390. NearestFilter: NearestFilter,
  30391. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30392. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30393. LinearFilter: LinearFilter,
  30394. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30395. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  30396. };
  30397. class ImageBitmapLoader extends Loader {
  30398. constructor(manager) {
  30399. super(manager);
  30400. if (typeof createImageBitmap === 'undefined') {
  30401. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  30402. }
  30403. if (typeof fetch === 'undefined') {
  30404. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  30405. }
  30406. this.options = {
  30407. premultiplyAlpha: 'none'
  30408. };
  30409. }
  30410. setOptions(options) {
  30411. this.options = options;
  30412. return this;
  30413. }
  30414. load(url, onLoad, onProgress, onError) {
  30415. if (url === undefined) url = '';
  30416. if (this.path !== undefined) url = this.path + url;
  30417. url = this.manager.resolveURL(url);
  30418. const scope = this;
  30419. const cached = Cache.get(url);
  30420. if (cached !== undefined) {
  30421. scope.manager.itemStart(url);
  30422. setTimeout(function () {
  30423. if (onLoad) onLoad(cached);
  30424. scope.manager.itemEnd(url);
  30425. }, 0);
  30426. return cached;
  30427. }
  30428. const fetchOptions = {};
  30429. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  30430. fetchOptions.headers = this.requestHeader;
  30431. fetch(url, fetchOptions).then(function (res) {
  30432. return res.blob();
  30433. }).then(function (blob) {
  30434. return createImageBitmap(blob, Object.assign(scope.options, {
  30435. colorSpaceConversion: 'none'
  30436. }));
  30437. }).then(function (imageBitmap) {
  30438. Cache.add(url, imageBitmap);
  30439. if (onLoad) onLoad(imageBitmap);
  30440. scope.manager.itemEnd(url);
  30441. }).catch(function (e) {
  30442. if (onError) onError(e);
  30443. scope.manager.itemError(url);
  30444. scope.manager.itemEnd(url);
  30445. });
  30446. scope.manager.itemStart(url);
  30447. }
  30448. }
  30449. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  30450. let _context;
  30451. const AudioContext = {
  30452. getContext: function () {
  30453. if (_context === undefined) {
  30454. _context = new (window.AudioContext || window.webkitAudioContext)();
  30455. }
  30456. return _context;
  30457. },
  30458. setContext: function (value) {
  30459. _context = value;
  30460. }
  30461. };
  30462. class AudioLoader extends Loader {
  30463. constructor(manager) {
  30464. super(manager);
  30465. }
  30466. load(url, onLoad, onProgress, onError) {
  30467. const scope = this;
  30468. const loader = new FileLoader(this.manager);
  30469. loader.setResponseType('arraybuffer');
  30470. loader.setPath(this.path);
  30471. loader.setRequestHeader(this.requestHeader);
  30472. loader.setWithCredentials(this.withCredentials);
  30473. loader.load(url, function (buffer) {
  30474. try {
  30475. // Create a copy of the buffer. The `decodeAudioData` method
  30476. // detaches the buffer when complete, preventing reuse.
  30477. const bufferCopy = buffer.slice(0);
  30478. const context = AudioContext.getContext();
  30479. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  30480. onLoad(audioBuffer);
  30481. });
  30482. } catch (e) {
  30483. if (onError) {
  30484. onError(e);
  30485. } else {
  30486. console.error(e);
  30487. }
  30488. scope.manager.itemError(url);
  30489. }
  30490. }, onProgress, onError);
  30491. }
  30492. }
  30493. class HemisphereLightProbe extends LightProbe {
  30494. constructor(skyColor, groundColor, intensity = 1) {
  30495. super(undefined, intensity);
  30496. const color1 = new Color().set(skyColor);
  30497. const color2 = new Color().set(groundColor);
  30498. const sky = new Vector3(color1.r, color1.g, color1.b);
  30499. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30500. const c0 = Math.sqrt(Math.PI);
  30501. const c1 = c0 * Math.sqrt(0.75);
  30502. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  30503. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  30504. }
  30505. }
  30506. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  30507. class AmbientLightProbe extends LightProbe {
  30508. constructor(color, intensity = 1) {
  30509. super(undefined, intensity);
  30510. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30511. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  30512. }
  30513. }
  30514. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  30515. const _eyeRight = /*@__PURE__*/new Matrix4();
  30516. const _eyeLeft = /*@__PURE__*/new Matrix4();
  30517. class StereoCamera {
  30518. constructor() {
  30519. this.type = 'StereoCamera';
  30520. this.aspect = 1;
  30521. this.eyeSep = 0.064;
  30522. this.cameraL = new PerspectiveCamera();
  30523. this.cameraL.layers.enable(1);
  30524. this.cameraL.matrixAutoUpdate = false;
  30525. this.cameraR = new PerspectiveCamera();
  30526. this.cameraR.layers.enable(2);
  30527. this.cameraR.matrixAutoUpdate = false;
  30528. this._cache = {
  30529. focus: null,
  30530. fov: null,
  30531. aspect: null,
  30532. near: null,
  30533. far: null,
  30534. zoom: null,
  30535. eyeSep: null
  30536. };
  30537. }
  30538. update(camera) {
  30539. const cache = this._cache;
  30540. const 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;
  30541. if (needsUpdate) {
  30542. cache.focus = camera.focus;
  30543. cache.fov = camera.fov;
  30544. cache.aspect = camera.aspect * this.aspect;
  30545. cache.near = camera.near;
  30546. cache.far = camera.far;
  30547. cache.zoom = camera.zoom;
  30548. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  30549. // http://paulbourke.net/stereographics/stereorender/
  30550. const projectionMatrix = camera.projectionMatrix.clone();
  30551. const eyeSepHalf = cache.eyeSep / 2;
  30552. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  30553. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  30554. let xmin, xmax; // translate xOffset
  30555. _eyeLeft.elements[12] = -eyeSepHalf;
  30556. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  30557. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  30558. xmax = ymax * cache.aspect + eyeSepOnProjection;
  30559. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  30560. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  30561. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  30562. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  30563. xmax = ymax * cache.aspect - eyeSepOnProjection;
  30564. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  30565. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  30566. this.cameraR.projectionMatrix.copy(projectionMatrix);
  30567. }
  30568. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  30569. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  30570. }
  30571. }
  30572. class Clock {
  30573. constructor(autoStart = true) {
  30574. this.autoStart = autoStart;
  30575. this.startTime = 0;
  30576. this.oldTime = 0;
  30577. this.elapsedTime = 0;
  30578. this.running = false;
  30579. }
  30580. start() {
  30581. this.startTime = now();
  30582. this.oldTime = this.startTime;
  30583. this.elapsedTime = 0;
  30584. this.running = true;
  30585. }
  30586. stop() {
  30587. this.getElapsedTime();
  30588. this.running = false;
  30589. this.autoStart = false;
  30590. }
  30591. getElapsedTime() {
  30592. this.getDelta();
  30593. return this.elapsedTime;
  30594. }
  30595. getDelta() {
  30596. let diff = 0;
  30597. if (this.autoStart && !this.running) {
  30598. this.start();
  30599. return 0;
  30600. }
  30601. if (this.running) {
  30602. const newTime = now();
  30603. diff = (newTime - this.oldTime) / 1000;
  30604. this.oldTime = newTime;
  30605. this.elapsedTime += diff;
  30606. }
  30607. return diff;
  30608. }
  30609. }
  30610. function now() {
  30611. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  30612. }
  30613. const _position$1 = /*@__PURE__*/new Vector3();
  30614. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  30615. const _scale$1 = /*@__PURE__*/new Vector3();
  30616. const _orientation$1 = /*@__PURE__*/new Vector3();
  30617. class AudioListener extends Object3D {
  30618. constructor() {
  30619. super();
  30620. this.type = 'AudioListener';
  30621. this.context = AudioContext.getContext();
  30622. this.gain = this.context.createGain();
  30623. this.gain.connect(this.context.destination);
  30624. this.filter = null;
  30625. this.timeDelta = 0; // private
  30626. this._clock = new Clock();
  30627. }
  30628. getInput() {
  30629. return this.gain;
  30630. }
  30631. removeFilter() {
  30632. if (this.filter !== null) {
  30633. this.gain.disconnect(this.filter);
  30634. this.filter.disconnect(this.context.destination);
  30635. this.gain.connect(this.context.destination);
  30636. this.filter = null;
  30637. }
  30638. return this;
  30639. }
  30640. getFilter() {
  30641. return this.filter;
  30642. }
  30643. setFilter(value) {
  30644. if (this.filter !== null) {
  30645. this.gain.disconnect(this.filter);
  30646. this.filter.disconnect(this.context.destination);
  30647. } else {
  30648. this.gain.disconnect(this.context.destination);
  30649. }
  30650. this.filter = value;
  30651. this.gain.connect(this.filter);
  30652. this.filter.connect(this.context.destination);
  30653. return this;
  30654. }
  30655. getMasterVolume() {
  30656. return this.gain.gain.value;
  30657. }
  30658. setMasterVolume(value) {
  30659. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  30660. return this;
  30661. }
  30662. updateMatrixWorld(force) {
  30663. super.updateMatrixWorld(force);
  30664. const listener = this.context.listener;
  30665. const up = this.up;
  30666. this.timeDelta = this._clock.getDelta();
  30667. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  30668. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  30669. if (listener.positionX) {
  30670. // code path for Chrome (see #14393)
  30671. const endTime = this.context.currentTime + this.timeDelta;
  30672. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  30673. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  30674. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  30675. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  30676. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  30677. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  30678. listener.upX.linearRampToValueAtTime(up.x, endTime);
  30679. listener.upY.linearRampToValueAtTime(up.y, endTime);
  30680. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  30681. } else {
  30682. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  30683. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  30684. }
  30685. }
  30686. }
  30687. class Audio extends Object3D {
  30688. constructor(listener) {
  30689. super();
  30690. this.type = 'Audio';
  30691. this.listener = listener;
  30692. this.context = listener.context;
  30693. this.gain = this.context.createGain();
  30694. this.gain.connect(listener.getInput());
  30695. this.autoplay = false;
  30696. this.buffer = null;
  30697. this.detune = 0;
  30698. this.loop = false;
  30699. this.loopStart = 0;
  30700. this.loopEnd = 0;
  30701. this.offset = 0;
  30702. this.duration = undefined;
  30703. this.playbackRate = 1;
  30704. this.isPlaying = false;
  30705. this.hasPlaybackControl = true;
  30706. this.source = null;
  30707. this.sourceType = 'empty';
  30708. this._startedAt = 0;
  30709. this._progress = 0;
  30710. this._connected = false;
  30711. this.filters = [];
  30712. }
  30713. getOutput() {
  30714. return this.gain;
  30715. }
  30716. setNodeSource(audioNode) {
  30717. this.hasPlaybackControl = false;
  30718. this.sourceType = 'audioNode';
  30719. this.source = audioNode;
  30720. this.connect();
  30721. return this;
  30722. }
  30723. setMediaElementSource(mediaElement) {
  30724. this.hasPlaybackControl = false;
  30725. this.sourceType = 'mediaNode';
  30726. this.source = this.context.createMediaElementSource(mediaElement);
  30727. this.connect();
  30728. return this;
  30729. }
  30730. setMediaStreamSource(mediaStream) {
  30731. this.hasPlaybackControl = false;
  30732. this.sourceType = 'mediaStreamNode';
  30733. this.source = this.context.createMediaStreamSource(mediaStream);
  30734. this.connect();
  30735. return this;
  30736. }
  30737. setBuffer(audioBuffer) {
  30738. this.buffer = audioBuffer;
  30739. this.sourceType = 'buffer';
  30740. if (this.autoplay) this.play();
  30741. return this;
  30742. }
  30743. play(delay = 0) {
  30744. if (this.isPlaying === true) {
  30745. console.warn('THREE.Audio: Audio is already playing.');
  30746. return;
  30747. }
  30748. if (this.hasPlaybackControl === false) {
  30749. console.warn('THREE.Audio: this Audio has no playback control.');
  30750. return;
  30751. }
  30752. this._startedAt = this.context.currentTime + delay;
  30753. const source = this.context.createBufferSource();
  30754. source.buffer = this.buffer;
  30755. source.loop = this.loop;
  30756. source.loopStart = this.loopStart;
  30757. source.loopEnd = this.loopEnd;
  30758. source.onended = this.onEnded.bind(this);
  30759. source.start(this._startedAt, this._progress + this.offset, this.duration);
  30760. this.isPlaying = true;
  30761. this.source = source;
  30762. this.setDetune(this.detune);
  30763. this.setPlaybackRate(this.playbackRate);
  30764. return this.connect();
  30765. }
  30766. pause() {
  30767. if (this.hasPlaybackControl === false) {
  30768. console.warn('THREE.Audio: this Audio has no playback control.');
  30769. return;
  30770. }
  30771. if (this.isPlaying === true) {
  30772. // update current progress
  30773. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  30774. if (this.loop === true) {
  30775. // ensure _progress does not exceed duration with looped audios
  30776. this._progress = this._progress % (this.duration || this.buffer.duration);
  30777. }
  30778. this.source.stop();
  30779. this.source.onended = null;
  30780. this.isPlaying = false;
  30781. }
  30782. return this;
  30783. }
  30784. stop() {
  30785. if (this.hasPlaybackControl === false) {
  30786. console.warn('THREE.Audio: this Audio has no playback control.');
  30787. return;
  30788. }
  30789. this._progress = 0;
  30790. this.source.stop();
  30791. this.source.onended = null;
  30792. this.isPlaying = false;
  30793. return this;
  30794. }
  30795. connect() {
  30796. if (this.filters.length > 0) {
  30797. this.source.connect(this.filters[0]);
  30798. for (let i = 1, l = this.filters.length; i < l; i++) {
  30799. this.filters[i - 1].connect(this.filters[i]);
  30800. }
  30801. this.filters[this.filters.length - 1].connect(this.getOutput());
  30802. } else {
  30803. this.source.connect(this.getOutput());
  30804. }
  30805. this._connected = true;
  30806. return this;
  30807. }
  30808. disconnect() {
  30809. if (this.filters.length > 0) {
  30810. this.source.disconnect(this.filters[0]);
  30811. for (let i = 1, l = this.filters.length; i < l; i++) {
  30812. this.filters[i - 1].disconnect(this.filters[i]);
  30813. }
  30814. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  30815. } else {
  30816. this.source.disconnect(this.getOutput());
  30817. }
  30818. this._connected = false;
  30819. return this;
  30820. }
  30821. getFilters() {
  30822. return this.filters;
  30823. }
  30824. setFilters(value) {
  30825. if (!value) value = [];
  30826. if (this._connected === true) {
  30827. this.disconnect();
  30828. this.filters = value.slice();
  30829. this.connect();
  30830. } else {
  30831. this.filters = value.slice();
  30832. }
  30833. return this;
  30834. }
  30835. setDetune(value) {
  30836. this.detune = value;
  30837. if (this.source.detune === undefined) return; // only set detune when available
  30838. if (this.isPlaying === true) {
  30839. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  30840. }
  30841. return this;
  30842. }
  30843. getDetune() {
  30844. return this.detune;
  30845. }
  30846. getFilter() {
  30847. return this.getFilters()[0];
  30848. }
  30849. setFilter(filter) {
  30850. return this.setFilters(filter ? [filter] : []);
  30851. }
  30852. setPlaybackRate(value) {
  30853. if (this.hasPlaybackControl === false) {
  30854. console.warn('THREE.Audio: this Audio has no playback control.');
  30855. return;
  30856. }
  30857. this.playbackRate = value;
  30858. if (this.isPlaying === true) {
  30859. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  30860. }
  30861. return this;
  30862. }
  30863. getPlaybackRate() {
  30864. return this.playbackRate;
  30865. }
  30866. onEnded() {
  30867. this.isPlaying = false;
  30868. }
  30869. getLoop() {
  30870. if (this.hasPlaybackControl === false) {
  30871. console.warn('THREE.Audio: this Audio has no playback control.');
  30872. return false;
  30873. }
  30874. return this.loop;
  30875. }
  30876. setLoop(value) {
  30877. if (this.hasPlaybackControl === false) {
  30878. console.warn('THREE.Audio: this Audio has no playback control.');
  30879. return;
  30880. }
  30881. this.loop = value;
  30882. if (this.isPlaying === true) {
  30883. this.source.loop = this.loop;
  30884. }
  30885. return this;
  30886. }
  30887. setLoopStart(value) {
  30888. this.loopStart = value;
  30889. return this;
  30890. }
  30891. setLoopEnd(value) {
  30892. this.loopEnd = value;
  30893. return this;
  30894. }
  30895. getVolume() {
  30896. return this.gain.gain.value;
  30897. }
  30898. setVolume(value) {
  30899. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  30900. return this;
  30901. }
  30902. }
  30903. const _position = /*@__PURE__*/new Vector3();
  30904. const _quaternion = /*@__PURE__*/new Quaternion();
  30905. const _scale = /*@__PURE__*/new Vector3();
  30906. const _orientation = /*@__PURE__*/new Vector3();
  30907. class PositionalAudio extends Audio {
  30908. constructor(listener) {
  30909. super(listener);
  30910. this.panner = this.context.createPanner();
  30911. this.panner.panningModel = 'HRTF';
  30912. this.panner.connect(this.gain);
  30913. }
  30914. getOutput() {
  30915. return this.panner;
  30916. }
  30917. getRefDistance() {
  30918. return this.panner.refDistance;
  30919. }
  30920. setRefDistance(value) {
  30921. this.panner.refDistance = value;
  30922. return this;
  30923. }
  30924. getRolloffFactor() {
  30925. return this.panner.rolloffFactor;
  30926. }
  30927. setRolloffFactor(value) {
  30928. this.panner.rolloffFactor = value;
  30929. return this;
  30930. }
  30931. getDistanceModel() {
  30932. return this.panner.distanceModel;
  30933. }
  30934. setDistanceModel(value) {
  30935. this.panner.distanceModel = value;
  30936. return this;
  30937. }
  30938. getMaxDistance() {
  30939. return this.panner.maxDistance;
  30940. }
  30941. setMaxDistance(value) {
  30942. this.panner.maxDistance = value;
  30943. return this;
  30944. }
  30945. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30946. this.panner.coneInnerAngle = coneInnerAngle;
  30947. this.panner.coneOuterAngle = coneOuterAngle;
  30948. this.panner.coneOuterGain = coneOuterGain;
  30949. return this;
  30950. }
  30951. updateMatrixWorld(force) {
  30952. super.updateMatrixWorld(force);
  30953. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  30954. this.matrixWorld.decompose(_position, _quaternion, _scale);
  30955. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  30956. const panner = this.panner;
  30957. if (panner.positionX) {
  30958. // code path for Chrome and Firefox (see #14393)
  30959. const endTime = this.context.currentTime + this.listener.timeDelta;
  30960. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  30961. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  30962. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  30963. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  30964. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  30965. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  30966. } else {
  30967. panner.setPosition(_position.x, _position.y, _position.z);
  30968. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  30969. }
  30970. }
  30971. }
  30972. class AudioAnalyser {
  30973. constructor(audio, fftSize = 2048) {
  30974. this.analyser = audio.context.createAnalyser();
  30975. this.analyser.fftSize = fftSize;
  30976. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  30977. audio.getOutput().connect(this.analyser);
  30978. }
  30979. getFrequencyData() {
  30980. this.analyser.getByteFrequencyData(this.data);
  30981. return this.data;
  30982. }
  30983. getAverageFrequency() {
  30984. let value = 0;
  30985. const data = this.getFrequencyData();
  30986. for (let i = 0; i < data.length; i++) {
  30987. value += data[i];
  30988. }
  30989. return value / data.length;
  30990. }
  30991. }
  30992. class PropertyMixer {
  30993. constructor(binding, typeName, valueSize) {
  30994. this.binding = binding;
  30995. this.valueSize = valueSize;
  30996. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  30997. //
  30998. // interpolators can use .buffer as their .result
  30999. // the data then goes to 'incoming'
  31000. //
  31001. // 'accu0' and 'accu1' are used frame-interleaved for
  31002. // the cumulative result and are compared to detect
  31003. // changes
  31004. //
  31005. // 'orig' stores the original state of the property
  31006. //
  31007. // 'add' is used for additive cumulative results
  31008. //
  31009. // 'work' is optional and is only present for quaternion types. It is used
  31010. // to store intermediate quaternion multiplication results
  31011. switch (typeName) {
  31012. case 'quaternion':
  31013. mixFunction = this._slerp;
  31014. mixFunctionAdditive = this._slerpAdditive;
  31015. setIdentity = this._setAdditiveIdentityQuaternion;
  31016. this.buffer = new Float64Array(valueSize * 6);
  31017. this._workIndex = 5;
  31018. break;
  31019. case 'string':
  31020. case 'bool':
  31021. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  31022. // additive is not relevant for non-numeric types
  31023. mixFunctionAdditive = this._select;
  31024. setIdentity = this._setAdditiveIdentityOther;
  31025. this.buffer = new Array(valueSize * 5);
  31026. break;
  31027. default:
  31028. mixFunction = this._lerp;
  31029. mixFunctionAdditive = this._lerpAdditive;
  31030. setIdentity = this._setAdditiveIdentityNumeric;
  31031. this.buffer = new Float64Array(valueSize * 5);
  31032. }
  31033. this._mixBufferRegion = mixFunction;
  31034. this._mixBufferRegionAdditive = mixFunctionAdditive;
  31035. this._setIdentity = setIdentity;
  31036. this._origIndex = 3;
  31037. this._addIndex = 4;
  31038. this.cumulativeWeight = 0;
  31039. this.cumulativeWeightAdditive = 0;
  31040. this.useCount = 0;
  31041. this.referenceCount = 0;
  31042. } // accumulate data in the 'incoming' region into 'accu<i>'
  31043. accumulate(accuIndex, weight) {
  31044. // note: happily accumulating nothing when weight = 0, the caller knows
  31045. // the weight and shouldn't have made the call in the first place
  31046. const buffer = this.buffer,
  31047. stride = this.valueSize,
  31048. offset = accuIndex * stride + stride;
  31049. let currentWeight = this.cumulativeWeight;
  31050. if (currentWeight === 0) {
  31051. // accuN := incoming * weight
  31052. for (let i = 0; i !== stride; ++i) {
  31053. buffer[offset + i] = buffer[i];
  31054. }
  31055. currentWeight = weight;
  31056. } else {
  31057. // accuN := accuN + incoming * weight
  31058. currentWeight += weight;
  31059. const mix = weight / currentWeight;
  31060. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  31061. }
  31062. this.cumulativeWeight = currentWeight;
  31063. } // accumulate data in the 'incoming' region into 'add'
  31064. accumulateAdditive(weight) {
  31065. const buffer = this.buffer,
  31066. stride = this.valueSize,
  31067. offset = stride * this._addIndex;
  31068. if (this.cumulativeWeightAdditive === 0) {
  31069. // add = identity
  31070. this._setIdentity();
  31071. } // add := add + incoming * weight
  31072. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  31073. this.cumulativeWeightAdditive += weight;
  31074. } // apply the state of 'accu<i>' to the binding when accus differ
  31075. apply(accuIndex) {
  31076. const stride = this.valueSize,
  31077. buffer = this.buffer,
  31078. offset = accuIndex * stride + stride,
  31079. weight = this.cumulativeWeight,
  31080. weightAdditive = this.cumulativeWeightAdditive,
  31081. binding = this.binding;
  31082. this.cumulativeWeight = 0;
  31083. this.cumulativeWeightAdditive = 0;
  31084. if (weight < 1) {
  31085. // accuN := accuN + original * ( 1 - cumulativeWeight )
  31086. const originalValueOffset = stride * this._origIndex;
  31087. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  31088. }
  31089. if (weightAdditive > 0) {
  31090. // accuN := accuN + additive accuN
  31091. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  31092. }
  31093. for (let i = stride, e = stride + stride; i !== e; ++i) {
  31094. if (buffer[i] !== buffer[i + stride]) {
  31095. // value has changed -> update scene graph
  31096. binding.setValue(buffer, offset);
  31097. break;
  31098. }
  31099. }
  31100. } // remember the state of the bound property and copy it to both accus
  31101. saveOriginalState() {
  31102. const binding = this.binding;
  31103. const buffer = this.buffer,
  31104. stride = this.valueSize,
  31105. originalValueOffset = stride * this._origIndex;
  31106. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  31107. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  31108. buffer[i] = buffer[originalValueOffset + i % stride];
  31109. } // Add to identity for additive
  31110. this._setIdentity();
  31111. this.cumulativeWeight = 0;
  31112. this.cumulativeWeightAdditive = 0;
  31113. } // apply the state previously taken via 'saveOriginalState' to the binding
  31114. restoreOriginalState() {
  31115. const originalValueOffset = this.valueSize * 3;
  31116. this.binding.setValue(this.buffer, originalValueOffset);
  31117. }
  31118. _setAdditiveIdentityNumeric() {
  31119. const startIndex = this._addIndex * this.valueSize;
  31120. const endIndex = startIndex + this.valueSize;
  31121. for (let i = startIndex; i < endIndex; i++) {
  31122. this.buffer[i] = 0;
  31123. }
  31124. }
  31125. _setAdditiveIdentityQuaternion() {
  31126. this._setAdditiveIdentityNumeric();
  31127. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  31128. }
  31129. _setAdditiveIdentityOther() {
  31130. const startIndex = this._origIndex * this.valueSize;
  31131. const targetIndex = this._addIndex * this.valueSize;
  31132. for (let i = 0; i < this.valueSize; i++) {
  31133. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  31134. }
  31135. } // mix functions
  31136. _select(buffer, dstOffset, srcOffset, t, stride) {
  31137. if (t >= 0.5) {
  31138. for (let i = 0; i !== stride; ++i) {
  31139. buffer[dstOffset + i] = buffer[srcOffset + i];
  31140. }
  31141. }
  31142. }
  31143. _slerp(buffer, dstOffset, srcOffset, t) {
  31144. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  31145. }
  31146. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31147. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  31148. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  31149. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  31150. }
  31151. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  31152. const s = 1 - t;
  31153. for (let i = 0; i !== stride; ++i) {
  31154. const j = dstOffset + i;
  31155. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  31156. }
  31157. }
  31158. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31159. for (let i = 0; i !== stride; ++i) {
  31160. const j = dstOffset + i;
  31161. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  31162. }
  31163. }
  31164. }
  31165. // Characters [].:/ are reserved for track binding syntax.
  31166. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  31167. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  31168. // only latin characters, and the unicode \p{L} is not yet supported. So
  31169. // instead, we exclude reserved characters and match everything else.
  31170. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  31171. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  31172. // be matched to parse the rest of the track name.
  31173. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  31174. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  31175. // characters. Accessor may contain any character except closing bracket.
  31176. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  31177. // contain any non-bracket characters.
  31178. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  31179. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  31180. const _supportedObjectNames = ['material', 'materials', 'bones'];
  31181. class Composite {
  31182. constructor(targetGroup, path, optionalParsedPath) {
  31183. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  31184. this._targetGroup = targetGroup;
  31185. this._bindings = targetGroup.subscribe_(path, parsedPath);
  31186. }
  31187. getValue(array, offset) {
  31188. this.bind(); // bind all binding
  31189. const firstValidIndex = this._targetGroup.nCachedObjects_,
  31190. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  31191. if (binding !== undefined) binding.getValue(array, offset);
  31192. }
  31193. setValue(array, offset) {
  31194. const bindings = this._bindings;
  31195. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31196. bindings[i].setValue(array, offset);
  31197. }
  31198. }
  31199. bind() {
  31200. const bindings = this._bindings;
  31201. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31202. bindings[i].bind();
  31203. }
  31204. }
  31205. unbind() {
  31206. const bindings = this._bindings;
  31207. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31208. bindings[i].unbind();
  31209. }
  31210. }
  31211. } // Note: This class uses a State pattern on a per-method basis:
  31212. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31213. // prototype version of these methods with one that represents
  31214. // the bound state. When the property is not found, the methods
  31215. // become no-ops.
  31216. class PropertyBinding {
  31217. constructor(rootNode, path, parsedPath) {
  31218. this.path = path;
  31219. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  31220. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  31221. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  31222. this.getValue = this._getValue_unbound;
  31223. this.setValue = this._setValue_unbound;
  31224. }
  31225. static create(root, path, parsedPath) {
  31226. if (!(root && root.isAnimationObjectGroup)) {
  31227. return new PropertyBinding(root, path, parsedPath);
  31228. } else {
  31229. return new PropertyBinding.Composite(root, path, parsedPath);
  31230. }
  31231. }
  31232. /**
  31233. * Replaces spaces with underscores and removes unsupported characters from
  31234. * node names, to ensure compatibility with parseTrackName().
  31235. *
  31236. * @param {string} name Node name to be sanitized.
  31237. * @return {string}
  31238. */
  31239. static sanitizeNodeName(name) {
  31240. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  31241. }
  31242. static parseTrackName(trackName) {
  31243. const matches = _trackRe.exec(trackName);
  31244. if (!matches) {
  31245. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  31246. }
  31247. const results = {
  31248. // directoryName: matches[ 1 ], // (tschw) currently unused
  31249. nodeName: matches[2],
  31250. objectName: matches[3],
  31251. objectIndex: matches[4],
  31252. propertyName: matches[5],
  31253. // required
  31254. propertyIndex: matches[6]
  31255. };
  31256. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  31257. if (lastDot !== undefined && lastDot !== -1) {
  31258. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  31259. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  31260. // 'bar' could be the objectName, or part of a nodeName (which can
  31261. // include '.' characters).
  31262. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  31263. results.nodeName = results.nodeName.substring(0, lastDot);
  31264. results.objectName = objectName;
  31265. }
  31266. }
  31267. if (results.propertyName === null || results.propertyName.length === 0) {
  31268. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  31269. }
  31270. return results;
  31271. }
  31272. static findNode(root, nodeName) {
  31273. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  31274. return root;
  31275. } // search into skeleton bones.
  31276. if (root.skeleton) {
  31277. const bone = root.skeleton.getBoneByName(nodeName);
  31278. if (bone !== undefined) {
  31279. return bone;
  31280. }
  31281. } // search into node subtree.
  31282. if (root.children) {
  31283. const searchNodeSubtree = function (children) {
  31284. for (let i = 0; i < children.length; i++) {
  31285. const childNode = children[i];
  31286. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  31287. return childNode;
  31288. }
  31289. const result = searchNodeSubtree(childNode.children);
  31290. if (result) return result;
  31291. }
  31292. return null;
  31293. };
  31294. const subTreeNode = searchNodeSubtree(root.children);
  31295. if (subTreeNode) {
  31296. return subTreeNode;
  31297. }
  31298. }
  31299. return null;
  31300. } // these are used to "bind" a nonexistent property
  31301. _getValue_unavailable() {}
  31302. _setValue_unavailable() {} // Getters
  31303. _getValue_direct(buffer, offset) {
  31304. buffer[offset] = this.targetObject[this.propertyName];
  31305. }
  31306. _getValue_array(buffer, offset) {
  31307. const source = this.resolvedProperty;
  31308. for (let i = 0, n = source.length; i !== n; ++i) {
  31309. buffer[offset++] = source[i];
  31310. }
  31311. }
  31312. _getValue_arrayElement(buffer, offset) {
  31313. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  31314. }
  31315. _getValue_toArray(buffer, offset) {
  31316. this.resolvedProperty.toArray(buffer, offset);
  31317. } // Direct
  31318. _setValue_direct(buffer, offset) {
  31319. this.targetObject[this.propertyName] = buffer[offset];
  31320. }
  31321. _setValue_direct_setNeedsUpdate(buffer, offset) {
  31322. this.targetObject[this.propertyName] = buffer[offset];
  31323. this.targetObject.needsUpdate = true;
  31324. }
  31325. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  31326. this.targetObject[this.propertyName] = buffer[offset];
  31327. this.targetObject.matrixWorldNeedsUpdate = true;
  31328. } // EntireArray
  31329. _setValue_array(buffer, offset) {
  31330. const dest = this.resolvedProperty;
  31331. for (let i = 0, n = dest.length; i !== n; ++i) {
  31332. dest[i] = buffer[offset++];
  31333. }
  31334. }
  31335. _setValue_array_setNeedsUpdate(buffer, offset) {
  31336. const dest = this.resolvedProperty;
  31337. for (let i = 0, n = dest.length; i !== n; ++i) {
  31338. dest[i] = buffer[offset++];
  31339. }
  31340. this.targetObject.needsUpdate = true;
  31341. }
  31342. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  31343. const dest = this.resolvedProperty;
  31344. for (let i = 0, n = dest.length; i !== n; ++i) {
  31345. dest[i] = buffer[offset++];
  31346. }
  31347. this.targetObject.matrixWorldNeedsUpdate = true;
  31348. } // ArrayElement
  31349. _setValue_arrayElement(buffer, offset) {
  31350. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31351. }
  31352. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  31353. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31354. this.targetObject.needsUpdate = true;
  31355. }
  31356. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  31357. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31358. this.targetObject.matrixWorldNeedsUpdate = true;
  31359. } // HasToFromArray
  31360. _setValue_fromArray(buffer, offset) {
  31361. this.resolvedProperty.fromArray(buffer, offset);
  31362. }
  31363. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  31364. this.resolvedProperty.fromArray(buffer, offset);
  31365. this.targetObject.needsUpdate = true;
  31366. }
  31367. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  31368. this.resolvedProperty.fromArray(buffer, offset);
  31369. this.targetObject.matrixWorldNeedsUpdate = true;
  31370. }
  31371. _getValue_unbound(targetArray, offset) {
  31372. this.bind();
  31373. this.getValue(targetArray, offset);
  31374. }
  31375. _setValue_unbound(sourceArray, offset) {
  31376. this.bind();
  31377. this.setValue(sourceArray, offset);
  31378. } // create getter / setter pair for a property in the scene graph
  31379. bind() {
  31380. let targetObject = this.node;
  31381. const parsedPath = this.parsedPath;
  31382. const objectName = parsedPath.objectName;
  31383. const propertyName = parsedPath.propertyName;
  31384. let propertyIndex = parsedPath.propertyIndex;
  31385. if (!targetObject) {
  31386. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  31387. this.node = targetObject;
  31388. } // set fail state so we can just 'return' on error
  31389. this.getValue = this._getValue_unavailable;
  31390. this.setValue = this._setValue_unavailable; // ensure there is a value node
  31391. if (!targetObject) {
  31392. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  31393. return;
  31394. }
  31395. if (objectName) {
  31396. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31397. switch (objectName) {
  31398. case 'materials':
  31399. if (!targetObject.material) {
  31400. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  31401. return;
  31402. }
  31403. if (!targetObject.material.materials) {
  31404. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  31405. return;
  31406. }
  31407. targetObject = targetObject.material.materials;
  31408. break;
  31409. case 'bones':
  31410. if (!targetObject.skeleton) {
  31411. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  31412. return;
  31413. } // potential future optimization: skip this if propertyIndex is already an integer
  31414. // and convert the integer string to a true integer.
  31415. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  31416. for (let i = 0; i < targetObject.length; i++) {
  31417. if (targetObject[i].name === objectIndex) {
  31418. objectIndex = i;
  31419. break;
  31420. }
  31421. }
  31422. break;
  31423. default:
  31424. if (targetObject[objectName] === undefined) {
  31425. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  31426. return;
  31427. }
  31428. targetObject = targetObject[objectName];
  31429. }
  31430. if (objectIndex !== undefined) {
  31431. if (targetObject[objectIndex] === undefined) {
  31432. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  31433. return;
  31434. }
  31435. targetObject = targetObject[objectIndex];
  31436. }
  31437. } // resolve property
  31438. const nodeProperty = targetObject[propertyName];
  31439. if (nodeProperty === undefined) {
  31440. const nodeName = parsedPath.nodeName;
  31441. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  31442. return;
  31443. } // determine versioning scheme
  31444. let versioning = this.Versioning.None;
  31445. this.targetObject = targetObject;
  31446. if (targetObject.needsUpdate !== undefined) {
  31447. // material
  31448. versioning = this.Versioning.NeedsUpdate;
  31449. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  31450. // node transform
  31451. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31452. } // determine how the property gets bound
  31453. let bindingType = this.BindingType.Direct;
  31454. if (propertyIndex !== undefined) {
  31455. // access a sub element of the property array (only primitives are supported right now)
  31456. if (propertyName === 'morphTargetInfluences') {
  31457. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31458. // support resolving morphTarget names into indices.
  31459. if (!targetObject.geometry) {
  31460. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  31461. return;
  31462. }
  31463. if (targetObject.geometry.isBufferGeometry) {
  31464. if (!targetObject.geometry.morphAttributes) {
  31465. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  31466. return;
  31467. }
  31468. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  31469. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  31470. }
  31471. } else {
  31472. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  31473. return;
  31474. }
  31475. }
  31476. bindingType = this.BindingType.ArrayElement;
  31477. this.resolvedProperty = nodeProperty;
  31478. this.propertyIndex = propertyIndex;
  31479. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  31480. // must use copy for Object3D.Euler/Quaternion
  31481. bindingType = this.BindingType.HasFromToArray;
  31482. this.resolvedProperty = nodeProperty;
  31483. } else if (Array.isArray(nodeProperty)) {
  31484. bindingType = this.BindingType.EntireArray;
  31485. this.resolvedProperty = nodeProperty;
  31486. } else {
  31487. this.propertyName = propertyName;
  31488. } // select getter / setter
  31489. this.getValue = this.GetterByBindingType[bindingType];
  31490. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  31491. }
  31492. unbind() {
  31493. this.node = null; // back to the prototype version of getValue / setValue
  31494. // note: avoiding to mutate the shape of 'this' via 'delete'
  31495. this.getValue = this._getValue_unbound;
  31496. this.setValue = this._setValue_unbound;
  31497. }
  31498. }
  31499. PropertyBinding.Composite = Composite;
  31500. PropertyBinding.prototype.BindingType = {
  31501. Direct: 0,
  31502. EntireArray: 1,
  31503. ArrayElement: 2,
  31504. HasFromToArray: 3
  31505. };
  31506. PropertyBinding.prototype.Versioning = {
  31507. None: 0,
  31508. NeedsUpdate: 1,
  31509. MatrixWorldNeedsUpdate: 2
  31510. };
  31511. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  31512. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  31513. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  31514. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  31515. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  31516. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  31517. /**
  31518. *
  31519. * A group of objects that receives a shared animation state.
  31520. *
  31521. * Usage:
  31522. *
  31523. * - Add objects you would otherwise pass as 'root' to the
  31524. * constructor or the .clipAction method of AnimationMixer.
  31525. *
  31526. * - Instead pass this object as 'root'.
  31527. *
  31528. * - You can also add and remove objects later when the mixer
  31529. * is running.
  31530. *
  31531. * Note:
  31532. *
  31533. * Objects of this class appear as one object to the mixer,
  31534. * so cache control of the individual objects must be done
  31535. * on the group.
  31536. *
  31537. * Limitation:
  31538. *
  31539. * - The animated properties must be compatible among the
  31540. * all objects in the group.
  31541. *
  31542. * - A single property can either be controlled through a
  31543. * target group or directly, but not both.
  31544. */
  31545. class AnimationObjectGroup {
  31546. constructor() {
  31547. this.uuid = generateUUID(); // cached objects followed by the active ones
  31548. this._objects = Array.prototype.slice.call(arguments);
  31549. this.nCachedObjects_ = 0; // threshold
  31550. // note: read by PropertyBinding.Composite
  31551. const indices = {};
  31552. this._indicesByUUID = indices; // for bookkeeping
  31553. for (let i = 0, n = arguments.length; i !== n; ++i) {
  31554. indices[arguments[i].uuid] = i;
  31555. }
  31556. this._paths = []; // inside: string
  31557. this._parsedPaths = []; // inside: { we don't care, here }
  31558. this._bindings = []; // inside: Array< PropertyBinding >
  31559. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  31560. const scope = this;
  31561. this.stats = {
  31562. objects: {
  31563. get total() {
  31564. return scope._objects.length;
  31565. },
  31566. get inUse() {
  31567. return this.total - scope.nCachedObjects_;
  31568. }
  31569. },
  31570. get bindingsPerObject() {
  31571. return scope._bindings.length;
  31572. }
  31573. };
  31574. }
  31575. add() {
  31576. const objects = this._objects,
  31577. indicesByUUID = this._indicesByUUID,
  31578. paths = this._paths,
  31579. parsedPaths = this._parsedPaths,
  31580. bindings = this._bindings,
  31581. nBindings = bindings.length;
  31582. let knownObject = undefined,
  31583. nObjects = objects.length,
  31584. nCachedObjects = this.nCachedObjects_;
  31585. for (let i = 0, n = arguments.length; i !== n; ++i) {
  31586. const object = arguments[i],
  31587. uuid = object.uuid;
  31588. let index = indicesByUUID[uuid];
  31589. if (index === undefined) {
  31590. // unknown object -> add it to the ACTIVE region
  31591. index = nObjects++;
  31592. indicesByUUID[uuid] = index;
  31593. objects.push(object); // accounting is done, now do the same for all bindings
  31594. for (let j = 0, m = nBindings; j !== m; ++j) {
  31595. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  31596. }
  31597. } else if (index < nCachedObjects) {
  31598. knownObject = objects[index]; // move existing object to the ACTIVE region
  31599. const firstActiveIndex = --nCachedObjects,
  31600. lastCachedObject = objects[firstActiveIndex];
  31601. indicesByUUID[lastCachedObject.uuid] = index;
  31602. objects[index] = lastCachedObject;
  31603. indicesByUUID[uuid] = firstActiveIndex;
  31604. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  31605. for (let j = 0, m = nBindings; j !== m; ++j) {
  31606. const bindingsForPath = bindings[j],
  31607. lastCached = bindingsForPath[firstActiveIndex];
  31608. let binding = bindingsForPath[index];
  31609. bindingsForPath[index] = lastCached;
  31610. if (binding === undefined) {
  31611. // since we do not bother to create new bindings
  31612. // for objects that are cached, the binding may
  31613. // or may not exist
  31614. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  31615. }
  31616. bindingsForPath[firstActiveIndex] = binding;
  31617. }
  31618. } else if (objects[index] !== knownObject) {
  31619. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  31620. } // else the object is already where we want it to be
  31621. } // for arguments
  31622. this.nCachedObjects_ = nCachedObjects;
  31623. }
  31624. remove() {
  31625. const objects = this._objects,
  31626. indicesByUUID = this._indicesByUUID,
  31627. bindings = this._bindings,
  31628. nBindings = bindings.length;
  31629. let nCachedObjects = this.nCachedObjects_;
  31630. for (let i = 0, n = arguments.length; i !== n; ++i) {
  31631. const object = arguments[i],
  31632. uuid = object.uuid,
  31633. index = indicesByUUID[uuid];
  31634. if (index !== undefined && index >= nCachedObjects) {
  31635. // move existing object into the CACHED region
  31636. const lastCachedIndex = nCachedObjects++,
  31637. firstActiveObject = objects[lastCachedIndex];
  31638. indicesByUUID[firstActiveObject.uuid] = index;
  31639. objects[index] = firstActiveObject;
  31640. indicesByUUID[uuid] = lastCachedIndex;
  31641. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  31642. for (let j = 0, m = nBindings; j !== m; ++j) {
  31643. const bindingsForPath = bindings[j],
  31644. firstActive = bindingsForPath[lastCachedIndex],
  31645. binding = bindingsForPath[index];
  31646. bindingsForPath[index] = firstActive;
  31647. bindingsForPath[lastCachedIndex] = binding;
  31648. }
  31649. }
  31650. } // for arguments
  31651. this.nCachedObjects_ = nCachedObjects;
  31652. } // remove & forget
  31653. uncache() {
  31654. const objects = this._objects,
  31655. indicesByUUID = this._indicesByUUID,
  31656. bindings = this._bindings,
  31657. nBindings = bindings.length;
  31658. let nCachedObjects = this.nCachedObjects_,
  31659. nObjects = objects.length;
  31660. for (let i = 0, n = arguments.length; i !== n; ++i) {
  31661. const object = arguments[i],
  31662. uuid = object.uuid,
  31663. index = indicesByUUID[uuid];
  31664. if (index !== undefined) {
  31665. delete indicesByUUID[uuid];
  31666. if (index < nCachedObjects) {
  31667. // object is cached, shrink the CACHED region
  31668. const firstActiveIndex = --nCachedObjects,
  31669. lastCachedObject = objects[firstActiveIndex],
  31670. lastIndex = --nObjects,
  31671. lastObject = objects[lastIndex]; // last cached object takes this object's place
  31672. indicesByUUID[lastCachedObject.uuid] = index;
  31673. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  31674. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  31675. objects[firstActiveIndex] = lastObject;
  31676. objects.pop(); // accounting is done, now do the same for all bindings
  31677. for (let j = 0, m = nBindings; j !== m; ++j) {
  31678. const bindingsForPath = bindings[j],
  31679. lastCached = bindingsForPath[firstActiveIndex],
  31680. last = bindingsForPath[lastIndex];
  31681. bindingsForPath[index] = lastCached;
  31682. bindingsForPath[firstActiveIndex] = last;
  31683. bindingsForPath.pop();
  31684. }
  31685. } else {
  31686. // object is active, just swap with the last and pop
  31687. const lastIndex = --nObjects,
  31688. lastObject = objects[lastIndex];
  31689. if (lastIndex > 0) {
  31690. indicesByUUID[lastObject.uuid] = index;
  31691. }
  31692. objects[index] = lastObject;
  31693. objects.pop(); // accounting is done, now do the same for all bindings
  31694. for (let j = 0, m = nBindings; j !== m; ++j) {
  31695. const bindingsForPath = bindings[j];
  31696. bindingsForPath[index] = bindingsForPath[lastIndex];
  31697. bindingsForPath.pop();
  31698. }
  31699. } // cached or active
  31700. } // if object is known
  31701. } // for arguments
  31702. this.nCachedObjects_ = nCachedObjects;
  31703. } // Internal interface used by befriended PropertyBinding.Composite:
  31704. subscribe_(path, parsedPath) {
  31705. // returns an array of bindings for the given path that is changed
  31706. // according to the contained objects in the group
  31707. const indicesByPath = this._bindingsIndicesByPath;
  31708. let index = indicesByPath[path];
  31709. const bindings = this._bindings;
  31710. if (index !== undefined) return bindings[index];
  31711. const paths = this._paths,
  31712. parsedPaths = this._parsedPaths,
  31713. objects = this._objects,
  31714. nObjects = objects.length,
  31715. nCachedObjects = this.nCachedObjects_,
  31716. bindingsForPath = new Array(nObjects);
  31717. index = bindings.length;
  31718. indicesByPath[path] = index;
  31719. paths.push(path);
  31720. parsedPaths.push(parsedPath);
  31721. bindings.push(bindingsForPath);
  31722. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  31723. const object = objects[i];
  31724. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  31725. }
  31726. return bindingsForPath;
  31727. }
  31728. unsubscribe_(path) {
  31729. // tells the group to forget about a property path and no longer
  31730. // update the array previously obtained with 'subscribe_'
  31731. const indicesByPath = this._bindingsIndicesByPath,
  31732. index = indicesByPath[path];
  31733. if (index !== undefined) {
  31734. const paths = this._paths,
  31735. parsedPaths = this._parsedPaths,
  31736. bindings = this._bindings,
  31737. lastBindingsIndex = bindings.length - 1,
  31738. lastBindings = bindings[lastBindingsIndex],
  31739. lastBindingsPath = path[lastBindingsIndex];
  31740. indicesByPath[lastBindingsPath] = index;
  31741. bindings[index] = lastBindings;
  31742. bindings.pop();
  31743. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  31744. parsedPaths.pop();
  31745. paths[index] = paths[lastBindingsIndex];
  31746. paths.pop();
  31747. }
  31748. }
  31749. }
  31750. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  31751. class AnimationAction {
  31752. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  31753. this._mixer = mixer;
  31754. this._clip = clip;
  31755. this._localRoot = localRoot;
  31756. this.blendMode = blendMode;
  31757. const tracks = clip.tracks,
  31758. nTracks = tracks.length,
  31759. interpolants = new Array(nTracks);
  31760. const interpolantSettings = {
  31761. endingStart: ZeroCurvatureEnding,
  31762. endingEnd: ZeroCurvatureEnding
  31763. };
  31764. for (let i = 0; i !== nTracks; ++i) {
  31765. const interpolant = tracks[i].createInterpolant(null);
  31766. interpolants[i] = interpolant;
  31767. interpolant.settings = interpolantSettings;
  31768. }
  31769. this._interpolantSettings = interpolantSettings;
  31770. this._interpolants = interpolants; // bound by the mixer
  31771. // inside: PropertyMixer (managed by the mixer)
  31772. this._propertyBindings = new Array(nTracks);
  31773. this._cacheIndex = null; // for the memory manager
  31774. this._byClipCacheIndex = null; // for the memory manager
  31775. this._timeScaleInterpolant = null;
  31776. this._weightInterpolant = null;
  31777. this.loop = LoopRepeat;
  31778. this._loopCount = -1; // global mixer time when the action is to be started
  31779. // it's set back to 'null' upon start of the action
  31780. this._startTime = null; // scaled local time of the action
  31781. // gets clamped or wrapped to 0..clip.duration according to loop
  31782. this.time = 0;
  31783. this.timeScale = 1;
  31784. this._effectiveTimeScale = 1;
  31785. this.weight = 1;
  31786. this._effectiveWeight = 1;
  31787. this.repetitions = Infinity; // no. of repetitions when looping
  31788. this.paused = false; // true -> zero effective time scale
  31789. this.enabled = true; // false -> zero effective weight
  31790. this.clampWhenFinished = false; // keep feeding the last frame?
  31791. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  31792. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  31793. } // State & Scheduling
  31794. play() {
  31795. this._mixer._activateAction(this);
  31796. return this;
  31797. }
  31798. stop() {
  31799. this._mixer._deactivateAction(this);
  31800. return this.reset();
  31801. }
  31802. reset() {
  31803. this.paused = false;
  31804. this.enabled = true;
  31805. this.time = 0; // restart clip
  31806. this._loopCount = -1; // forget previous loops
  31807. this._startTime = null; // forget scheduling
  31808. return this.stopFading().stopWarping();
  31809. }
  31810. isRunning() {
  31811. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  31812. } // return true when play has been called
  31813. isScheduled() {
  31814. return this._mixer._isActiveAction(this);
  31815. }
  31816. startAt(time) {
  31817. this._startTime = time;
  31818. return this;
  31819. }
  31820. setLoop(mode, repetitions) {
  31821. this.loop = mode;
  31822. this.repetitions = repetitions;
  31823. return this;
  31824. } // Weight
  31825. // set the weight stopping any scheduled fading
  31826. // although .enabled = false yields an effective weight of zero, this
  31827. // method does *not* change .enabled, because it would be confusing
  31828. setEffectiveWeight(weight) {
  31829. this.weight = weight; // note: same logic as when updated at runtime
  31830. this._effectiveWeight = this.enabled ? weight : 0;
  31831. return this.stopFading();
  31832. } // return the weight considering fading and .enabled
  31833. getEffectiveWeight() {
  31834. return this._effectiveWeight;
  31835. }
  31836. fadeIn(duration) {
  31837. return this._scheduleFading(duration, 0, 1);
  31838. }
  31839. fadeOut(duration) {
  31840. return this._scheduleFading(duration, 1, 0);
  31841. }
  31842. crossFadeFrom(fadeOutAction, duration, warp) {
  31843. fadeOutAction.fadeOut(duration);
  31844. this.fadeIn(duration);
  31845. if (warp) {
  31846. const fadeInDuration = this._clip.duration,
  31847. fadeOutDuration = fadeOutAction._clip.duration,
  31848. startEndRatio = fadeOutDuration / fadeInDuration,
  31849. endStartRatio = fadeInDuration / fadeOutDuration;
  31850. fadeOutAction.warp(1.0, startEndRatio, duration);
  31851. this.warp(endStartRatio, 1.0, duration);
  31852. }
  31853. return this;
  31854. }
  31855. crossFadeTo(fadeInAction, duration, warp) {
  31856. return fadeInAction.crossFadeFrom(this, duration, warp);
  31857. }
  31858. stopFading() {
  31859. const weightInterpolant = this._weightInterpolant;
  31860. if (weightInterpolant !== null) {
  31861. this._weightInterpolant = null;
  31862. this._mixer._takeBackControlInterpolant(weightInterpolant);
  31863. }
  31864. return this;
  31865. } // Time Scale Control
  31866. // set the time scale stopping any scheduled warping
  31867. // although .paused = true yields an effective time scale of zero, this
  31868. // method does *not* change .paused, because it would be confusing
  31869. setEffectiveTimeScale(timeScale) {
  31870. this.timeScale = timeScale;
  31871. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  31872. return this.stopWarping();
  31873. } // return the time scale considering warping and .paused
  31874. getEffectiveTimeScale() {
  31875. return this._effectiveTimeScale;
  31876. }
  31877. setDuration(duration) {
  31878. this.timeScale = this._clip.duration / duration;
  31879. return this.stopWarping();
  31880. }
  31881. syncWith(action) {
  31882. this.time = action.time;
  31883. this.timeScale = action.timeScale;
  31884. return this.stopWarping();
  31885. }
  31886. halt(duration) {
  31887. return this.warp(this._effectiveTimeScale, 0, duration);
  31888. }
  31889. warp(startTimeScale, endTimeScale, duration) {
  31890. const mixer = this._mixer,
  31891. now = mixer.time,
  31892. timeScale = this.timeScale;
  31893. let interpolant = this._timeScaleInterpolant;
  31894. if (interpolant === null) {
  31895. interpolant = mixer._lendControlInterpolant();
  31896. this._timeScaleInterpolant = interpolant;
  31897. }
  31898. const times = interpolant.parameterPositions,
  31899. values = interpolant.sampleValues;
  31900. times[0] = now;
  31901. times[1] = now + duration;
  31902. values[0] = startTimeScale / timeScale;
  31903. values[1] = endTimeScale / timeScale;
  31904. return this;
  31905. }
  31906. stopWarping() {
  31907. const timeScaleInterpolant = this._timeScaleInterpolant;
  31908. if (timeScaleInterpolant !== null) {
  31909. this._timeScaleInterpolant = null;
  31910. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  31911. }
  31912. return this;
  31913. } // Object Accessors
  31914. getMixer() {
  31915. return this._mixer;
  31916. }
  31917. getClip() {
  31918. return this._clip;
  31919. }
  31920. getRoot() {
  31921. return this._localRoot || this._mixer._root;
  31922. } // Interna
  31923. _update(time, deltaTime, timeDirection, accuIndex) {
  31924. // called by the mixer
  31925. if (!this.enabled) {
  31926. // call ._updateWeight() to update ._effectiveWeight
  31927. this._updateWeight(time);
  31928. return;
  31929. }
  31930. const startTime = this._startTime;
  31931. if (startTime !== null) {
  31932. // check for scheduled start of action
  31933. const timeRunning = (time - startTime) * timeDirection;
  31934. if (timeRunning < 0 || timeDirection === 0) {
  31935. return; // yet to come / don't decide when delta = 0
  31936. } // start
  31937. this._startTime = null; // unschedule
  31938. deltaTime = timeDirection * timeRunning;
  31939. } // apply time scale and advance time
  31940. deltaTime *= this._updateTimeScale(time);
  31941. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  31942. // an effective weight of 0
  31943. const weight = this._updateWeight(time);
  31944. if (weight > 0) {
  31945. const interpolants = this._interpolants;
  31946. const propertyMixers = this._propertyBindings;
  31947. switch (this.blendMode) {
  31948. case AdditiveAnimationBlendMode:
  31949. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  31950. interpolants[j].evaluate(clipTime);
  31951. propertyMixers[j].accumulateAdditive(weight);
  31952. }
  31953. break;
  31954. case NormalAnimationBlendMode:
  31955. default:
  31956. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  31957. interpolants[j].evaluate(clipTime);
  31958. propertyMixers[j].accumulate(accuIndex, weight);
  31959. }
  31960. }
  31961. }
  31962. }
  31963. _updateWeight(time) {
  31964. let weight = 0;
  31965. if (this.enabled) {
  31966. weight = this.weight;
  31967. const interpolant = this._weightInterpolant;
  31968. if (interpolant !== null) {
  31969. const interpolantValue = interpolant.evaluate(time)[0];
  31970. weight *= interpolantValue;
  31971. if (time > interpolant.parameterPositions[1]) {
  31972. this.stopFading();
  31973. if (interpolantValue === 0) {
  31974. // faded out, disable
  31975. this.enabled = false;
  31976. }
  31977. }
  31978. }
  31979. }
  31980. this._effectiveWeight = weight;
  31981. return weight;
  31982. }
  31983. _updateTimeScale(time) {
  31984. let timeScale = 0;
  31985. if (!this.paused) {
  31986. timeScale = this.timeScale;
  31987. const interpolant = this._timeScaleInterpolant;
  31988. if (interpolant !== null) {
  31989. const interpolantValue = interpolant.evaluate(time)[0];
  31990. timeScale *= interpolantValue;
  31991. if (time > interpolant.parameterPositions[1]) {
  31992. this.stopWarping();
  31993. if (timeScale === 0) {
  31994. // motion has halted, pause
  31995. this.paused = true;
  31996. } else {
  31997. // warp done - apply final time scale
  31998. this.timeScale = timeScale;
  31999. }
  32000. }
  32001. }
  32002. }
  32003. this._effectiveTimeScale = timeScale;
  32004. return timeScale;
  32005. }
  32006. _updateTime(deltaTime) {
  32007. const duration = this._clip.duration;
  32008. const loop = this.loop;
  32009. let time = this.time + deltaTime;
  32010. let loopCount = this._loopCount;
  32011. const pingPong = loop === LoopPingPong;
  32012. if (deltaTime === 0) {
  32013. if (loopCount === -1) return time;
  32014. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  32015. }
  32016. if (loop === LoopOnce) {
  32017. if (loopCount === -1) {
  32018. // just started
  32019. this._loopCount = 0;
  32020. this._setEndings(true, true, false);
  32021. }
  32022. handle_stop: {
  32023. if (time >= duration) {
  32024. time = duration;
  32025. } else if (time < 0) {
  32026. time = 0;
  32027. } else {
  32028. this.time = time;
  32029. break handle_stop;
  32030. }
  32031. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32032. this.time = time;
  32033. this._mixer.dispatchEvent({
  32034. type: 'finished',
  32035. action: this,
  32036. direction: deltaTime < 0 ? -1 : 1
  32037. });
  32038. }
  32039. } else {
  32040. // repetitive Repeat or PingPong
  32041. if (loopCount === -1) {
  32042. // just started
  32043. if (deltaTime >= 0) {
  32044. loopCount = 0;
  32045. this._setEndings(true, this.repetitions === 0, pingPong);
  32046. } else {
  32047. // when looping in reverse direction, the initial
  32048. // transition through zero counts as a repetition,
  32049. // so leave loopCount at -1
  32050. this._setEndings(this.repetitions === 0, true, pingPong);
  32051. }
  32052. }
  32053. if (time >= duration || time < 0) {
  32054. // wrap around
  32055. const loopDelta = Math.floor(time / duration); // signed
  32056. time -= duration * loopDelta;
  32057. loopCount += Math.abs(loopDelta);
  32058. const pending = this.repetitions - loopCount;
  32059. if (pending <= 0) {
  32060. // have to stop (switch state, clamp time, fire event)
  32061. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32062. time = deltaTime > 0 ? duration : 0;
  32063. this.time = time;
  32064. this._mixer.dispatchEvent({
  32065. type: 'finished',
  32066. action: this,
  32067. direction: deltaTime > 0 ? 1 : -1
  32068. });
  32069. } else {
  32070. // keep running
  32071. if (pending === 1) {
  32072. // entering the last round
  32073. const atStart = deltaTime < 0;
  32074. this._setEndings(atStart, !atStart, pingPong);
  32075. } else {
  32076. this._setEndings(false, false, pingPong);
  32077. }
  32078. this._loopCount = loopCount;
  32079. this.time = time;
  32080. this._mixer.dispatchEvent({
  32081. type: 'loop',
  32082. action: this,
  32083. loopDelta: loopDelta
  32084. });
  32085. }
  32086. } else {
  32087. this.time = time;
  32088. }
  32089. if (pingPong && (loopCount & 1) === 1) {
  32090. // invert time for the "pong round"
  32091. return duration - time;
  32092. }
  32093. }
  32094. return time;
  32095. }
  32096. _setEndings(atStart, atEnd, pingPong) {
  32097. const settings = this._interpolantSettings;
  32098. if (pingPong) {
  32099. settings.endingStart = ZeroSlopeEnding;
  32100. settings.endingEnd = ZeroSlopeEnding;
  32101. } else {
  32102. // assuming for LoopOnce atStart == atEnd == true
  32103. if (atStart) {
  32104. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32105. } else {
  32106. settings.endingStart = WrapAroundEnding;
  32107. }
  32108. if (atEnd) {
  32109. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32110. } else {
  32111. settings.endingEnd = WrapAroundEnding;
  32112. }
  32113. }
  32114. }
  32115. _scheduleFading(duration, weightNow, weightThen) {
  32116. const mixer = this._mixer,
  32117. now = mixer.time;
  32118. let interpolant = this._weightInterpolant;
  32119. if (interpolant === null) {
  32120. interpolant = mixer._lendControlInterpolant();
  32121. this._weightInterpolant = interpolant;
  32122. }
  32123. const times = interpolant.parameterPositions,
  32124. values = interpolant.sampleValues;
  32125. times[0] = now;
  32126. values[0] = weightNow;
  32127. times[1] = now + duration;
  32128. values[1] = weightThen;
  32129. return this;
  32130. }
  32131. }
  32132. class AnimationMixer extends EventDispatcher {
  32133. constructor(root) {
  32134. super();
  32135. this._root = root;
  32136. this._initMemoryManager();
  32137. this._accuIndex = 0;
  32138. this.time = 0;
  32139. this.timeScale = 1.0;
  32140. }
  32141. _bindAction(action, prototypeAction) {
  32142. const root = action._localRoot || this._root,
  32143. tracks = action._clip.tracks,
  32144. nTracks = tracks.length,
  32145. bindings = action._propertyBindings,
  32146. interpolants = action._interpolants,
  32147. rootUuid = root.uuid,
  32148. bindingsByRoot = this._bindingsByRootAndName;
  32149. let bindingsByName = bindingsByRoot[rootUuid];
  32150. if (bindingsByName === undefined) {
  32151. bindingsByName = {};
  32152. bindingsByRoot[rootUuid] = bindingsByName;
  32153. }
  32154. for (let i = 0; i !== nTracks; ++i) {
  32155. const track = tracks[i],
  32156. trackName = track.name;
  32157. let binding = bindingsByName[trackName];
  32158. if (binding !== undefined) {
  32159. bindings[i] = binding;
  32160. } else {
  32161. binding = bindings[i];
  32162. if (binding !== undefined) {
  32163. // existing binding, make sure the cache knows
  32164. if (binding._cacheIndex === null) {
  32165. ++binding.referenceCount;
  32166. this._addInactiveBinding(binding, rootUuid, trackName);
  32167. }
  32168. continue;
  32169. }
  32170. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  32171. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  32172. ++binding.referenceCount;
  32173. this._addInactiveBinding(binding, rootUuid, trackName);
  32174. bindings[i] = binding;
  32175. }
  32176. interpolants[i].resultBuffer = binding.buffer;
  32177. }
  32178. }
  32179. _activateAction(action) {
  32180. if (!this._isActiveAction(action)) {
  32181. if (action._cacheIndex === null) {
  32182. // this action has been forgotten by the cache, but the user
  32183. // appears to be still using it -> rebind
  32184. const rootUuid = (action._localRoot || this._root).uuid,
  32185. clipUuid = action._clip.uuid,
  32186. actionsForClip = this._actionsByClip[clipUuid];
  32187. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  32188. this._addInactiveAction(action, clipUuid, rootUuid);
  32189. }
  32190. const bindings = action._propertyBindings; // increment reference counts / sort out state
  32191. for (let i = 0, n = bindings.length; i !== n; ++i) {
  32192. const binding = bindings[i];
  32193. if (binding.useCount++ === 0) {
  32194. this._lendBinding(binding);
  32195. binding.saveOriginalState();
  32196. }
  32197. }
  32198. this._lendAction(action);
  32199. }
  32200. }
  32201. _deactivateAction(action) {
  32202. if (this._isActiveAction(action)) {
  32203. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  32204. for (let i = 0, n = bindings.length; i !== n; ++i) {
  32205. const binding = bindings[i];
  32206. if (--binding.useCount === 0) {
  32207. binding.restoreOriginalState();
  32208. this._takeBackBinding(binding);
  32209. }
  32210. }
  32211. this._takeBackAction(action);
  32212. }
  32213. } // Memory manager
  32214. _initMemoryManager() {
  32215. this._actions = []; // 'nActiveActions' followed by inactive ones
  32216. this._nActiveActions = 0;
  32217. this._actionsByClip = {}; // inside:
  32218. // {
  32219. // knownActions: Array< AnimationAction > - used as prototypes
  32220. // actionByRoot: AnimationAction - lookup
  32221. // }
  32222. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  32223. this._nActiveBindings = 0;
  32224. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  32225. this._controlInterpolants = []; // same game as above
  32226. this._nActiveControlInterpolants = 0;
  32227. const scope = this;
  32228. this.stats = {
  32229. actions: {
  32230. get total() {
  32231. return scope._actions.length;
  32232. },
  32233. get inUse() {
  32234. return scope._nActiveActions;
  32235. }
  32236. },
  32237. bindings: {
  32238. get total() {
  32239. return scope._bindings.length;
  32240. },
  32241. get inUse() {
  32242. return scope._nActiveBindings;
  32243. }
  32244. },
  32245. controlInterpolants: {
  32246. get total() {
  32247. return scope._controlInterpolants.length;
  32248. },
  32249. get inUse() {
  32250. return scope._nActiveControlInterpolants;
  32251. }
  32252. }
  32253. };
  32254. } // Memory management for AnimationAction objects
  32255. _isActiveAction(action) {
  32256. const index = action._cacheIndex;
  32257. return index !== null && index < this._nActiveActions;
  32258. }
  32259. _addInactiveAction(action, clipUuid, rootUuid) {
  32260. const actions = this._actions,
  32261. actionsByClip = this._actionsByClip;
  32262. let actionsForClip = actionsByClip[clipUuid];
  32263. if (actionsForClip === undefined) {
  32264. actionsForClip = {
  32265. knownActions: [action],
  32266. actionByRoot: {}
  32267. };
  32268. action._byClipCacheIndex = 0;
  32269. actionsByClip[clipUuid] = actionsForClip;
  32270. } else {
  32271. const knownActions = actionsForClip.knownActions;
  32272. action._byClipCacheIndex = knownActions.length;
  32273. knownActions.push(action);
  32274. }
  32275. action._cacheIndex = actions.length;
  32276. actions.push(action);
  32277. actionsForClip.actionByRoot[rootUuid] = action;
  32278. }
  32279. _removeInactiveAction(action) {
  32280. const actions = this._actions,
  32281. lastInactiveAction = actions[actions.length - 1],
  32282. cacheIndex = action._cacheIndex;
  32283. lastInactiveAction._cacheIndex = cacheIndex;
  32284. actions[cacheIndex] = lastInactiveAction;
  32285. actions.pop();
  32286. action._cacheIndex = null;
  32287. const clipUuid = action._clip.uuid,
  32288. actionsByClip = this._actionsByClip,
  32289. actionsForClip = actionsByClip[clipUuid],
  32290. knownActionsForClip = actionsForClip.knownActions,
  32291. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  32292. byClipCacheIndex = action._byClipCacheIndex;
  32293. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  32294. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  32295. knownActionsForClip.pop();
  32296. action._byClipCacheIndex = null;
  32297. const actionByRoot = actionsForClip.actionByRoot,
  32298. rootUuid = (action._localRoot || this._root).uuid;
  32299. delete actionByRoot[rootUuid];
  32300. if (knownActionsForClip.length === 0) {
  32301. delete actionsByClip[clipUuid];
  32302. }
  32303. this._removeInactiveBindingsForAction(action);
  32304. }
  32305. _removeInactiveBindingsForAction(action) {
  32306. const bindings = action._propertyBindings;
  32307. for (let i = 0, n = bindings.length; i !== n; ++i) {
  32308. const binding = bindings[i];
  32309. if (--binding.referenceCount === 0) {
  32310. this._removeInactiveBinding(binding);
  32311. }
  32312. }
  32313. }
  32314. _lendAction(action) {
  32315. // [ active actions | inactive actions ]
  32316. // [ active actions >| inactive actions ]
  32317. // s a
  32318. // <-swap->
  32319. // a s
  32320. const actions = this._actions,
  32321. prevIndex = action._cacheIndex,
  32322. lastActiveIndex = this._nActiveActions++,
  32323. firstInactiveAction = actions[lastActiveIndex];
  32324. action._cacheIndex = lastActiveIndex;
  32325. actions[lastActiveIndex] = action;
  32326. firstInactiveAction._cacheIndex = prevIndex;
  32327. actions[prevIndex] = firstInactiveAction;
  32328. }
  32329. _takeBackAction(action) {
  32330. // [ active actions | inactive actions ]
  32331. // [ active actions |< inactive actions ]
  32332. // a s
  32333. // <-swap->
  32334. // s a
  32335. const actions = this._actions,
  32336. prevIndex = action._cacheIndex,
  32337. firstInactiveIndex = --this._nActiveActions,
  32338. lastActiveAction = actions[firstInactiveIndex];
  32339. action._cacheIndex = firstInactiveIndex;
  32340. actions[firstInactiveIndex] = action;
  32341. lastActiveAction._cacheIndex = prevIndex;
  32342. actions[prevIndex] = lastActiveAction;
  32343. } // Memory management for PropertyMixer objects
  32344. _addInactiveBinding(binding, rootUuid, trackName) {
  32345. const bindingsByRoot = this._bindingsByRootAndName,
  32346. bindings = this._bindings;
  32347. let bindingByName = bindingsByRoot[rootUuid];
  32348. if (bindingByName === undefined) {
  32349. bindingByName = {};
  32350. bindingsByRoot[rootUuid] = bindingByName;
  32351. }
  32352. bindingByName[trackName] = binding;
  32353. binding._cacheIndex = bindings.length;
  32354. bindings.push(binding);
  32355. }
  32356. _removeInactiveBinding(binding) {
  32357. const bindings = this._bindings,
  32358. propBinding = binding.binding,
  32359. rootUuid = propBinding.rootNode.uuid,
  32360. trackName = propBinding.path,
  32361. bindingsByRoot = this._bindingsByRootAndName,
  32362. bindingByName = bindingsByRoot[rootUuid],
  32363. lastInactiveBinding = bindings[bindings.length - 1],
  32364. cacheIndex = binding._cacheIndex;
  32365. lastInactiveBinding._cacheIndex = cacheIndex;
  32366. bindings[cacheIndex] = lastInactiveBinding;
  32367. bindings.pop();
  32368. delete bindingByName[trackName];
  32369. if (Object.keys(bindingByName).length === 0) {
  32370. delete bindingsByRoot[rootUuid];
  32371. }
  32372. }
  32373. _lendBinding(binding) {
  32374. const bindings = this._bindings,
  32375. prevIndex = binding._cacheIndex,
  32376. lastActiveIndex = this._nActiveBindings++,
  32377. firstInactiveBinding = bindings[lastActiveIndex];
  32378. binding._cacheIndex = lastActiveIndex;
  32379. bindings[lastActiveIndex] = binding;
  32380. firstInactiveBinding._cacheIndex = prevIndex;
  32381. bindings[prevIndex] = firstInactiveBinding;
  32382. }
  32383. _takeBackBinding(binding) {
  32384. const bindings = this._bindings,
  32385. prevIndex = binding._cacheIndex,
  32386. firstInactiveIndex = --this._nActiveBindings,
  32387. lastActiveBinding = bindings[firstInactiveIndex];
  32388. binding._cacheIndex = firstInactiveIndex;
  32389. bindings[firstInactiveIndex] = binding;
  32390. lastActiveBinding._cacheIndex = prevIndex;
  32391. bindings[prevIndex] = lastActiveBinding;
  32392. } // Memory management of Interpolants for weight and time scale
  32393. _lendControlInterpolant() {
  32394. const interpolants = this._controlInterpolants,
  32395. lastActiveIndex = this._nActiveControlInterpolants++;
  32396. let interpolant = interpolants[lastActiveIndex];
  32397. if (interpolant === undefined) {
  32398. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  32399. interpolant.__cacheIndex = lastActiveIndex;
  32400. interpolants[lastActiveIndex] = interpolant;
  32401. }
  32402. return interpolant;
  32403. }
  32404. _takeBackControlInterpolant(interpolant) {
  32405. const interpolants = this._controlInterpolants,
  32406. prevIndex = interpolant.__cacheIndex,
  32407. firstInactiveIndex = --this._nActiveControlInterpolants,
  32408. lastActiveInterpolant = interpolants[firstInactiveIndex];
  32409. interpolant.__cacheIndex = firstInactiveIndex;
  32410. interpolants[firstInactiveIndex] = interpolant;
  32411. lastActiveInterpolant.__cacheIndex = prevIndex;
  32412. interpolants[prevIndex] = lastActiveInterpolant;
  32413. } // return an action for a clip optionally using a custom root target
  32414. // object (this method allocates a lot of dynamic memory in case a
  32415. // previously unknown clip/root combination is specified)
  32416. clipAction(clip, optionalRoot, blendMode) {
  32417. const root = optionalRoot || this._root,
  32418. rootUuid = root.uuid;
  32419. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  32420. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  32421. const actionsForClip = this._actionsByClip[clipUuid];
  32422. let prototypeAction = null;
  32423. if (blendMode === undefined) {
  32424. if (clipObject !== null) {
  32425. blendMode = clipObject.blendMode;
  32426. } else {
  32427. blendMode = NormalAnimationBlendMode;
  32428. }
  32429. }
  32430. if (actionsForClip !== undefined) {
  32431. const existingAction = actionsForClip.actionByRoot[rootUuid];
  32432. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  32433. return existingAction;
  32434. } // we know the clip, so we don't have to parse all
  32435. // the bindings again but can just copy
  32436. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  32437. if (clipObject === null) clipObject = prototypeAction._clip;
  32438. } // clip must be known when specified via string
  32439. if (clipObject === null) return null; // allocate all resources required to run it
  32440. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  32441. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  32442. this._addInactiveAction(newAction, clipUuid, rootUuid);
  32443. return newAction;
  32444. } // get an existing action
  32445. existingAction(clip, optionalRoot) {
  32446. const root = optionalRoot || this._root,
  32447. rootUuid = root.uuid,
  32448. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  32449. clipUuid = clipObject ? clipObject.uuid : clip,
  32450. actionsForClip = this._actionsByClip[clipUuid];
  32451. if (actionsForClip !== undefined) {
  32452. return actionsForClip.actionByRoot[rootUuid] || null;
  32453. }
  32454. return null;
  32455. } // deactivates all previously scheduled actions
  32456. stopAllAction() {
  32457. const actions = this._actions,
  32458. nActions = this._nActiveActions;
  32459. for (let i = nActions - 1; i >= 0; --i) {
  32460. actions[i].stop();
  32461. }
  32462. return this;
  32463. } // advance the time and update apply the animation
  32464. update(deltaTime) {
  32465. deltaTime *= this.timeScale;
  32466. const actions = this._actions,
  32467. nActions = this._nActiveActions,
  32468. time = this.time += deltaTime,
  32469. timeDirection = Math.sign(deltaTime),
  32470. accuIndex = this._accuIndex ^= 1; // run active actions
  32471. for (let i = 0; i !== nActions; ++i) {
  32472. const action = actions[i];
  32473. action._update(time, deltaTime, timeDirection, accuIndex);
  32474. } // update scene graph
  32475. const bindings = this._bindings,
  32476. nBindings = this._nActiveBindings;
  32477. for (let i = 0; i !== nBindings; ++i) {
  32478. bindings[i].apply(accuIndex);
  32479. }
  32480. return this;
  32481. } // Allows you to seek to a specific time in an animation.
  32482. setTime(timeInSeconds) {
  32483. this.time = 0; // Zero out time attribute for AnimationMixer object;
  32484. for (let i = 0; i < this._actions.length; i++) {
  32485. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  32486. }
  32487. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  32488. } // return this mixer's root target object
  32489. getRoot() {
  32490. return this._root;
  32491. } // free all resources specific to a particular clip
  32492. uncacheClip(clip) {
  32493. const actions = this._actions,
  32494. clipUuid = clip.uuid,
  32495. actionsByClip = this._actionsByClip,
  32496. actionsForClip = actionsByClip[clipUuid];
  32497. if (actionsForClip !== undefined) {
  32498. // note: just calling _removeInactiveAction would mess up the
  32499. // iteration state and also require updating the state we can
  32500. // just throw away
  32501. const actionsToRemove = actionsForClip.knownActions;
  32502. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  32503. const action = actionsToRemove[i];
  32504. this._deactivateAction(action);
  32505. const cacheIndex = action._cacheIndex,
  32506. lastInactiveAction = actions[actions.length - 1];
  32507. action._cacheIndex = null;
  32508. action._byClipCacheIndex = null;
  32509. lastInactiveAction._cacheIndex = cacheIndex;
  32510. actions[cacheIndex] = lastInactiveAction;
  32511. actions.pop();
  32512. this._removeInactiveBindingsForAction(action);
  32513. }
  32514. delete actionsByClip[clipUuid];
  32515. }
  32516. } // free all resources specific to a particular root target object
  32517. uncacheRoot(root) {
  32518. const rootUuid = root.uuid,
  32519. actionsByClip = this._actionsByClip;
  32520. for (const clipUuid in actionsByClip) {
  32521. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  32522. action = actionByRoot[rootUuid];
  32523. if (action !== undefined) {
  32524. this._deactivateAction(action);
  32525. this._removeInactiveAction(action);
  32526. }
  32527. }
  32528. const bindingsByRoot = this._bindingsByRootAndName,
  32529. bindingByName = bindingsByRoot[rootUuid];
  32530. if (bindingByName !== undefined) {
  32531. for (const trackName in bindingByName) {
  32532. const binding = bindingByName[trackName];
  32533. binding.restoreOriginalState();
  32534. this._removeInactiveBinding(binding);
  32535. }
  32536. }
  32537. } // remove a targeted clip from the cache
  32538. uncacheAction(clip, optionalRoot) {
  32539. const action = this.existingAction(clip, optionalRoot);
  32540. if (action !== null) {
  32541. this._deactivateAction(action);
  32542. this._removeInactiveAction(action);
  32543. }
  32544. }
  32545. }
  32546. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  32547. class Uniform {
  32548. constructor(value) {
  32549. if (typeof value === 'string') {
  32550. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  32551. value = arguments[1];
  32552. }
  32553. this.value = value;
  32554. }
  32555. clone() {
  32556. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  32557. }
  32558. }
  32559. class InstancedInterleavedBuffer extends InterleavedBuffer {
  32560. constructor(array, stride, meshPerAttribute = 1) {
  32561. super(array, stride);
  32562. this.meshPerAttribute = meshPerAttribute;
  32563. }
  32564. copy(source) {
  32565. super.copy(source);
  32566. this.meshPerAttribute = source.meshPerAttribute;
  32567. return this;
  32568. }
  32569. clone(data) {
  32570. const ib = super.clone(data);
  32571. ib.meshPerAttribute = this.meshPerAttribute;
  32572. return ib;
  32573. }
  32574. toJSON(data) {
  32575. const json = super.toJSON(data);
  32576. json.isInstancedInterleavedBuffer = true;
  32577. json.meshPerAttribute = this.meshPerAttribute;
  32578. return json;
  32579. }
  32580. }
  32581. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  32582. class GLBufferAttribute {
  32583. constructor(buffer, type, itemSize, elementSize, count) {
  32584. this.buffer = buffer;
  32585. this.type = type;
  32586. this.itemSize = itemSize;
  32587. this.elementSize = elementSize;
  32588. this.count = count;
  32589. this.version = 0;
  32590. }
  32591. set needsUpdate(value) {
  32592. if (value === true) this.version++;
  32593. }
  32594. setBuffer(buffer) {
  32595. this.buffer = buffer;
  32596. return this;
  32597. }
  32598. setType(type, elementSize) {
  32599. this.type = type;
  32600. this.elementSize = elementSize;
  32601. return this;
  32602. }
  32603. setItemSize(itemSize) {
  32604. this.itemSize = itemSize;
  32605. return this;
  32606. }
  32607. setCount(count) {
  32608. this.count = count;
  32609. return this;
  32610. }
  32611. }
  32612. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  32613. class Raycaster {
  32614. constructor(origin, direction, near = 0, far = Infinity) {
  32615. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  32616. this.near = near;
  32617. this.far = far;
  32618. this.camera = null;
  32619. this.layers = new Layers();
  32620. this.params = {
  32621. Mesh: {},
  32622. Line: {
  32623. threshold: 1
  32624. },
  32625. LOD: {},
  32626. Points: {
  32627. threshold: 1
  32628. },
  32629. Sprite: {}
  32630. };
  32631. }
  32632. set(origin, direction) {
  32633. // direction is assumed to be normalized (for accurate distance calculations)
  32634. this.ray.set(origin, direction);
  32635. }
  32636. setFromCamera(coords, camera) {
  32637. if (camera && camera.isPerspectiveCamera) {
  32638. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  32639. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  32640. this.camera = camera;
  32641. } else if (camera && camera.isOrthographicCamera) {
  32642. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  32643. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  32644. this.camera = camera;
  32645. } else {
  32646. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  32647. }
  32648. }
  32649. intersectObject(object, recursive = true, intersects = []) {
  32650. intersectObject(object, this, intersects, recursive);
  32651. intersects.sort(ascSort);
  32652. return intersects;
  32653. }
  32654. intersectObjects(objects, recursive = true, intersects = []) {
  32655. for (let i = 0, l = objects.length; i < l; i++) {
  32656. intersectObject(objects[i], this, intersects, recursive);
  32657. }
  32658. intersects.sort(ascSort);
  32659. return intersects;
  32660. }
  32661. }
  32662. function ascSort(a, b) {
  32663. return a.distance - b.distance;
  32664. }
  32665. function intersectObject(object, raycaster, intersects, recursive) {
  32666. if (object.layers.test(raycaster.layers)) {
  32667. object.raycast(raycaster, intersects);
  32668. }
  32669. if (recursive === true) {
  32670. const children = object.children;
  32671. for (let i = 0, l = children.length; i < l; i++) {
  32672. intersectObject(children[i], raycaster, intersects, true);
  32673. }
  32674. }
  32675. }
  32676. /**
  32677. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  32678. *
  32679. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  32680. * The azimuthal angle (theta) is measured from the positive z-axis.
  32681. */
  32682. class Spherical {
  32683. constructor(radius = 1, phi = 0, theta = 0) {
  32684. this.radius = radius;
  32685. this.phi = phi; // polar angle
  32686. this.theta = theta; // azimuthal angle
  32687. return this;
  32688. }
  32689. set(radius, phi, theta) {
  32690. this.radius = radius;
  32691. this.phi = phi;
  32692. this.theta = theta;
  32693. return this;
  32694. }
  32695. copy(other) {
  32696. this.radius = other.radius;
  32697. this.phi = other.phi;
  32698. this.theta = other.theta;
  32699. return this;
  32700. } // restrict phi to be betwee EPS and PI-EPS
  32701. makeSafe() {
  32702. const EPS = 0.000001;
  32703. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  32704. return this;
  32705. }
  32706. setFromVector3(v) {
  32707. return this.setFromCartesianCoords(v.x, v.y, v.z);
  32708. }
  32709. setFromCartesianCoords(x, y, z) {
  32710. this.radius = Math.sqrt(x * x + y * y + z * z);
  32711. if (this.radius === 0) {
  32712. this.theta = 0;
  32713. this.phi = 0;
  32714. } else {
  32715. this.theta = Math.atan2(x, z);
  32716. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  32717. }
  32718. return this;
  32719. }
  32720. clone() {
  32721. return new this.constructor().copy(this);
  32722. }
  32723. }
  32724. /**
  32725. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  32726. */
  32727. class Cylindrical {
  32728. constructor(radius = 1, theta = 0, y = 0) {
  32729. this.radius = radius; // distance from the origin to a point in the x-z plane
  32730. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  32731. this.y = y; // height above the x-z plane
  32732. return this;
  32733. }
  32734. set(radius, theta, y) {
  32735. this.radius = radius;
  32736. this.theta = theta;
  32737. this.y = y;
  32738. return this;
  32739. }
  32740. copy(other) {
  32741. this.radius = other.radius;
  32742. this.theta = other.theta;
  32743. this.y = other.y;
  32744. return this;
  32745. }
  32746. setFromVector3(v) {
  32747. return this.setFromCartesianCoords(v.x, v.y, v.z);
  32748. }
  32749. setFromCartesianCoords(x, y, z) {
  32750. this.radius = Math.sqrt(x * x + z * z);
  32751. this.theta = Math.atan2(x, z);
  32752. this.y = y;
  32753. return this;
  32754. }
  32755. clone() {
  32756. return new this.constructor().copy(this);
  32757. }
  32758. }
  32759. const _vector$4 = /*@__PURE__*/new Vector2();
  32760. class Box2 {
  32761. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  32762. this.min = min;
  32763. this.max = max;
  32764. }
  32765. set(min, max) {
  32766. this.min.copy(min);
  32767. this.max.copy(max);
  32768. return this;
  32769. }
  32770. setFromPoints(points) {
  32771. this.makeEmpty();
  32772. for (let i = 0, il = points.length; i < il; i++) {
  32773. this.expandByPoint(points[i]);
  32774. }
  32775. return this;
  32776. }
  32777. setFromCenterAndSize(center, size) {
  32778. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  32779. this.min.copy(center).sub(halfSize);
  32780. this.max.copy(center).add(halfSize);
  32781. return this;
  32782. }
  32783. clone() {
  32784. return new this.constructor().copy(this);
  32785. }
  32786. copy(box) {
  32787. this.min.copy(box.min);
  32788. this.max.copy(box.max);
  32789. return this;
  32790. }
  32791. makeEmpty() {
  32792. this.min.x = this.min.y = +Infinity;
  32793. this.max.x = this.max.y = -Infinity;
  32794. return this;
  32795. }
  32796. isEmpty() {
  32797. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  32798. return this.max.x < this.min.x || this.max.y < this.min.y;
  32799. }
  32800. getCenter(target) {
  32801. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  32802. }
  32803. getSize(target) {
  32804. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  32805. }
  32806. expandByPoint(point) {
  32807. this.min.min(point);
  32808. this.max.max(point);
  32809. return this;
  32810. }
  32811. expandByVector(vector) {
  32812. this.min.sub(vector);
  32813. this.max.add(vector);
  32814. return this;
  32815. }
  32816. expandByScalar(scalar) {
  32817. this.min.addScalar(-scalar);
  32818. this.max.addScalar(scalar);
  32819. return this;
  32820. }
  32821. containsPoint(point) {
  32822. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  32823. }
  32824. containsBox(box) {
  32825. 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;
  32826. }
  32827. getParameter(point, target) {
  32828. // This can potentially have a divide by zero if the box
  32829. // has a size dimension of 0.
  32830. 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));
  32831. }
  32832. intersectsBox(box) {
  32833. // using 4 splitting planes to rule out intersections
  32834. 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;
  32835. }
  32836. clampPoint(point, target) {
  32837. return target.copy(point).clamp(this.min, this.max);
  32838. }
  32839. distanceToPoint(point) {
  32840. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  32841. return clampedPoint.sub(point).length();
  32842. }
  32843. intersect(box) {
  32844. this.min.max(box.min);
  32845. this.max.min(box.max);
  32846. return this;
  32847. }
  32848. union(box) {
  32849. this.min.min(box.min);
  32850. this.max.max(box.max);
  32851. return this;
  32852. }
  32853. translate(offset) {
  32854. this.min.add(offset);
  32855. this.max.add(offset);
  32856. return this;
  32857. }
  32858. equals(box) {
  32859. return box.min.equals(this.min) && box.max.equals(this.max);
  32860. }
  32861. }
  32862. Box2.prototype.isBox2 = true;
  32863. const _startP = /*@__PURE__*/new Vector3();
  32864. const _startEnd = /*@__PURE__*/new Vector3();
  32865. class Line3 {
  32866. constructor(start = new Vector3(), end = new Vector3()) {
  32867. this.start = start;
  32868. this.end = end;
  32869. }
  32870. set(start, end) {
  32871. this.start.copy(start);
  32872. this.end.copy(end);
  32873. return this;
  32874. }
  32875. copy(line) {
  32876. this.start.copy(line.start);
  32877. this.end.copy(line.end);
  32878. return this;
  32879. }
  32880. getCenter(target) {
  32881. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  32882. }
  32883. delta(target) {
  32884. return target.subVectors(this.end, this.start);
  32885. }
  32886. distanceSq() {
  32887. return this.start.distanceToSquared(this.end);
  32888. }
  32889. distance() {
  32890. return this.start.distanceTo(this.end);
  32891. }
  32892. at(t, target) {
  32893. return this.delta(target).multiplyScalar(t).add(this.start);
  32894. }
  32895. closestPointToPointParameter(point, clampToLine) {
  32896. _startP.subVectors(point, this.start);
  32897. _startEnd.subVectors(this.end, this.start);
  32898. const startEnd2 = _startEnd.dot(_startEnd);
  32899. const startEnd_startP = _startEnd.dot(_startP);
  32900. let t = startEnd_startP / startEnd2;
  32901. if (clampToLine) {
  32902. t = clamp(t, 0, 1);
  32903. }
  32904. return t;
  32905. }
  32906. closestPointToPoint(point, clampToLine, target) {
  32907. const t = this.closestPointToPointParameter(point, clampToLine);
  32908. return this.delta(target).multiplyScalar(t).add(this.start);
  32909. }
  32910. applyMatrix4(matrix) {
  32911. this.start.applyMatrix4(matrix);
  32912. this.end.applyMatrix4(matrix);
  32913. return this;
  32914. }
  32915. equals(line) {
  32916. return line.start.equals(this.start) && line.end.equals(this.end);
  32917. }
  32918. clone() {
  32919. return new this.constructor().copy(this);
  32920. }
  32921. }
  32922. class ImmediateRenderObject extends Object3D {
  32923. constructor(material) {
  32924. super();
  32925. this.material = material;
  32926. this.render = function () {};
  32927. this.hasPositions = false;
  32928. this.hasNormals = false;
  32929. this.hasColors = false;
  32930. this.hasUvs = false;
  32931. this.positionArray = null;
  32932. this.normalArray = null;
  32933. this.colorArray = null;
  32934. this.uvArray = null;
  32935. this.count = 0;
  32936. }
  32937. }
  32938. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  32939. const _vector$3 = /*@__PURE__*/new Vector3();
  32940. class SpotLightHelper extends Object3D {
  32941. constructor(light, color) {
  32942. super();
  32943. this.light = light;
  32944. this.light.updateMatrixWorld();
  32945. this.matrix = light.matrixWorld;
  32946. this.matrixAutoUpdate = false;
  32947. this.color = color;
  32948. const geometry = new BufferGeometry();
  32949. const 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];
  32950. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  32951. const p1 = i / l * Math.PI * 2;
  32952. const p2 = j / l * Math.PI * 2;
  32953. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  32954. }
  32955. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  32956. const material = new LineBasicMaterial({
  32957. fog: false,
  32958. toneMapped: false
  32959. });
  32960. this.cone = new LineSegments(geometry, material);
  32961. this.add(this.cone);
  32962. this.update();
  32963. }
  32964. dispose() {
  32965. this.cone.geometry.dispose();
  32966. this.cone.material.dispose();
  32967. }
  32968. update() {
  32969. this.light.updateMatrixWorld();
  32970. const coneLength = this.light.distance ? this.light.distance : 1000;
  32971. const coneWidth = coneLength * Math.tan(this.light.angle);
  32972. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  32973. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  32974. this.cone.lookAt(_vector$3);
  32975. if (this.color !== undefined) {
  32976. this.cone.material.color.set(this.color);
  32977. } else {
  32978. this.cone.material.color.copy(this.light.color);
  32979. }
  32980. }
  32981. }
  32982. const _vector$2 = /*@__PURE__*/new Vector3();
  32983. const _boneMatrix = /*@__PURE__*/new Matrix4();
  32984. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  32985. class SkeletonHelper extends LineSegments {
  32986. constructor(object) {
  32987. const bones = getBoneList(object);
  32988. const geometry = new BufferGeometry();
  32989. const vertices = [];
  32990. const colors = [];
  32991. const color1 = new Color(0, 0, 1);
  32992. const color2 = new Color(0, 1, 0);
  32993. for (let i = 0; i < bones.length; i++) {
  32994. const bone = bones[i];
  32995. if (bone.parent && bone.parent.isBone) {
  32996. vertices.push(0, 0, 0);
  32997. vertices.push(0, 0, 0);
  32998. colors.push(color1.r, color1.g, color1.b);
  32999. colors.push(color2.r, color2.g, color2.b);
  33000. }
  33001. }
  33002. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33003. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33004. const material = new LineBasicMaterial({
  33005. vertexColors: true,
  33006. depthTest: false,
  33007. depthWrite: false,
  33008. toneMapped: false,
  33009. transparent: true
  33010. });
  33011. super(geometry, material);
  33012. this.type = 'SkeletonHelper';
  33013. this.isSkeletonHelper = true;
  33014. this.root = object;
  33015. this.bones = bones;
  33016. this.matrix = object.matrixWorld;
  33017. this.matrixAutoUpdate = false;
  33018. }
  33019. updateMatrixWorld(force) {
  33020. const bones = this.bones;
  33021. const geometry = this.geometry;
  33022. const position = geometry.getAttribute('position');
  33023. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  33024. for (let i = 0, j = 0; i < bones.length; i++) {
  33025. const bone = bones[i];
  33026. if (bone.parent && bone.parent.isBone) {
  33027. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  33028. _vector$2.setFromMatrixPosition(_boneMatrix);
  33029. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  33030. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  33031. _vector$2.setFromMatrixPosition(_boneMatrix);
  33032. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  33033. j += 2;
  33034. }
  33035. }
  33036. geometry.getAttribute('position').needsUpdate = true;
  33037. super.updateMatrixWorld(force);
  33038. }
  33039. }
  33040. function getBoneList(object) {
  33041. const boneList = [];
  33042. if (object && object.isBone) {
  33043. boneList.push(object);
  33044. }
  33045. for (let i = 0; i < object.children.length; i++) {
  33046. boneList.push.apply(boneList, getBoneList(object.children[i]));
  33047. }
  33048. return boneList;
  33049. }
  33050. class PointLightHelper extends Mesh {
  33051. constructor(light, sphereSize, color) {
  33052. const geometry = new SphereGeometry(sphereSize, 4, 2);
  33053. const material = new MeshBasicMaterial({
  33054. wireframe: true,
  33055. fog: false,
  33056. toneMapped: false
  33057. });
  33058. super(geometry, material);
  33059. this.light = light;
  33060. this.light.updateMatrixWorld();
  33061. this.color = color;
  33062. this.type = 'PointLightHelper';
  33063. this.matrix = this.light.matrixWorld;
  33064. this.matrixAutoUpdate = false;
  33065. this.update();
  33066. /*
  33067. // TODO: delete this comment?
  33068. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  33069. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  33070. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  33071. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  33072. const d = light.distance;
  33073. if ( d === 0.0 ) {
  33074. this.lightDistance.visible = false;
  33075. } else {
  33076. this.lightDistance.scale.set( d, d, d );
  33077. }
  33078. this.add( this.lightDistance );
  33079. */
  33080. }
  33081. dispose() {
  33082. this.geometry.dispose();
  33083. this.material.dispose();
  33084. }
  33085. update() {
  33086. if (this.color !== undefined) {
  33087. this.material.color.set(this.color);
  33088. } else {
  33089. this.material.color.copy(this.light.color);
  33090. }
  33091. /*
  33092. const d = this.light.distance;
  33093. if ( d === 0.0 ) {
  33094. this.lightDistance.visible = false;
  33095. } else {
  33096. this.lightDistance.visible = true;
  33097. this.lightDistance.scale.set( d, d, d );
  33098. }
  33099. */
  33100. }
  33101. }
  33102. const _vector$1 = /*@__PURE__*/new Vector3();
  33103. const _color1 = /*@__PURE__*/new Color();
  33104. const _color2 = /*@__PURE__*/new Color();
  33105. class HemisphereLightHelper extends Object3D {
  33106. constructor(light, size, color) {
  33107. super();
  33108. this.light = light;
  33109. this.light.updateMatrixWorld();
  33110. this.matrix = light.matrixWorld;
  33111. this.matrixAutoUpdate = false;
  33112. this.color = color;
  33113. const geometry = new OctahedronGeometry(size);
  33114. geometry.rotateY(Math.PI * 0.5);
  33115. this.material = new MeshBasicMaterial({
  33116. wireframe: true,
  33117. fog: false,
  33118. toneMapped: false
  33119. });
  33120. if (this.color === undefined) this.material.vertexColors = true;
  33121. const position = geometry.getAttribute('position');
  33122. const colors = new Float32Array(position.count * 3);
  33123. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  33124. this.add(new Mesh(geometry, this.material));
  33125. this.update();
  33126. }
  33127. dispose() {
  33128. this.children[0].geometry.dispose();
  33129. this.children[0].material.dispose();
  33130. }
  33131. update() {
  33132. const mesh = this.children[0];
  33133. if (this.color !== undefined) {
  33134. this.material.color.set(this.color);
  33135. } else {
  33136. const colors = mesh.geometry.getAttribute('color');
  33137. _color1.copy(this.light.color);
  33138. _color2.copy(this.light.groundColor);
  33139. for (let i = 0, l = colors.count; i < l; i++) {
  33140. const color = i < l / 2 ? _color1 : _color2;
  33141. colors.setXYZ(i, color.r, color.g, color.b);
  33142. }
  33143. colors.needsUpdate = true;
  33144. }
  33145. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  33146. }
  33147. }
  33148. class GridHelper extends LineSegments {
  33149. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  33150. color1 = new Color(color1);
  33151. color2 = new Color(color2);
  33152. const center = divisions / 2;
  33153. const step = size / divisions;
  33154. const halfSize = size / 2;
  33155. const vertices = [],
  33156. colors = [];
  33157. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  33158. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  33159. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  33160. const color = i === center ? color1 : color2;
  33161. color.toArray(colors, j);
  33162. j += 3;
  33163. color.toArray(colors, j);
  33164. j += 3;
  33165. color.toArray(colors, j);
  33166. j += 3;
  33167. color.toArray(colors, j);
  33168. j += 3;
  33169. }
  33170. const geometry = new BufferGeometry();
  33171. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33172. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33173. const material = new LineBasicMaterial({
  33174. vertexColors: true,
  33175. toneMapped: false
  33176. });
  33177. super(geometry, material);
  33178. this.type = 'GridHelper';
  33179. }
  33180. }
  33181. class PolarGridHelper extends LineSegments {
  33182. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  33183. color1 = new Color(color1);
  33184. color2 = new Color(color2);
  33185. const vertices = [];
  33186. const colors = []; // create the radials
  33187. for (let i = 0; i <= radials; i++) {
  33188. const v = i / radials * (Math.PI * 2);
  33189. const x = Math.sin(v) * radius;
  33190. const z = Math.cos(v) * radius;
  33191. vertices.push(0, 0, 0);
  33192. vertices.push(x, 0, z);
  33193. const color = i & 1 ? color1 : color2;
  33194. colors.push(color.r, color.g, color.b);
  33195. colors.push(color.r, color.g, color.b);
  33196. } // create the circles
  33197. for (let i = 0; i <= circles; i++) {
  33198. const color = i & 1 ? color1 : color2;
  33199. const r = radius - radius / circles * i;
  33200. for (let j = 0; j < divisions; j++) {
  33201. // first vertex
  33202. let v = j / divisions * (Math.PI * 2);
  33203. let x = Math.sin(v) * r;
  33204. let z = Math.cos(v) * r;
  33205. vertices.push(x, 0, z);
  33206. colors.push(color.r, color.g, color.b); // second vertex
  33207. v = (j + 1) / divisions * (Math.PI * 2);
  33208. x = Math.sin(v) * r;
  33209. z = Math.cos(v) * r;
  33210. vertices.push(x, 0, z);
  33211. colors.push(color.r, color.g, color.b);
  33212. }
  33213. }
  33214. const geometry = new BufferGeometry();
  33215. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33216. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33217. const material = new LineBasicMaterial({
  33218. vertexColors: true,
  33219. toneMapped: false
  33220. });
  33221. super(geometry, material);
  33222. this.type = 'PolarGridHelper';
  33223. }
  33224. }
  33225. const _v1 = /*@__PURE__*/new Vector3();
  33226. const _v2 = /*@__PURE__*/new Vector3();
  33227. const _v3 = /*@__PURE__*/new Vector3();
  33228. class DirectionalLightHelper extends Object3D {
  33229. constructor(light, size, color) {
  33230. super();
  33231. this.light = light;
  33232. this.light.updateMatrixWorld();
  33233. this.matrix = light.matrixWorld;
  33234. this.matrixAutoUpdate = false;
  33235. this.color = color;
  33236. if (size === undefined) size = 1;
  33237. let geometry = new BufferGeometry();
  33238. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  33239. const material = new LineBasicMaterial({
  33240. fog: false,
  33241. toneMapped: false
  33242. });
  33243. this.lightPlane = new Line(geometry, material);
  33244. this.add(this.lightPlane);
  33245. geometry = new BufferGeometry();
  33246. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  33247. this.targetLine = new Line(geometry, material);
  33248. this.add(this.targetLine);
  33249. this.update();
  33250. }
  33251. dispose() {
  33252. this.lightPlane.geometry.dispose();
  33253. this.lightPlane.material.dispose();
  33254. this.targetLine.geometry.dispose();
  33255. this.targetLine.material.dispose();
  33256. }
  33257. update() {
  33258. _v1.setFromMatrixPosition(this.light.matrixWorld);
  33259. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  33260. _v3.subVectors(_v2, _v1);
  33261. this.lightPlane.lookAt(_v2);
  33262. if (this.color !== undefined) {
  33263. this.lightPlane.material.color.set(this.color);
  33264. this.targetLine.material.color.set(this.color);
  33265. } else {
  33266. this.lightPlane.material.color.copy(this.light.color);
  33267. this.targetLine.material.color.copy(this.light.color);
  33268. }
  33269. this.targetLine.lookAt(_v2);
  33270. this.targetLine.scale.z = _v3.length();
  33271. }
  33272. }
  33273. const _vector = /*@__PURE__*/new Vector3();
  33274. const _camera = /*@__PURE__*/new Camera();
  33275. /**
  33276. * - shows frustum, line of sight and up of the camera
  33277. * - suitable for fast updates
  33278. * - based on frustum visualization in lightgl.js shadowmap example
  33279. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33280. */
  33281. class CameraHelper extends LineSegments {
  33282. constructor(camera) {
  33283. const geometry = new BufferGeometry();
  33284. const material = new LineBasicMaterial({
  33285. color: 0xffffff,
  33286. vertexColors: true,
  33287. toneMapped: false
  33288. });
  33289. const vertices = [];
  33290. const colors = [];
  33291. const pointMap = {}; // colors
  33292. const colorFrustum = new Color(0xffaa00);
  33293. const colorCone = new Color(0xff0000);
  33294. const colorUp = new Color(0x00aaff);
  33295. const colorTarget = new Color(0xffffff);
  33296. const colorCross = new Color(0x333333); // near
  33297. addLine('n1', 'n2', colorFrustum);
  33298. addLine('n2', 'n4', colorFrustum);
  33299. addLine('n4', 'n3', colorFrustum);
  33300. addLine('n3', 'n1', colorFrustum); // far
  33301. addLine('f1', 'f2', colorFrustum);
  33302. addLine('f2', 'f4', colorFrustum);
  33303. addLine('f4', 'f3', colorFrustum);
  33304. addLine('f3', 'f1', colorFrustum); // sides
  33305. addLine('n1', 'f1', colorFrustum);
  33306. addLine('n2', 'f2', colorFrustum);
  33307. addLine('n3', 'f3', colorFrustum);
  33308. addLine('n4', 'f4', colorFrustum); // cone
  33309. addLine('p', 'n1', colorCone);
  33310. addLine('p', 'n2', colorCone);
  33311. addLine('p', 'n3', colorCone);
  33312. addLine('p', 'n4', colorCone); // up
  33313. addLine('u1', 'u2', colorUp);
  33314. addLine('u2', 'u3', colorUp);
  33315. addLine('u3', 'u1', colorUp); // target
  33316. addLine('c', 't', colorTarget);
  33317. addLine('p', 'c', colorCross); // cross
  33318. addLine('cn1', 'cn2', colorCross);
  33319. addLine('cn3', 'cn4', colorCross);
  33320. addLine('cf1', 'cf2', colorCross);
  33321. addLine('cf3', 'cf4', colorCross);
  33322. function addLine(a, b, color) {
  33323. addPoint(a, color);
  33324. addPoint(b, color);
  33325. }
  33326. function addPoint(id, color) {
  33327. vertices.push(0, 0, 0);
  33328. colors.push(color.r, color.g, color.b);
  33329. if (pointMap[id] === undefined) {
  33330. pointMap[id] = [];
  33331. }
  33332. pointMap[id].push(vertices.length / 3 - 1);
  33333. }
  33334. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33335. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33336. super(geometry, material);
  33337. this.type = 'CameraHelper';
  33338. this.camera = camera;
  33339. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  33340. this.matrix = camera.matrixWorld;
  33341. this.matrixAutoUpdate = false;
  33342. this.pointMap = pointMap;
  33343. this.update();
  33344. }
  33345. update() {
  33346. const geometry = this.geometry;
  33347. const pointMap = this.pointMap;
  33348. const w = 1,
  33349. h = 1; // we need just camera projection matrix inverse
  33350. // world matrix must be identity
  33351. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  33352. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  33353. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  33354. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  33355. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  33356. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  33357. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  33358. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  33359. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  33360. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  33361. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  33362. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  33363. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  33364. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  33365. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  33366. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  33367. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  33368. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  33369. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  33370. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  33371. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  33372. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  33373. geometry.getAttribute('position').needsUpdate = true;
  33374. }
  33375. dispose() {
  33376. this.geometry.dispose();
  33377. this.material.dispose();
  33378. }
  33379. }
  33380. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  33381. _vector.set(x, y, z).unproject(camera);
  33382. const points = pointMap[point];
  33383. if (points !== undefined) {
  33384. const position = geometry.getAttribute('position');
  33385. for (let i = 0, l = points.length; i < l; i++) {
  33386. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  33387. }
  33388. }
  33389. }
  33390. const _box = /*@__PURE__*/new Box3();
  33391. class BoxHelper extends LineSegments {
  33392. constructor(object, color = 0xffff00) {
  33393. const 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]);
  33394. const positions = new Float32Array(8 * 3);
  33395. const geometry = new BufferGeometry();
  33396. geometry.setIndex(new BufferAttribute(indices, 1));
  33397. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  33398. super(geometry, new LineBasicMaterial({
  33399. color: color,
  33400. toneMapped: false
  33401. }));
  33402. this.object = object;
  33403. this.type = 'BoxHelper';
  33404. this.matrixAutoUpdate = false;
  33405. this.update();
  33406. }
  33407. update(object) {
  33408. if (object !== undefined) {
  33409. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  33410. }
  33411. if (this.object !== undefined) {
  33412. _box.setFromObject(this.object);
  33413. }
  33414. if (_box.isEmpty()) return;
  33415. const min = _box.min;
  33416. const max = _box.max;
  33417. /*
  33418. 5____4
  33419. 1/___0/|
  33420. | 6__|_7
  33421. 2/___3/
  33422. 0: max.x, max.y, max.z
  33423. 1: min.x, max.y, max.z
  33424. 2: min.x, min.y, max.z
  33425. 3: max.x, min.y, max.z
  33426. 4: max.x, max.y, min.z
  33427. 5: min.x, max.y, min.z
  33428. 6: min.x, min.y, min.z
  33429. 7: max.x, min.y, min.z
  33430. */
  33431. const position = this.geometry.attributes.position;
  33432. const array = position.array;
  33433. array[0] = max.x;
  33434. array[1] = max.y;
  33435. array[2] = max.z;
  33436. array[3] = min.x;
  33437. array[4] = max.y;
  33438. array[5] = max.z;
  33439. array[6] = min.x;
  33440. array[7] = min.y;
  33441. array[8] = max.z;
  33442. array[9] = max.x;
  33443. array[10] = min.y;
  33444. array[11] = max.z;
  33445. array[12] = max.x;
  33446. array[13] = max.y;
  33447. array[14] = min.z;
  33448. array[15] = min.x;
  33449. array[16] = max.y;
  33450. array[17] = min.z;
  33451. array[18] = min.x;
  33452. array[19] = min.y;
  33453. array[20] = min.z;
  33454. array[21] = max.x;
  33455. array[22] = min.y;
  33456. array[23] = min.z;
  33457. position.needsUpdate = true;
  33458. this.geometry.computeBoundingSphere();
  33459. }
  33460. setFromObject(object) {
  33461. this.object = object;
  33462. this.update();
  33463. return this;
  33464. }
  33465. copy(source) {
  33466. LineSegments.prototype.copy.call(this, source);
  33467. this.object = source.object;
  33468. return this;
  33469. }
  33470. }
  33471. class Box3Helper extends LineSegments {
  33472. constructor(box, color = 0xffff00) {
  33473. const 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]);
  33474. const 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];
  33475. const geometry = new BufferGeometry();
  33476. geometry.setIndex(new BufferAttribute(indices, 1));
  33477. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  33478. super(geometry, new LineBasicMaterial({
  33479. color: color,
  33480. toneMapped: false
  33481. }));
  33482. this.box = box;
  33483. this.type = 'Box3Helper';
  33484. this.geometry.computeBoundingSphere();
  33485. }
  33486. updateMatrixWorld(force) {
  33487. const box = this.box;
  33488. if (box.isEmpty()) return;
  33489. box.getCenter(this.position);
  33490. box.getSize(this.scale);
  33491. this.scale.multiplyScalar(0.5);
  33492. super.updateMatrixWorld(force);
  33493. }
  33494. }
  33495. class PlaneHelper extends Line {
  33496. constructor(plane, size = 1, hex = 0xffff00) {
  33497. const color = hex;
  33498. const 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];
  33499. const geometry = new BufferGeometry();
  33500. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  33501. geometry.computeBoundingSphere();
  33502. super(geometry, new LineBasicMaterial({
  33503. color: color,
  33504. toneMapped: false
  33505. }));
  33506. this.type = 'PlaneHelper';
  33507. this.plane = plane;
  33508. this.size = size;
  33509. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  33510. const geometry2 = new BufferGeometry();
  33511. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  33512. geometry2.computeBoundingSphere();
  33513. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  33514. color: color,
  33515. opacity: 0.2,
  33516. transparent: true,
  33517. depthWrite: false,
  33518. toneMapped: false
  33519. })));
  33520. }
  33521. updateMatrixWorld(force) {
  33522. let scale = -this.plane.constant;
  33523. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  33524. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  33525. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  33526. this.lookAt(this.plane.normal);
  33527. super.updateMatrixWorld(force);
  33528. }
  33529. }
  33530. const _axis = /*@__PURE__*/new Vector3();
  33531. let _lineGeometry, _coneGeometry;
  33532. class ArrowHelper extends Object3D {
  33533. // dir is assumed to be normalized
  33534. constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2) {
  33535. super();
  33536. this.type = 'ArrowHelper';
  33537. if (_lineGeometry === undefined) {
  33538. _lineGeometry = new BufferGeometry();
  33539. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  33540. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  33541. _coneGeometry.translate(0, -0.5, 0);
  33542. }
  33543. this.position.copy(origin);
  33544. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  33545. color: color,
  33546. toneMapped: false
  33547. }));
  33548. this.line.matrixAutoUpdate = false;
  33549. this.add(this.line);
  33550. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  33551. color: color,
  33552. toneMapped: false
  33553. }));
  33554. this.cone.matrixAutoUpdate = false;
  33555. this.add(this.cone);
  33556. this.setDirection(dir);
  33557. this.setLength(length, headLength, headWidth);
  33558. }
  33559. setDirection(dir) {
  33560. // dir is assumed to be normalized
  33561. if (dir.y > 0.99999) {
  33562. this.quaternion.set(0, 0, 0, 1);
  33563. } else if (dir.y < -0.99999) {
  33564. this.quaternion.set(1, 0, 0, 0);
  33565. } else {
  33566. _axis.set(dir.z, 0, -dir.x).normalize();
  33567. const radians = Math.acos(dir.y);
  33568. this.quaternion.setFromAxisAngle(_axis, radians);
  33569. }
  33570. }
  33571. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  33572. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  33573. this.line.updateMatrix();
  33574. this.cone.scale.set(headWidth, headLength, headWidth);
  33575. this.cone.position.y = length;
  33576. this.cone.updateMatrix();
  33577. }
  33578. setColor(color) {
  33579. this.line.material.color.set(color);
  33580. this.cone.material.color.set(color);
  33581. }
  33582. copy(source) {
  33583. super.copy(source, false);
  33584. this.line.copy(source.line);
  33585. this.cone.copy(source.cone);
  33586. return this;
  33587. }
  33588. }
  33589. class AxesHelper extends LineSegments {
  33590. constructor(size = 1) {
  33591. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  33592. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  33593. const geometry = new BufferGeometry();
  33594. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33595. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33596. const material = new LineBasicMaterial({
  33597. vertexColors: true,
  33598. toneMapped: false
  33599. });
  33600. super(geometry, material);
  33601. this.type = 'AxesHelper';
  33602. }
  33603. setColors(xAxisColor, yAxisColor, zAxisColor) {
  33604. const color = new Color();
  33605. const array = this.geometry.attributes.color.array;
  33606. color.set(xAxisColor);
  33607. color.toArray(array, 0);
  33608. color.toArray(array, 3);
  33609. color.set(yAxisColor);
  33610. color.toArray(array, 6);
  33611. color.toArray(array, 9);
  33612. color.set(zAxisColor);
  33613. color.toArray(array, 12);
  33614. color.toArray(array, 15);
  33615. this.geometry.attributes.color.needsUpdate = true;
  33616. return this;
  33617. }
  33618. dispose() {
  33619. this.geometry.dispose();
  33620. this.material.dispose();
  33621. }
  33622. }
  33623. class ShapePath {
  33624. constructor() {
  33625. this.type = 'ShapePath';
  33626. this.color = new Color();
  33627. this.subPaths = [];
  33628. this.currentPath = null;
  33629. }
  33630. moveTo(x, y) {
  33631. this.currentPath = new Path();
  33632. this.subPaths.push(this.currentPath);
  33633. this.currentPath.moveTo(x, y);
  33634. return this;
  33635. }
  33636. lineTo(x, y) {
  33637. this.currentPath.lineTo(x, y);
  33638. return this;
  33639. }
  33640. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  33641. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  33642. return this;
  33643. }
  33644. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  33645. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  33646. return this;
  33647. }
  33648. splineThru(pts) {
  33649. this.currentPath.splineThru(pts);
  33650. return this;
  33651. }
  33652. toShapes(isCCW, noHoles) {
  33653. function toShapesNoHoles(inSubpaths) {
  33654. const shapes = [];
  33655. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  33656. const tmpPath = inSubpaths[i];
  33657. const tmpShape = new Shape();
  33658. tmpShape.curves = tmpPath.curves;
  33659. shapes.push(tmpShape);
  33660. }
  33661. return shapes;
  33662. }
  33663. function isPointInsidePolygon(inPt, inPolygon) {
  33664. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  33665. // toggling of inside/outside at every single! intersection point of an edge
  33666. // with the horizontal line through inPt, left of inPt
  33667. // not counting lowerY endpoints of edges and whole edges on that line
  33668. let inside = false;
  33669. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  33670. let edgeLowPt = inPolygon[p];
  33671. let edgeHighPt = inPolygon[q];
  33672. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  33673. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  33674. if (Math.abs(edgeDy) > Number.EPSILON) {
  33675. // not parallel
  33676. if (edgeDy < 0) {
  33677. edgeLowPt = inPolygon[q];
  33678. edgeDx = -edgeDx;
  33679. edgeHighPt = inPolygon[p];
  33680. edgeDy = -edgeDy;
  33681. }
  33682. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  33683. if (inPt.y === edgeLowPt.y) {
  33684. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  33685. // continue; // no intersection or edgeLowPt => doesn't count !!!
  33686. } else {
  33687. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  33688. if (perpEdge === 0) return true; // inPt is on contour ?
  33689. if (perpEdge < 0) continue;
  33690. inside = !inside; // true intersection left of inPt
  33691. }
  33692. } else {
  33693. // parallel or collinear
  33694. if (inPt.y !== edgeLowPt.y) continue; // parallel
  33695. // edge lies on the same horizontal line as inPt
  33696. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  33697. // continue;
  33698. }
  33699. }
  33700. return inside;
  33701. }
  33702. const isClockWise = ShapeUtils.isClockWise;
  33703. const subPaths = this.subPaths;
  33704. if (subPaths.length === 0) return [];
  33705. if (noHoles === true) return toShapesNoHoles(subPaths);
  33706. let solid, tmpPath, tmpShape;
  33707. const shapes = [];
  33708. if (subPaths.length === 1) {
  33709. tmpPath = subPaths[0];
  33710. tmpShape = new Shape();
  33711. tmpShape.curves = tmpPath.curves;
  33712. shapes.push(tmpShape);
  33713. return shapes;
  33714. }
  33715. let holesFirst = !isClockWise(subPaths[0].getPoints());
  33716. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  33717. const betterShapeHoles = [];
  33718. const newShapes = [];
  33719. let newShapeHoles = [];
  33720. let mainIdx = 0;
  33721. let tmpPoints;
  33722. newShapes[mainIdx] = undefined;
  33723. newShapeHoles[mainIdx] = [];
  33724. for (let i = 0, l = subPaths.length; i < l; i++) {
  33725. tmpPath = subPaths[i];
  33726. tmpPoints = tmpPath.getPoints();
  33727. solid = isClockWise(tmpPoints);
  33728. solid = isCCW ? !solid : solid;
  33729. if (solid) {
  33730. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  33731. newShapes[mainIdx] = {
  33732. s: new Shape(),
  33733. p: tmpPoints
  33734. };
  33735. newShapes[mainIdx].s.curves = tmpPath.curves;
  33736. if (holesFirst) mainIdx++;
  33737. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  33738. } else {
  33739. newShapeHoles[mainIdx].push({
  33740. h: tmpPath,
  33741. p: tmpPoints[0]
  33742. }); //console.log('ccw', i);
  33743. }
  33744. } // only Holes? -> probably all Shapes with wrong orientation
  33745. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  33746. if (newShapes.length > 1) {
  33747. let ambiguous = false;
  33748. const toChange = [];
  33749. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  33750. betterShapeHoles[sIdx] = [];
  33751. }
  33752. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  33753. const sho = newShapeHoles[sIdx];
  33754. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  33755. const ho = sho[hIdx];
  33756. let hole_unassigned = true;
  33757. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  33758. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  33759. if (sIdx !== s2Idx) toChange.push({
  33760. froms: sIdx,
  33761. tos: s2Idx,
  33762. hole: hIdx
  33763. });
  33764. if (hole_unassigned) {
  33765. hole_unassigned = false;
  33766. betterShapeHoles[s2Idx].push(ho);
  33767. } else {
  33768. ambiguous = true;
  33769. }
  33770. }
  33771. }
  33772. if (hole_unassigned) {
  33773. betterShapeHoles[sIdx].push(ho);
  33774. }
  33775. }
  33776. } // console.log("ambiguous: ", ambiguous);
  33777. if (toChange.length > 0) {
  33778. // console.log("to change: ", toChange);
  33779. if (!ambiguous) newShapeHoles = betterShapeHoles;
  33780. }
  33781. }
  33782. let tmpHoles;
  33783. for (let i = 0, il = newShapes.length; i < il; i++) {
  33784. tmpShape = newShapes[i].s;
  33785. shapes.push(tmpShape);
  33786. tmpHoles = newShapeHoles[i];
  33787. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  33788. tmpShape.holes.push(tmpHoles[j].h);
  33789. }
  33790. } //console.log("shape", shapes);
  33791. return shapes;
  33792. }
  33793. }
  33794. const _floatView = new Float32Array(1);
  33795. const _int32View = new Int32Array(_floatView.buffer);
  33796. class DataUtils {
  33797. // Converts float32 to float16 (stored as uint16 value).
  33798. static toHalfFloat(val) {
  33799. if (val > 65504) {
  33800. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  33801. val = 65504; // maximum representable value in float16
  33802. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  33803. /* This method is faster than the OpenEXR implementation (very often
  33804. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  33805. * by James Tursa?s half-precision code. */
  33806. _floatView[0] = val;
  33807. const x = _int32View[0];
  33808. let bits = x >> 16 & 0x8000;
  33809. /* Get the sign */
  33810. let m = x >> 12 & 0x07ff;
  33811. /* Keep one extra bit for rounding */
  33812. const e = x >> 23 & 0xff;
  33813. /* Using int is faster here */
  33814. /* If zero, or denormal, or exponent underflows too much for a denormal
  33815. * half, return signed zero. */
  33816. if (e < 103) return bits;
  33817. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  33818. if (e > 142) {
  33819. bits |= 0x7c00;
  33820. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  33821. * not Inf, so make sure we set one mantissa bit too. */
  33822. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  33823. return bits;
  33824. }
  33825. /* If exponent underflows but not too much, return a denormal */
  33826. if (e < 113) {
  33827. m |= 0x0800;
  33828. /* Extra rounding may overflow and set mantissa to 0 and exponent
  33829. * to 1, which is OK. */
  33830. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  33831. return bits;
  33832. }
  33833. bits |= e - 112 << 10 | m >> 1;
  33834. /* Extra rounding. An overflow will set mantissa to 0 and increment
  33835. * the exponent, which is OK. */
  33836. bits += m & 1;
  33837. return bits;
  33838. }
  33839. }
  33840. const LineStrip = 0;
  33841. const LinePieces = 1;
  33842. const NoColors = 0;
  33843. const FaceColors = 1;
  33844. const VertexColors = 2;
  33845. function MeshFaceMaterial(materials) {
  33846. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  33847. return materials;
  33848. }
  33849. function MultiMaterial(materials = []) {
  33850. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  33851. materials.isMultiMaterial = true;
  33852. materials.materials = materials;
  33853. materials.clone = function () {
  33854. return materials.slice();
  33855. };
  33856. return materials;
  33857. }
  33858. function PointCloud(geometry, material) {
  33859. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  33860. return new Points(geometry, material);
  33861. }
  33862. function Particle(material) {
  33863. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  33864. return new Sprite(material);
  33865. }
  33866. function ParticleSystem(geometry, material) {
  33867. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  33868. return new Points(geometry, material);
  33869. }
  33870. function PointCloudMaterial(parameters) {
  33871. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  33872. return new PointsMaterial(parameters);
  33873. }
  33874. function ParticleBasicMaterial(parameters) {
  33875. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  33876. return new PointsMaterial(parameters);
  33877. }
  33878. function ParticleSystemMaterial(parameters) {
  33879. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  33880. return new PointsMaterial(parameters);
  33881. }
  33882. function Vertex(x, y, z) {
  33883. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  33884. return new Vector3(x, y, z);
  33885. } //
  33886. function DynamicBufferAttribute(array, itemSize) {
  33887. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  33888. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  33889. }
  33890. function Int8Attribute(array, itemSize) {
  33891. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  33892. return new Int8BufferAttribute(array, itemSize);
  33893. }
  33894. function Uint8Attribute(array, itemSize) {
  33895. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  33896. return new Uint8BufferAttribute(array, itemSize);
  33897. }
  33898. function Uint8ClampedAttribute(array, itemSize) {
  33899. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  33900. return new Uint8ClampedBufferAttribute(array, itemSize);
  33901. }
  33902. function Int16Attribute(array, itemSize) {
  33903. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  33904. return new Int16BufferAttribute(array, itemSize);
  33905. }
  33906. function Uint16Attribute(array, itemSize) {
  33907. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  33908. return new Uint16BufferAttribute(array, itemSize);
  33909. }
  33910. function Int32Attribute(array, itemSize) {
  33911. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  33912. return new Int32BufferAttribute(array, itemSize);
  33913. }
  33914. function Uint32Attribute(array, itemSize) {
  33915. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  33916. return new Uint32BufferAttribute(array, itemSize);
  33917. }
  33918. function Float32Attribute(array, itemSize) {
  33919. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  33920. return new Float32BufferAttribute(array, itemSize);
  33921. }
  33922. function Float64Attribute(array, itemSize) {
  33923. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  33924. return new Float64BufferAttribute(array, itemSize);
  33925. } //
  33926. Curve.create = function (construct, getPoint) {
  33927. console.log('THREE.Curve.create() has been deprecated');
  33928. construct.prototype = Object.create(Curve.prototype);
  33929. construct.prototype.constructor = construct;
  33930. construct.prototype.getPoint = getPoint;
  33931. return construct;
  33932. }; //
  33933. Path.prototype.fromPoints = function (points) {
  33934. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  33935. return this.setFromPoints(points);
  33936. }; //
  33937. function AxisHelper(size) {
  33938. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  33939. return new AxesHelper(size);
  33940. }
  33941. function BoundingBoxHelper(object, color) {
  33942. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  33943. return new BoxHelper(object, color);
  33944. }
  33945. function EdgesHelper(object, hex) {
  33946. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  33947. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  33948. color: hex !== undefined ? hex : 0xffffff
  33949. }));
  33950. }
  33951. GridHelper.prototype.setColors = function () {
  33952. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  33953. };
  33954. SkeletonHelper.prototype.update = function () {
  33955. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  33956. };
  33957. function WireframeHelper(object, hex) {
  33958. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  33959. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  33960. color: hex !== undefined ? hex : 0xffffff
  33961. }));
  33962. } //
  33963. Loader.prototype.extractUrlBase = function (url) {
  33964. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  33965. return LoaderUtils.extractUrlBase(url);
  33966. };
  33967. Loader.Handlers = {
  33968. add: function () {
  33969. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  33970. },
  33971. get: function () {
  33972. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  33973. }
  33974. };
  33975. function XHRLoader(manager) {
  33976. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  33977. return new FileLoader(manager);
  33978. }
  33979. function BinaryTextureLoader(manager) {
  33980. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  33981. return new DataTextureLoader(manager);
  33982. } //
  33983. Box2.prototype.center = function (optionalTarget) {
  33984. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  33985. return this.getCenter(optionalTarget);
  33986. };
  33987. Box2.prototype.empty = function () {
  33988. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  33989. return this.isEmpty();
  33990. };
  33991. Box2.prototype.isIntersectionBox = function (box) {
  33992. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  33993. return this.intersectsBox(box);
  33994. };
  33995. Box2.prototype.size = function (optionalTarget) {
  33996. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  33997. return this.getSize(optionalTarget);
  33998. }; //
  33999. Box3.prototype.center = function (optionalTarget) {
  34000. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  34001. return this.getCenter(optionalTarget);
  34002. };
  34003. Box3.prototype.empty = function () {
  34004. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  34005. return this.isEmpty();
  34006. };
  34007. Box3.prototype.isIntersectionBox = function (box) {
  34008. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  34009. return this.intersectsBox(box);
  34010. };
  34011. Box3.prototype.isIntersectionSphere = function (sphere) {
  34012. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  34013. return this.intersectsSphere(sphere);
  34014. };
  34015. Box3.prototype.size = function (optionalTarget) {
  34016. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  34017. return this.getSize(optionalTarget);
  34018. }; //
  34019. Sphere.prototype.empty = function () {
  34020. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  34021. return this.isEmpty();
  34022. }; //
  34023. Frustum.prototype.setFromMatrix = function (m) {
  34024. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  34025. return this.setFromProjectionMatrix(m);
  34026. }; //
  34027. Line3.prototype.center = function (optionalTarget) {
  34028. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  34029. return this.getCenter(optionalTarget);
  34030. }; //
  34031. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  34032. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  34033. return this.toArray(array, offset);
  34034. };
  34035. Matrix3.prototype.multiplyVector3 = function (vector) {
  34036. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  34037. return vector.applyMatrix3(this);
  34038. };
  34039. Matrix3.prototype.multiplyVector3Array = function () {
  34040. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  34041. };
  34042. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  34043. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  34044. return attribute.applyMatrix3(this);
  34045. };
  34046. Matrix3.prototype.applyToVector3Array = function () {
  34047. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  34048. };
  34049. Matrix3.prototype.getInverse = function (matrix) {
  34050. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  34051. return this.copy(matrix).invert();
  34052. }; //
  34053. Matrix4.prototype.extractPosition = function (m) {
  34054. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  34055. return this.copyPosition(m);
  34056. };
  34057. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  34058. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  34059. return this.toArray(array, offset);
  34060. };
  34061. Matrix4.prototype.getPosition = function () {
  34062. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  34063. return new Vector3().setFromMatrixColumn(this, 3);
  34064. };
  34065. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  34066. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  34067. return this.makeRotationFromQuaternion(q);
  34068. };
  34069. Matrix4.prototype.multiplyToArray = function () {
  34070. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  34071. };
  34072. Matrix4.prototype.multiplyVector3 = function (vector) {
  34073. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  34074. return vector.applyMatrix4(this);
  34075. };
  34076. Matrix4.prototype.multiplyVector4 = function (vector) {
  34077. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  34078. return vector.applyMatrix4(this);
  34079. };
  34080. Matrix4.prototype.multiplyVector3Array = function () {
  34081. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  34082. };
  34083. Matrix4.prototype.rotateAxis = function (v) {
  34084. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  34085. v.transformDirection(this);
  34086. };
  34087. Matrix4.prototype.crossVector = function (vector) {
  34088. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  34089. return vector.applyMatrix4(this);
  34090. };
  34091. Matrix4.prototype.translate = function () {
  34092. console.error('THREE.Matrix4: .translate() has been removed.');
  34093. };
  34094. Matrix4.prototype.rotateX = function () {
  34095. console.error('THREE.Matrix4: .rotateX() has been removed.');
  34096. };
  34097. Matrix4.prototype.rotateY = function () {
  34098. console.error('THREE.Matrix4: .rotateY() has been removed.');
  34099. };
  34100. Matrix4.prototype.rotateZ = function () {
  34101. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  34102. };
  34103. Matrix4.prototype.rotateByAxis = function () {
  34104. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  34105. };
  34106. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  34107. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  34108. return attribute.applyMatrix4(this);
  34109. };
  34110. Matrix4.prototype.applyToVector3Array = function () {
  34111. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  34112. };
  34113. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  34114. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  34115. return this.makePerspective(left, right, top, bottom, near, far);
  34116. };
  34117. Matrix4.prototype.getInverse = function (matrix) {
  34118. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  34119. return this.copy(matrix).invert();
  34120. }; //
  34121. Plane.prototype.isIntersectionLine = function (line) {
  34122. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  34123. return this.intersectsLine(line);
  34124. }; //
  34125. Quaternion.prototype.multiplyVector3 = function (vector) {
  34126. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  34127. return vector.applyQuaternion(this);
  34128. };
  34129. Quaternion.prototype.inverse = function () {
  34130. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  34131. return this.invert();
  34132. }; //
  34133. Ray.prototype.isIntersectionBox = function (box) {
  34134. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  34135. return this.intersectsBox(box);
  34136. };
  34137. Ray.prototype.isIntersectionPlane = function (plane) {
  34138. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  34139. return this.intersectsPlane(plane);
  34140. };
  34141. Ray.prototype.isIntersectionSphere = function (sphere) {
  34142. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  34143. return this.intersectsSphere(sphere);
  34144. }; //
  34145. Triangle.prototype.area = function () {
  34146. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  34147. return this.getArea();
  34148. };
  34149. Triangle.prototype.barycoordFromPoint = function (point, target) {
  34150. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  34151. return this.getBarycoord(point, target);
  34152. };
  34153. Triangle.prototype.midpoint = function (target) {
  34154. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  34155. return this.getMidpoint(target);
  34156. };
  34157. Triangle.prototypenormal = function (target) {
  34158. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  34159. return this.getNormal(target);
  34160. };
  34161. Triangle.prototype.plane = function (target) {
  34162. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  34163. return this.getPlane(target);
  34164. };
  34165. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  34166. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  34167. return Triangle.getBarycoord(point, a, b, c, target);
  34168. };
  34169. Triangle.normal = function (a, b, c, target) {
  34170. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  34171. return Triangle.getNormal(a, b, c, target);
  34172. }; //
  34173. Shape.prototype.extractAllPoints = function (divisions) {
  34174. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  34175. return this.extractPoints(divisions);
  34176. };
  34177. Shape.prototype.extrude = function (options) {
  34178. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  34179. return new ExtrudeGeometry(this, options);
  34180. };
  34181. Shape.prototype.makeGeometry = function (options) {
  34182. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  34183. return new ShapeGeometry(this, options);
  34184. }; //
  34185. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  34186. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  34187. return this.fromBufferAttribute(attribute, index, offset);
  34188. };
  34189. Vector2.prototype.distanceToManhattan = function (v) {
  34190. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  34191. return this.manhattanDistanceTo(v);
  34192. };
  34193. Vector2.prototype.lengthManhattan = function () {
  34194. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  34195. return this.manhattanLength();
  34196. }; //
  34197. Vector3.prototype.setEulerFromRotationMatrix = function () {
  34198. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  34199. };
  34200. Vector3.prototype.setEulerFromQuaternion = function () {
  34201. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  34202. };
  34203. Vector3.prototype.getPositionFromMatrix = function (m) {
  34204. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  34205. return this.setFromMatrixPosition(m);
  34206. };
  34207. Vector3.prototype.getScaleFromMatrix = function (m) {
  34208. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  34209. return this.setFromMatrixScale(m);
  34210. };
  34211. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  34212. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  34213. return this.setFromMatrixColumn(matrix, index);
  34214. };
  34215. Vector3.prototype.applyProjection = function (m) {
  34216. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  34217. return this.applyMatrix4(m);
  34218. };
  34219. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  34220. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  34221. return this.fromBufferAttribute(attribute, index, offset);
  34222. };
  34223. Vector3.prototype.distanceToManhattan = function (v) {
  34224. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  34225. return this.manhattanDistanceTo(v);
  34226. };
  34227. Vector3.prototype.lengthManhattan = function () {
  34228. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  34229. return this.manhattanLength();
  34230. }; //
  34231. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  34232. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  34233. return this.fromBufferAttribute(attribute, index, offset);
  34234. };
  34235. Vector4.prototype.lengthManhattan = function () {
  34236. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  34237. return this.manhattanLength();
  34238. }; //
  34239. Object3D.prototype.getChildByName = function (name) {
  34240. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  34241. return this.getObjectByName(name);
  34242. };
  34243. Object3D.prototype.renderDepth = function () {
  34244. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  34245. };
  34246. Object3D.prototype.translate = function (distance, axis) {
  34247. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  34248. return this.translateOnAxis(axis, distance);
  34249. };
  34250. Object3D.prototype.getWorldRotation = function () {
  34251. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  34252. };
  34253. Object3D.prototype.applyMatrix = function (matrix) {
  34254. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  34255. return this.applyMatrix4(matrix);
  34256. };
  34257. Object.defineProperties(Object3D.prototype, {
  34258. eulerOrder: {
  34259. get: function () {
  34260. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  34261. return this.rotation.order;
  34262. },
  34263. set: function (value) {
  34264. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  34265. this.rotation.order = value;
  34266. }
  34267. },
  34268. useQuaternion: {
  34269. get: function () {
  34270. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  34271. },
  34272. set: function () {
  34273. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  34274. }
  34275. }
  34276. });
  34277. Mesh.prototype.setDrawMode = function () {
  34278. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  34279. };
  34280. Object.defineProperties(Mesh.prototype, {
  34281. drawMode: {
  34282. get: function () {
  34283. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  34284. return TrianglesDrawMode;
  34285. },
  34286. set: function () {
  34287. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  34288. }
  34289. }
  34290. });
  34291. SkinnedMesh.prototype.initBones = function () {
  34292. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  34293. }; //
  34294. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  34295. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  34296. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  34297. this.setFocalLength(focalLength);
  34298. }; //
  34299. Object.defineProperties(Light.prototype, {
  34300. onlyShadow: {
  34301. set: function () {
  34302. console.warn('THREE.Light: .onlyShadow has been removed.');
  34303. }
  34304. },
  34305. shadowCameraFov: {
  34306. set: function (value) {
  34307. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  34308. this.shadow.camera.fov = value;
  34309. }
  34310. },
  34311. shadowCameraLeft: {
  34312. set: function (value) {
  34313. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  34314. this.shadow.camera.left = value;
  34315. }
  34316. },
  34317. shadowCameraRight: {
  34318. set: function (value) {
  34319. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  34320. this.shadow.camera.right = value;
  34321. }
  34322. },
  34323. shadowCameraTop: {
  34324. set: function (value) {
  34325. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  34326. this.shadow.camera.top = value;
  34327. }
  34328. },
  34329. shadowCameraBottom: {
  34330. set: function (value) {
  34331. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  34332. this.shadow.camera.bottom = value;
  34333. }
  34334. },
  34335. shadowCameraNear: {
  34336. set: function (value) {
  34337. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  34338. this.shadow.camera.near = value;
  34339. }
  34340. },
  34341. shadowCameraFar: {
  34342. set: function (value) {
  34343. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  34344. this.shadow.camera.far = value;
  34345. }
  34346. },
  34347. shadowCameraVisible: {
  34348. set: function () {
  34349. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  34350. }
  34351. },
  34352. shadowBias: {
  34353. set: function (value) {
  34354. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  34355. this.shadow.bias = value;
  34356. }
  34357. },
  34358. shadowDarkness: {
  34359. set: function () {
  34360. console.warn('THREE.Light: .shadowDarkness has been removed.');
  34361. }
  34362. },
  34363. shadowMapWidth: {
  34364. set: function (value) {
  34365. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  34366. this.shadow.mapSize.width = value;
  34367. }
  34368. },
  34369. shadowMapHeight: {
  34370. set: function (value) {
  34371. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  34372. this.shadow.mapSize.height = value;
  34373. }
  34374. }
  34375. }); //
  34376. Object.defineProperties(BufferAttribute.prototype, {
  34377. length: {
  34378. get: function () {
  34379. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  34380. return this.array.length;
  34381. }
  34382. },
  34383. dynamic: {
  34384. get: function () {
  34385. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  34386. return this.usage === DynamicDrawUsage;
  34387. },
  34388. set: function () {
  34389. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  34390. this.setUsage(DynamicDrawUsage);
  34391. }
  34392. }
  34393. });
  34394. BufferAttribute.prototype.setDynamic = function (value) {
  34395. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  34396. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  34397. return this;
  34398. };
  34399. BufferAttribute.prototype.copyIndicesArray = function () {
  34400. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  34401. }, BufferAttribute.prototype.setArray = function () {
  34402. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  34403. }; //
  34404. BufferGeometry.prototype.addIndex = function (index) {
  34405. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  34406. this.setIndex(index);
  34407. };
  34408. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  34409. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  34410. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  34411. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  34412. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  34413. }
  34414. if (name === 'index') {
  34415. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  34416. this.setIndex(attribute);
  34417. return this;
  34418. }
  34419. return this.setAttribute(name, attribute);
  34420. };
  34421. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  34422. if (indexOffset !== undefined) {
  34423. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  34424. }
  34425. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  34426. this.addGroup(start, count);
  34427. };
  34428. BufferGeometry.prototype.clearDrawCalls = function () {
  34429. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  34430. this.clearGroups();
  34431. };
  34432. BufferGeometry.prototype.computeOffsets = function () {
  34433. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  34434. };
  34435. BufferGeometry.prototype.removeAttribute = function (name) {
  34436. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  34437. return this.deleteAttribute(name);
  34438. };
  34439. BufferGeometry.prototype.applyMatrix = function (matrix) {
  34440. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  34441. return this.applyMatrix4(matrix);
  34442. };
  34443. Object.defineProperties(BufferGeometry.prototype, {
  34444. drawcalls: {
  34445. get: function () {
  34446. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  34447. return this.groups;
  34448. }
  34449. },
  34450. offsets: {
  34451. get: function () {
  34452. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  34453. return this.groups;
  34454. }
  34455. }
  34456. });
  34457. InterleavedBuffer.prototype.setDynamic = function (value) {
  34458. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  34459. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  34460. return this;
  34461. };
  34462. InterleavedBuffer.prototype.setArray = function () {
  34463. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  34464. }; //
  34465. ExtrudeGeometry.prototype.getArrays = function () {
  34466. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  34467. };
  34468. ExtrudeGeometry.prototype.addShapeList = function () {
  34469. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  34470. };
  34471. ExtrudeGeometry.prototype.addShape = function () {
  34472. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  34473. }; //
  34474. Scene.prototype.dispose = function () {
  34475. console.error('THREE.Scene: .dispose() has been removed.');
  34476. }; //
  34477. Uniform.prototype.onUpdate = function () {
  34478. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  34479. return this;
  34480. }; //
  34481. Object.defineProperties(Material.prototype, {
  34482. wrapAround: {
  34483. get: function () {
  34484. console.warn('THREE.Material: .wrapAround has been removed.');
  34485. },
  34486. set: function () {
  34487. console.warn('THREE.Material: .wrapAround has been removed.');
  34488. }
  34489. },
  34490. overdraw: {
  34491. get: function () {
  34492. console.warn('THREE.Material: .overdraw has been removed.');
  34493. },
  34494. set: function () {
  34495. console.warn('THREE.Material: .overdraw has been removed.');
  34496. }
  34497. },
  34498. wrapRGB: {
  34499. get: function () {
  34500. console.warn('THREE.Material: .wrapRGB has been removed.');
  34501. return new Color();
  34502. }
  34503. },
  34504. shading: {
  34505. get: function () {
  34506. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  34507. },
  34508. set: function (value) {
  34509. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  34510. this.flatShading = value === FlatShading;
  34511. }
  34512. },
  34513. stencilMask: {
  34514. get: function () {
  34515. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  34516. return this.stencilFuncMask;
  34517. },
  34518. set: function (value) {
  34519. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  34520. this.stencilFuncMask = value;
  34521. }
  34522. },
  34523. vertexTangents: {
  34524. get: function () {
  34525. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  34526. },
  34527. set: function () {
  34528. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  34529. }
  34530. }
  34531. });
  34532. Object.defineProperties(ShaderMaterial.prototype, {
  34533. derivatives: {
  34534. get: function () {
  34535. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  34536. return this.extensions.derivatives;
  34537. },
  34538. set: function (value) {
  34539. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  34540. this.extensions.derivatives = value;
  34541. }
  34542. }
  34543. }); //
  34544. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  34545. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  34546. this.setRenderTarget(renderTarget);
  34547. this.clear(color, depth, stencil);
  34548. };
  34549. WebGLRenderer.prototype.animate = function (callback) {
  34550. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  34551. this.setAnimationLoop(callback);
  34552. };
  34553. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  34554. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  34555. return this.getRenderTarget();
  34556. };
  34557. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  34558. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  34559. return this.capabilities.getMaxAnisotropy();
  34560. };
  34561. WebGLRenderer.prototype.getPrecision = function () {
  34562. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  34563. return this.capabilities.precision;
  34564. };
  34565. WebGLRenderer.prototype.resetGLState = function () {
  34566. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  34567. return this.state.reset();
  34568. };
  34569. WebGLRenderer.prototype.supportsFloatTextures = function () {
  34570. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  34571. return this.extensions.get('OES_texture_float');
  34572. };
  34573. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  34574. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  34575. return this.extensions.get('OES_texture_half_float');
  34576. };
  34577. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  34578. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  34579. return this.extensions.get('OES_standard_derivatives');
  34580. };
  34581. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  34582. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  34583. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  34584. };
  34585. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  34586. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  34587. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  34588. };
  34589. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  34590. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  34591. return this.extensions.get('EXT_blend_minmax');
  34592. };
  34593. WebGLRenderer.prototype.supportsVertexTextures = function () {
  34594. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  34595. return this.capabilities.vertexTextures;
  34596. };
  34597. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  34598. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  34599. return this.extensions.get('ANGLE_instanced_arrays');
  34600. };
  34601. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  34602. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  34603. this.setScissorTest(boolean);
  34604. };
  34605. WebGLRenderer.prototype.initMaterial = function () {
  34606. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  34607. };
  34608. WebGLRenderer.prototype.addPrePlugin = function () {
  34609. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  34610. };
  34611. WebGLRenderer.prototype.addPostPlugin = function () {
  34612. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  34613. };
  34614. WebGLRenderer.prototype.updateShadowMap = function () {
  34615. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  34616. };
  34617. WebGLRenderer.prototype.setFaceCulling = function () {
  34618. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  34619. };
  34620. WebGLRenderer.prototype.setTexture = function () {
  34621. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  34622. };
  34623. WebGLRenderer.prototype.setTextureCube = function () {
  34624. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  34625. };
  34626. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  34627. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  34628. return this.getActiveMipmapLevel();
  34629. };
  34630. Object.defineProperties(WebGLRenderer.prototype, {
  34631. shadowMapEnabled: {
  34632. get: function () {
  34633. return this.shadowMap.enabled;
  34634. },
  34635. set: function (value) {
  34636. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  34637. this.shadowMap.enabled = value;
  34638. }
  34639. },
  34640. shadowMapType: {
  34641. get: function () {
  34642. return this.shadowMap.type;
  34643. },
  34644. set: function (value) {
  34645. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  34646. this.shadowMap.type = value;
  34647. }
  34648. },
  34649. shadowMapCullFace: {
  34650. get: function () {
  34651. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  34652. return undefined;
  34653. },
  34654. set: function () {
  34655. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  34656. }
  34657. },
  34658. context: {
  34659. get: function () {
  34660. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  34661. return this.getContext();
  34662. }
  34663. },
  34664. vr: {
  34665. get: function () {
  34666. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  34667. return this.xr;
  34668. }
  34669. },
  34670. gammaInput: {
  34671. get: function () {
  34672. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  34673. return false;
  34674. },
  34675. set: function () {
  34676. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  34677. }
  34678. },
  34679. gammaOutput: {
  34680. get: function () {
  34681. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  34682. return false;
  34683. },
  34684. set: function (value) {
  34685. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  34686. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  34687. }
  34688. },
  34689. toneMappingWhitePoint: {
  34690. get: function () {
  34691. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  34692. return 1.0;
  34693. },
  34694. set: function () {
  34695. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  34696. }
  34697. }
  34698. });
  34699. Object.defineProperties(WebGLShadowMap.prototype, {
  34700. cullFace: {
  34701. get: function () {
  34702. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  34703. return undefined;
  34704. },
  34705. set: function () {
  34706. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  34707. }
  34708. },
  34709. renderReverseSided: {
  34710. get: function () {
  34711. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  34712. return undefined;
  34713. },
  34714. set: function () {
  34715. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  34716. }
  34717. },
  34718. renderSingleSided: {
  34719. get: function () {
  34720. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  34721. return undefined;
  34722. },
  34723. set: function () {
  34724. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  34725. }
  34726. }
  34727. });
  34728. function WebGLRenderTargetCube(width, height, options) {
  34729. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  34730. return new WebGLCubeRenderTarget(width, options);
  34731. } //
  34732. Object.defineProperties(WebGLRenderTarget.prototype, {
  34733. wrapS: {
  34734. get: function () {
  34735. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  34736. return this.texture.wrapS;
  34737. },
  34738. set: function (value) {
  34739. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  34740. this.texture.wrapS = value;
  34741. }
  34742. },
  34743. wrapT: {
  34744. get: function () {
  34745. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  34746. return this.texture.wrapT;
  34747. },
  34748. set: function (value) {
  34749. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  34750. this.texture.wrapT = value;
  34751. }
  34752. },
  34753. magFilter: {
  34754. get: function () {
  34755. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  34756. return this.texture.magFilter;
  34757. },
  34758. set: function (value) {
  34759. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  34760. this.texture.magFilter = value;
  34761. }
  34762. },
  34763. minFilter: {
  34764. get: function () {
  34765. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  34766. return this.texture.minFilter;
  34767. },
  34768. set: function (value) {
  34769. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  34770. this.texture.minFilter = value;
  34771. }
  34772. },
  34773. anisotropy: {
  34774. get: function () {
  34775. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  34776. return this.texture.anisotropy;
  34777. },
  34778. set: function (value) {
  34779. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  34780. this.texture.anisotropy = value;
  34781. }
  34782. },
  34783. offset: {
  34784. get: function () {
  34785. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  34786. return this.texture.offset;
  34787. },
  34788. set: function (value) {
  34789. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  34790. this.texture.offset = value;
  34791. }
  34792. },
  34793. repeat: {
  34794. get: function () {
  34795. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  34796. return this.texture.repeat;
  34797. },
  34798. set: function (value) {
  34799. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  34800. this.texture.repeat = value;
  34801. }
  34802. },
  34803. format: {
  34804. get: function () {
  34805. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  34806. return this.texture.format;
  34807. },
  34808. set: function (value) {
  34809. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  34810. this.texture.format = value;
  34811. }
  34812. },
  34813. type: {
  34814. get: function () {
  34815. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  34816. return this.texture.type;
  34817. },
  34818. set: function (value) {
  34819. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  34820. this.texture.type = value;
  34821. }
  34822. },
  34823. generateMipmaps: {
  34824. get: function () {
  34825. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  34826. return this.texture.generateMipmaps;
  34827. },
  34828. set: function (value) {
  34829. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  34830. this.texture.generateMipmaps = value;
  34831. }
  34832. }
  34833. }); //
  34834. Audio.prototype.load = function (file) {
  34835. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  34836. const scope = this;
  34837. const audioLoader = new AudioLoader();
  34838. audioLoader.load(file, function (buffer) {
  34839. scope.setBuffer(buffer);
  34840. });
  34841. return this;
  34842. };
  34843. AudioAnalyser.prototype.getData = function () {
  34844. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  34845. return this.getFrequencyData();
  34846. }; //
  34847. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  34848. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  34849. return this.update(renderer, scene);
  34850. };
  34851. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  34852. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  34853. return this.renderTarget.clear(renderer, color, depth, stencil);
  34854. };
  34855. ImageUtils.crossOrigin = undefined;
  34856. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  34857. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  34858. const loader = new TextureLoader();
  34859. loader.setCrossOrigin(this.crossOrigin);
  34860. const texture = loader.load(url, onLoad, undefined, onError);
  34861. if (mapping) texture.mapping = mapping;
  34862. return texture;
  34863. };
  34864. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  34865. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  34866. const loader = new CubeTextureLoader();
  34867. loader.setCrossOrigin(this.crossOrigin);
  34868. const texture = loader.load(urls, onLoad, undefined, onError);
  34869. if (mapping) texture.mapping = mapping;
  34870. return texture;
  34871. };
  34872. ImageUtils.loadCompressedTexture = function () {
  34873. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  34874. };
  34875. ImageUtils.loadCompressedTextureCube = function () {
  34876. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  34877. }; //
  34878. function CanvasRenderer() {
  34879. console.error('THREE.CanvasRenderer has been removed');
  34880. } //
  34881. function JSONLoader() {
  34882. console.error('THREE.JSONLoader has been removed.');
  34883. } //
  34884. const SceneUtils = {
  34885. createMultiMaterialObject: function () {
  34886. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  34887. },
  34888. detach: function () {
  34889. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  34890. },
  34891. attach: function () {
  34892. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  34893. }
  34894. }; //
  34895. function LensFlare() {
  34896. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  34897. } //
  34898. function ParametricGeometry() {
  34899. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  34900. return new BufferGeometry();
  34901. }
  34902. function TextGeometry() {
  34903. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  34904. return new BufferGeometry();
  34905. }
  34906. function FontLoader() {
  34907. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  34908. }
  34909. function Font() {
  34910. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  34911. }
  34912. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  34913. /* eslint-disable no-undef */
  34914. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  34915. detail: {
  34916. revision: REVISION
  34917. }
  34918. }));
  34919. /* eslint-enable no-undef */
  34920. }
  34921. if (typeof window !== 'undefined') {
  34922. if (window.__THREE__) {
  34923. console.warn('WARNING: Multiple instances of Three.js being imported.');
  34924. } else {
  34925. window.__THREE__ = REVISION;
  34926. }
  34927. }
  34928. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  34929. exports.AddEquation = AddEquation;
  34930. exports.AddOperation = AddOperation;
  34931. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  34932. exports.AdditiveBlending = AdditiveBlending;
  34933. exports.AlphaFormat = AlphaFormat;
  34934. exports.AlwaysDepth = AlwaysDepth;
  34935. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  34936. exports.AmbientLight = AmbientLight;
  34937. exports.AmbientLightProbe = AmbientLightProbe;
  34938. exports.AnimationClip = AnimationClip;
  34939. exports.AnimationLoader = AnimationLoader;
  34940. exports.AnimationMixer = AnimationMixer;
  34941. exports.AnimationObjectGroup = AnimationObjectGroup;
  34942. exports.AnimationUtils = AnimationUtils;
  34943. exports.ArcCurve = ArcCurve;
  34944. exports.ArrayCamera = ArrayCamera;
  34945. exports.ArrowHelper = ArrowHelper;
  34946. exports.Audio = Audio;
  34947. exports.AudioAnalyser = AudioAnalyser;
  34948. exports.AudioContext = AudioContext;
  34949. exports.AudioListener = AudioListener;
  34950. exports.AudioLoader = AudioLoader;
  34951. exports.AxesHelper = AxesHelper;
  34952. exports.AxisHelper = AxisHelper;
  34953. exports.BackSide = BackSide;
  34954. exports.BasicDepthPacking = BasicDepthPacking;
  34955. exports.BasicShadowMap = BasicShadowMap;
  34956. exports.BinaryTextureLoader = BinaryTextureLoader;
  34957. exports.Bone = Bone;
  34958. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  34959. exports.BoundingBoxHelper = BoundingBoxHelper;
  34960. exports.Box2 = Box2;
  34961. exports.Box3 = Box3;
  34962. exports.Box3Helper = Box3Helper;
  34963. exports.BoxBufferGeometry = BoxGeometry;
  34964. exports.BoxGeometry = BoxGeometry;
  34965. exports.BoxHelper = BoxHelper;
  34966. exports.BufferAttribute = BufferAttribute;
  34967. exports.BufferGeometry = BufferGeometry;
  34968. exports.BufferGeometryLoader = BufferGeometryLoader;
  34969. exports.ByteType = ByteType;
  34970. exports.Cache = Cache;
  34971. exports.Camera = Camera;
  34972. exports.CameraHelper = CameraHelper;
  34973. exports.CanvasRenderer = CanvasRenderer;
  34974. exports.CanvasTexture = CanvasTexture;
  34975. exports.CatmullRomCurve3 = CatmullRomCurve3;
  34976. exports.CineonToneMapping = CineonToneMapping;
  34977. exports.CircleBufferGeometry = CircleGeometry;
  34978. exports.CircleGeometry = CircleGeometry;
  34979. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  34980. exports.Clock = Clock;
  34981. exports.Color = Color;
  34982. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  34983. exports.CompressedTexture = CompressedTexture;
  34984. exports.CompressedTextureLoader = CompressedTextureLoader;
  34985. exports.ConeBufferGeometry = ConeGeometry;
  34986. exports.ConeGeometry = ConeGeometry;
  34987. exports.CubeCamera = CubeCamera;
  34988. exports.CubeReflectionMapping = CubeReflectionMapping;
  34989. exports.CubeRefractionMapping = CubeRefractionMapping;
  34990. exports.CubeTexture = CubeTexture;
  34991. exports.CubeTextureLoader = CubeTextureLoader;
  34992. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  34993. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  34994. exports.CubicBezierCurve = CubicBezierCurve;
  34995. exports.CubicBezierCurve3 = CubicBezierCurve3;
  34996. exports.CubicInterpolant = CubicInterpolant;
  34997. exports.CullFaceBack = CullFaceBack;
  34998. exports.CullFaceFront = CullFaceFront;
  34999. exports.CullFaceFrontBack = CullFaceFrontBack;
  35000. exports.CullFaceNone = CullFaceNone;
  35001. exports.Curve = Curve;
  35002. exports.CurvePath = CurvePath;
  35003. exports.CustomBlending = CustomBlending;
  35004. exports.CustomToneMapping = CustomToneMapping;
  35005. exports.CylinderBufferGeometry = CylinderGeometry;
  35006. exports.CylinderGeometry = CylinderGeometry;
  35007. exports.Cylindrical = Cylindrical;
  35008. exports.DataTexture = DataTexture;
  35009. exports.DataTexture2DArray = DataTexture2DArray;
  35010. exports.DataTexture3D = DataTexture3D;
  35011. exports.DataTextureLoader = DataTextureLoader;
  35012. exports.DataUtils = DataUtils;
  35013. exports.DecrementStencilOp = DecrementStencilOp;
  35014. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  35015. exports.DefaultLoadingManager = DefaultLoadingManager;
  35016. exports.DepthFormat = DepthFormat;
  35017. exports.DepthStencilFormat = DepthStencilFormat;
  35018. exports.DepthTexture = DepthTexture;
  35019. exports.DirectionalLight = DirectionalLight;
  35020. exports.DirectionalLightHelper = DirectionalLightHelper;
  35021. exports.DiscreteInterpolant = DiscreteInterpolant;
  35022. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  35023. exports.DodecahedronGeometry = DodecahedronGeometry;
  35024. exports.DoubleSide = DoubleSide;
  35025. exports.DstAlphaFactor = DstAlphaFactor;
  35026. exports.DstColorFactor = DstColorFactor;
  35027. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  35028. exports.DynamicCopyUsage = DynamicCopyUsage;
  35029. exports.DynamicDrawUsage = DynamicDrawUsage;
  35030. exports.DynamicReadUsage = DynamicReadUsage;
  35031. exports.EdgesGeometry = EdgesGeometry;
  35032. exports.EdgesHelper = EdgesHelper;
  35033. exports.EllipseCurve = EllipseCurve;
  35034. exports.EqualDepth = EqualDepth;
  35035. exports.EqualStencilFunc = EqualStencilFunc;
  35036. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  35037. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  35038. exports.Euler = Euler;
  35039. exports.EventDispatcher = EventDispatcher;
  35040. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  35041. exports.ExtrudeGeometry = ExtrudeGeometry;
  35042. exports.FaceColors = FaceColors;
  35043. exports.FileLoader = FileLoader;
  35044. exports.FlatShading = FlatShading;
  35045. exports.Float16BufferAttribute = Float16BufferAttribute;
  35046. exports.Float32Attribute = Float32Attribute;
  35047. exports.Float32BufferAttribute = Float32BufferAttribute;
  35048. exports.Float64Attribute = Float64Attribute;
  35049. exports.Float64BufferAttribute = Float64BufferAttribute;
  35050. exports.FloatType = FloatType;
  35051. exports.Fog = Fog;
  35052. exports.FogExp2 = FogExp2;
  35053. exports.Font = Font;
  35054. exports.FontLoader = FontLoader;
  35055. exports.FrontSide = FrontSide;
  35056. exports.Frustum = Frustum;
  35057. exports.GLBufferAttribute = GLBufferAttribute;
  35058. exports.GLSL1 = GLSL1;
  35059. exports.GLSL3 = GLSL3;
  35060. exports.GammaEncoding = GammaEncoding;
  35061. exports.GreaterDepth = GreaterDepth;
  35062. exports.GreaterEqualDepth = GreaterEqualDepth;
  35063. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  35064. exports.GreaterStencilFunc = GreaterStencilFunc;
  35065. exports.GridHelper = GridHelper;
  35066. exports.Group = Group;
  35067. exports.HalfFloatType = HalfFloatType;
  35068. exports.HemisphereLight = HemisphereLight;
  35069. exports.HemisphereLightHelper = HemisphereLightHelper;
  35070. exports.HemisphereLightProbe = HemisphereLightProbe;
  35071. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  35072. exports.IcosahedronGeometry = IcosahedronGeometry;
  35073. exports.ImageBitmapLoader = ImageBitmapLoader;
  35074. exports.ImageLoader = ImageLoader;
  35075. exports.ImageUtils = ImageUtils;
  35076. exports.ImmediateRenderObject = ImmediateRenderObject;
  35077. exports.IncrementStencilOp = IncrementStencilOp;
  35078. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  35079. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  35080. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  35081. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  35082. exports.InstancedMesh = InstancedMesh;
  35083. exports.Int16Attribute = Int16Attribute;
  35084. exports.Int16BufferAttribute = Int16BufferAttribute;
  35085. exports.Int32Attribute = Int32Attribute;
  35086. exports.Int32BufferAttribute = Int32BufferAttribute;
  35087. exports.Int8Attribute = Int8Attribute;
  35088. exports.Int8BufferAttribute = Int8BufferAttribute;
  35089. exports.IntType = IntType;
  35090. exports.InterleavedBuffer = InterleavedBuffer;
  35091. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  35092. exports.Interpolant = Interpolant;
  35093. exports.InterpolateDiscrete = InterpolateDiscrete;
  35094. exports.InterpolateLinear = InterpolateLinear;
  35095. exports.InterpolateSmooth = InterpolateSmooth;
  35096. exports.InvertStencilOp = InvertStencilOp;
  35097. exports.JSONLoader = JSONLoader;
  35098. exports.KeepStencilOp = KeepStencilOp;
  35099. exports.KeyframeTrack = KeyframeTrack;
  35100. exports.LOD = LOD;
  35101. exports.LatheBufferGeometry = LatheGeometry;
  35102. exports.LatheGeometry = LatheGeometry;
  35103. exports.Layers = Layers;
  35104. exports.LensFlare = LensFlare;
  35105. exports.LessDepth = LessDepth;
  35106. exports.LessEqualDepth = LessEqualDepth;
  35107. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  35108. exports.LessStencilFunc = LessStencilFunc;
  35109. exports.Light = Light;
  35110. exports.LightProbe = LightProbe;
  35111. exports.Line = Line;
  35112. exports.Line3 = Line3;
  35113. exports.LineBasicMaterial = LineBasicMaterial;
  35114. exports.LineCurve = LineCurve;
  35115. exports.LineCurve3 = LineCurve3;
  35116. exports.LineDashedMaterial = LineDashedMaterial;
  35117. exports.LineLoop = LineLoop;
  35118. exports.LinePieces = LinePieces;
  35119. exports.LineSegments = LineSegments;
  35120. exports.LineStrip = LineStrip;
  35121. exports.LinearEncoding = LinearEncoding;
  35122. exports.LinearFilter = LinearFilter;
  35123. exports.LinearInterpolant = LinearInterpolant;
  35124. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  35125. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  35126. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  35127. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  35128. exports.LinearToneMapping = LinearToneMapping;
  35129. exports.Loader = Loader;
  35130. exports.LoaderUtils = LoaderUtils;
  35131. exports.LoadingManager = LoadingManager;
  35132. exports.LogLuvEncoding = LogLuvEncoding;
  35133. exports.LoopOnce = LoopOnce;
  35134. exports.LoopPingPong = LoopPingPong;
  35135. exports.LoopRepeat = LoopRepeat;
  35136. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  35137. exports.LuminanceFormat = LuminanceFormat;
  35138. exports.MOUSE = MOUSE;
  35139. exports.Material = Material;
  35140. exports.MaterialLoader = MaterialLoader;
  35141. exports.Math = MathUtils;
  35142. exports.MathUtils = MathUtils;
  35143. exports.Matrix3 = Matrix3;
  35144. exports.Matrix4 = Matrix4;
  35145. exports.MaxEquation = MaxEquation;
  35146. exports.Mesh = Mesh;
  35147. exports.MeshBasicMaterial = MeshBasicMaterial;
  35148. exports.MeshDepthMaterial = MeshDepthMaterial;
  35149. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  35150. exports.MeshFaceMaterial = MeshFaceMaterial;
  35151. exports.MeshLambertMaterial = MeshLambertMaterial;
  35152. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  35153. exports.MeshNormalMaterial = MeshNormalMaterial;
  35154. exports.MeshPhongMaterial = MeshPhongMaterial;
  35155. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  35156. exports.MeshStandardMaterial = MeshStandardMaterial;
  35157. exports.MeshToonMaterial = MeshToonMaterial;
  35158. exports.MinEquation = MinEquation;
  35159. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  35160. exports.MixOperation = MixOperation;
  35161. exports.MultiMaterial = MultiMaterial;
  35162. exports.MultiplyBlending = MultiplyBlending;
  35163. exports.MultiplyOperation = MultiplyOperation;
  35164. exports.NearestFilter = NearestFilter;
  35165. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  35166. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  35167. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  35168. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  35169. exports.NeverDepth = NeverDepth;
  35170. exports.NeverStencilFunc = NeverStencilFunc;
  35171. exports.NoBlending = NoBlending;
  35172. exports.NoColors = NoColors;
  35173. exports.NoToneMapping = NoToneMapping;
  35174. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  35175. exports.NormalBlending = NormalBlending;
  35176. exports.NotEqualDepth = NotEqualDepth;
  35177. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  35178. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  35179. exports.Object3D = Object3D;
  35180. exports.ObjectLoader = ObjectLoader;
  35181. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  35182. exports.OctahedronBufferGeometry = OctahedronGeometry;
  35183. exports.OctahedronGeometry = OctahedronGeometry;
  35184. exports.OneFactor = OneFactor;
  35185. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  35186. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  35187. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  35188. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  35189. exports.OrthographicCamera = OrthographicCamera;
  35190. exports.PCFShadowMap = PCFShadowMap;
  35191. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  35192. exports.PMREMGenerator = PMREMGenerator;
  35193. exports.ParametricGeometry = ParametricGeometry;
  35194. exports.Particle = Particle;
  35195. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  35196. exports.ParticleSystem = ParticleSystem;
  35197. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  35198. exports.Path = Path;
  35199. exports.PerspectiveCamera = PerspectiveCamera;
  35200. exports.Plane = Plane;
  35201. exports.PlaneBufferGeometry = PlaneGeometry;
  35202. exports.PlaneGeometry = PlaneGeometry;
  35203. exports.PlaneHelper = PlaneHelper;
  35204. exports.PointCloud = PointCloud;
  35205. exports.PointCloudMaterial = PointCloudMaterial;
  35206. exports.PointLight = PointLight;
  35207. exports.PointLightHelper = PointLightHelper;
  35208. exports.Points = Points;
  35209. exports.PointsMaterial = PointsMaterial;
  35210. exports.PolarGridHelper = PolarGridHelper;
  35211. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  35212. exports.PolyhedronGeometry = PolyhedronGeometry;
  35213. exports.PositionalAudio = PositionalAudio;
  35214. exports.PropertyBinding = PropertyBinding;
  35215. exports.PropertyMixer = PropertyMixer;
  35216. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  35217. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  35218. exports.Quaternion = Quaternion;
  35219. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  35220. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  35221. exports.REVISION = REVISION;
  35222. exports.RGBADepthPacking = RGBADepthPacking;
  35223. exports.RGBAFormat = RGBAFormat;
  35224. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  35225. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  35226. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  35227. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  35228. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  35229. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  35230. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  35231. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  35232. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  35233. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  35234. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  35235. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  35236. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  35237. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  35238. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  35239. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  35240. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  35241. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  35242. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  35243. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  35244. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  35245. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  35246. exports.RGBDEncoding = RGBDEncoding;
  35247. exports.RGBEEncoding = RGBEEncoding;
  35248. exports.RGBEFormat = RGBEFormat;
  35249. exports.RGBFormat = RGBFormat;
  35250. exports.RGBIntegerFormat = RGBIntegerFormat;
  35251. exports.RGBM16Encoding = RGBM16Encoding;
  35252. exports.RGBM7Encoding = RGBM7Encoding;
  35253. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  35254. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  35255. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  35256. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  35257. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  35258. exports.RGFormat = RGFormat;
  35259. exports.RGIntegerFormat = RGIntegerFormat;
  35260. exports.RawShaderMaterial = RawShaderMaterial;
  35261. exports.Ray = Ray;
  35262. exports.Raycaster = Raycaster;
  35263. exports.RectAreaLight = RectAreaLight;
  35264. exports.RedFormat = RedFormat;
  35265. exports.RedIntegerFormat = RedIntegerFormat;
  35266. exports.ReinhardToneMapping = ReinhardToneMapping;
  35267. exports.RepeatWrapping = RepeatWrapping;
  35268. exports.ReplaceStencilOp = ReplaceStencilOp;
  35269. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  35270. exports.RingBufferGeometry = RingGeometry;
  35271. exports.RingGeometry = RingGeometry;
  35272. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  35273. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  35274. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  35275. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  35276. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  35277. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  35278. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  35279. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  35280. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  35281. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  35282. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  35283. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  35284. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  35285. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  35286. exports.Scene = Scene;
  35287. exports.SceneUtils = SceneUtils;
  35288. exports.ShaderChunk = ShaderChunk;
  35289. exports.ShaderLib = ShaderLib;
  35290. exports.ShaderMaterial = ShaderMaterial;
  35291. exports.ShadowMaterial = ShadowMaterial;
  35292. exports.Shape = Shape;
  35293. exports.ShapeBufferGeometry = ShapeGeometry;
  35294. exports.ShapeGeometry = ShapeGeometry;
  35295. exports.ShapePath = ShapePath;
  35296. exports.ShapeUtils = ShapeUtils;
  35297. exports.ShortType = ShortType;
  35298. exports.Skeleton = Skeleton;
  35299. exports.SkeletonHelper = SkeletonHelper;
  35300. exports.SkinnedMesh = SkinnedMesh;
  35301. exports.SmoothShading = SmoothShading;
  35302. exports.Sphere = Sphere;
  35303. exports.SphereBufferGeometry = SphereGeometry;
  35304. exports.SphereGeometry = SphereGeometry;
  35305. exports.Spherical = Spherical;
  35306. exports.SphericalHarmonics3 = SphericalHarmonics3;
  35307. exports.SplineCurve = SplineCurve;
  35308. exports.SpotLight = SpotLight;
  35309. exports.SpotLightHelper = SpotLightHelper;
  35310. exports.Sprite = Sprite;
  35311. exports.SpriteMaterial = SpriteMaterial;
  35312. exports.SrcAlphaFactor = SrcAlphaFactor;
  35313. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  35314. exports.SrcColorFactor = SrcColorFactor;
  35315. exports.StaticCopyUsage = StaticCopyUsage;
  35316. exports.StaticDrawUsage = StaticDrawUsage;
  35317. exports.StaticReadUsage = StaticReadUsage;
  35318. exports.StereoCamera = StereoCamera;
  35319. exports.StreamCopyUsage = StreamCopyUsage;
  35320. exports.StreamDrawUsage = StreamDrawUsage;
  35321. exports.StreamReadUsage = StreamReadUsage;
  35322. exports.StringKeyframeTrack = StringKeyframeTrack;
  35323. exports.SubtractEquation = SubtractEquation;
  35324. exports.SubtractiveBlending = SubtractiveBlending;
  35325. exports.TOUCH = TOUCH;
  35326. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  35327. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  35328. exports.TetrahedronGeometry = TetrahedronGeometry;
  35329. exports.TextGeometry = TextGeometry;
  35330. exports.Texture = Texture;
  35331. exports.TextureLoader = TextureLoader;
  35332. exports.TorusBufferGeometry = TorusGeometry;
  35333. exports.TorusGeometry = TorusGeometry;
  35334. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  35335. exports.TorusKnotGeometry = TorusKnotGeometry;
  35336. exports.Triangle = Triangle;
  35337. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  35338. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  35339. exports.TrianglesDrawMode = TrianglesDrawMode;
  35340. exports.TubeBufferGeometry = TubeGeometry;
  35341. exports.TubeGeometry = TubeGeometry;
  35342. exports.UVMapping = UVMapping;
  35343. exports.Uint16Attribute = Uint16Attribute;
  35344. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  35345. exports.Uint32Attribute = Uint32Attribute;
  35346. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  35347. exports.Uint8Attribute = Uint8Attribute;
  35348. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  35349. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  35350. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  35351. exports.Uniform = Uniform;
  35352. exports.UniformsLib = UniformsLib;
  35353. exports.UniformsUtils = UniformsUtils;
  35354. exports.UnsignedByteType = UnsignedByteType;
  35355. exports.UnsignedInt248Type = UnsignedInt248Type;
  35356. exports.UnsignedIntType = UnsignedIntType;
  35357. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  35358. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  35359. exports.UnsignedShort565Type = UnsignedShort565Type;
  35360. exports.UnsignedShortType = UnsignedShortType;
  35361. exports.VSMShadowMap = VSMShadowMap;
  35362. exports.Vector2 = Vector2;
  35363. exports.Vector3 = Vector3;
  35364. exports.Vector4 = Vector4;
  35365. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  35366. exports.Vertex = Vertex;
  35367. exports.VertexColors = VertexColors;
  35368. exports.VideoTexture = VideoTexture;
  35369. exports.WebGL1Renderer = WebGL1Renderer;
  35370. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  35371. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  35372. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  35373. exports.WebGLRenderTarget = WebGLRenderTarget;
  35374. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  35375. exports.WebGLRenderer = WebGLRenderer;
  35376. exports.WebGLUtils = WebGLUtils;
  35377. exports.WireframeGeometry = WireframeGeometry;
  35378. exports.WireframeHelper = WireframeHelper;
  35379. exports.WrapAroundEnding = WrapAroundEnding;
  35380. exports.XHRLoader = XHRLoader;
  35381. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  35382. exports.ZeroFactor = ZeroFactor;
  35383. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  35384. exports.ZeroStencilOp = ZeroStencilOp;
  35385. exports.sRGBEncoding = sRGBEncoding;
  35386. Object.defineProperty(exports, '__esModule', { value: true });
  35387. })));
  35388. },{}],58:[function(require,module,exports){
  35389. ( function () {
  35390. class LightProbeGenerator {
  35391. // https://www.ppsloan.org/publications/StupidSH36.pdf
  35392. static fromCubeTexture( cubeTexture ) {
  35393. let totalWeight = 0;
  35394. const coord = new THREE.Vector3();
  35395. const dir = new THREE.Vector3();
  35396. const color = new THREE.Color();
  35397. const shBasis = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  35398. const sh = new THREE.SphericalHarmonics3();
  35399. const shCoefficients = sh.coefficients;
  35400. for ( let faceIndex = 0; faceIndex < 6; faceIndex ++ ) {
  35401. const image = cubeTexture.image[ faceIndex ];
  35402. const width = image.width;
  35403. const height = image.height;
  35404. const canvas = document.createElement( 'canvas' );
  35405. canvas.width = width;
  35406. canvas.height = height;
  35407. const context = canvas.getContext( '2d' );
  35408. context.drawImage( image, 0, 0, width, height );
  35409. const imageData = context.getImageData( 0, 0, width, height );
  35410. const data = imageData.data;
  35411. const imageWidth = imageData.width; // assumed to be square
  35412. const pixelSize = 2 / imageWidth;
  35413. for ( let i = 0, il = data.length; i < il; i += 4 ) {
  35414. // RGBA assumed
  35415. // pixel color
  35416. color.setRGB( data[ i ] / 255, data[ i + 1 ] / 255, data[ i + 2 ] / 255 ); // convert to linear color space
  35417. convertColorToLinear( color, cubeTexture.encoding ); // pixel coordinate on unit cube
  35418. const pixelIndex = i / 4;
  35419. const col = - 1 + ( pixelIndex % imageWidth + 0.5 ) * pixelSize;
  35420. const row = 1 - ( Math.floor( pixelIndex / imageWidth ) + 0.5 ) * pixelSize;
  35421. switch ( faceIndex ) {
  35422. case 0:
  35423. coord.set( - 1, row, - col );
  35424. break;
  35425. case 1:
  35426. coord.set( 1, row, col );
  35427. break;
  35428. case 2:
  35429. coord.set( - col, 1, - row );
  35430. break;
  35431. case 3:
  35432. coord.set( - col, - 1, row );
  35433. break;
  35434. case 4:
  35435. coord.set( - col, row, 1 );
  35436. break;
  35437. case 5:
  35438. coord.set( col, row, - 1 );
  35439. break;
  35440. } // weight assigned to this pixel
  35441. const lengthSq = coord.lengthSq();
  35442. const weight = 4 / ( Math.sqrt( lengthSq ) * lengthSq );
  35443. totalWeight += weight; // direction vector to this pixel
  35444. dir.copy( coord ).normalize(); // evaluate SH basis functions in direction dir
  35445. THREE.SphericalHarmonics3.getBasisAt( dir, shBasis ); // accummuulate
  35446. for ( let j = 0; j < 9; j ++ ) {
  35447. shCoefficients[ j ].x += shBasis[ j ] * color.r * weight;
  35448. shCoefficients[ j ].y += shBasis[ j ] * color.g * weight;
  35449. shCoefficients[ j ].z += shBasis[ j ] * color.b * weight;
  35450. }
  35451. }
  35452. } // normalize
  35453. const norm = 4 * Math.PI / totalWeight;
  35454. for ( let j = 0; j < 9; j ++ ) {
  35455. shCoefficients[ j ].x *= norm;
  35456. shCoefficients[ j ].y *= norm;
  35457. shCoefficients[ j ].z *= norm;
  35458. }
  35459. return new THREE.LightProbe( sh );
  35460. }
  35461. static fromCubeRenderTarget( renderer, cubeRenderTarget ) {
  35462. // The renderTarget must be set to RGBA in order to make readRenderTargetPixels works
  35463. let totalWeight = 0;
  35464. const coord = new THREE.Vector3();
  35465. const dir = new THREE.Vector3();
  35466. const color = new THREE.Color();
  35467. const shBasis = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  35468. const sh = new THREE.SphericalHarmonics3();
  35469. const shCoefficients = sh.coefficients;
  35470. for ( let faceIndex = 0; faceIndex < 6; faceIndex ++ ) {
  35471. const imageWidth = cubeRenderTarget.width; // assumed to be square
  35472. const data = new Uint8Array( imageWidth * imageWidth * 4 );
  35473. renderer.readRenderTargetPixels( cubeRenderTarget, 0, 0, imageWidth, imageWidth, data, faceIndex );
  35474. const pixelSize = 2 / imageWidth;
  35475. for ( let i = 0, il = data.length; i < il; i += 4 ) {
  35476. // RGBA assumed
  35477. // pixel color
  35478. color.setRGB( data[ i ] / 255, data[ i + 1 ] / 255, data[ i + 2 ] / 255 ); // convert to linear color space
  35479. convertColorToLinear( color, cubeRenderTarget.texture.encoding ); // pixel coordinate on unit cube
  35480. const pixelIndex = i / 4;
  35481. const col = - 1 + ( pixelIndex % imageWidth + 0.5 ) * pixelSize;
  35482. const row = 1 - ( Math.floor( pixelIndex / imageWidth ) + 0.5 ) * pixelSize;
  35483. switch ( faceIndex ) {
  35484. case 0:
  35485. coord.set( 1, row, - col );
  35486. break;
  35487. case 1:
  35488. coord.set( - 1, row, col );
  35489. break;
  35490. case 2:
  35491. coord.set( col, 1, - row );
  35492. break;
  35493. case 3:
  35494. coord.set( col, - 1, row );
  35495. break;
  35496. case 4:
  35497. coord.set( col, row, 1 );
  35498. break;
  35499. case 5:
  35500. coord.set( - col, row, - 1 );
  35501. break;
  35502. } // weight assigned to this pixel
  35503. const lengthSq = coord.lengthSq();
  35504. const weight = 4 / ( Math.sqrt( lengthSq ) * lengthSq );
  35505. totalWeight += weight; // direction vector to this pixel
  35506. dir.copy( coord ).normalize(); // evaluate SH basis functions in direction dir
  35507. THREE.SphericalHarmonics3.getBasisAt( dir, shBasis ); // accummuulate
  35508. for ( let j = 0; j < 9; j ++ ) {
  35509. shCoefficients[ j ].x += shBasis[ j ] * color.r * weight;
  35510. shCoefficients[ j ].y += shBasis[ j ] * color.g * weight;
  35511. shCoefficients[ j ].z += shBasis[ j ] * color.b * weight;
  35512. }
  35513. }
  35514. } // normalize
  35515. const norm = 4 * Math.PI / totalWeight;
  35516. for ( let j = 0; j < 9; j ++ ) {
  35517. shCoefficients[ j ].x *= norm;
  35518. shCoefficients[ j ].y *= norm;
  35519. shCoefficients[ j ].z *= norm;
  35520. }
  35521. return new THREE.LightProbe( sh );
  35522. }
  35523. }
  35524. function convertColorToLinear( color, encoding ) {
  35525. switch ( encoding ) {
  35526. case THREE.sRGBEncoding:
  35527. color.convertSRGBToLinear();
  35528. break;
  35529. case THREE.LinearEncoding:
  35530. break;
  35531. default:
  35532. console.warn( 'WARNING: LightProbeGenerator convertColorToLinear() encountered an unsupported encoding.' );
  35533. break;
  35534. }
  35535. return color;
  35536. }
  35537. THREE.LightProbeGenerator = LightProbeGenerator;
  35538. } )();
  35539. },{}],59:[function(require,module,exports){
  35540. ( function () {
  35541. const _taskCache = new WeakMap();
  35542. class DRACOLoader extends THREE.Loader {
  35543. constructor( manager ) {
  35544. super( manager );
  35545. this.decoderPath = '';
  35546. this.decoderConfig = {};
  35547. this.decoderBinary = null;
  35548. this.decoderPending = null;
  35549. this.workerLimit = 4;
  35550. this.workerPool = [];
  35551. this.workerNextTaskID = 1;
  35552. this.workerSourceURL = '';
  35553. this.defaultAttributeIDs = {
  35554. position: 'POSITION',
  35555. normal: 'NORMAL',
  35556. color: 'COLOR',
  35557. uv: 'TEX_COORD'
  35558. };
  35559. this.defaultAttributeTypes = {
  35560. position: 'Float32Array',
  35561. normal: 'Float32Array',
  35562. color: 'Float32Array',
  35563. uv: 'Float32Array'
  35564. };
  35565. }
  35566. setDecoderPath( path ) {
  35567. this.decoderPath = path;
  35568. return this;
  35569. }
  35570. setDecoderConfig( config ) {
  35571. this.decoderConfig = config;
  35572. return this;
  35573. }
  35574. setWorkerLimit( workerLimit ) {
  35575. this.workerLimit = workerLimit;
  35576. return this;
  35577. }
  35578. load( url, onLoad, onProgress, onError ) {
  35579. const loader = new THREE.FileLoader( this.manager );
  35580. loader.setPath( this.path );
  35581. loader.setResponseType( 'arraybuffer' );
  35582. loader.setRequestHeader( this.requestHeader );
  35583. loader.setWithCredentials( this.withCredentials );
  35584. loader.load( url, buffer => {
  35585. const taskConfig = {
  35586. attributeIDs: this.defaultAttributeIDs,
  35587. attributeTypes: this.defaultAttributeTypes,
  35588. useUniqueIDs: false
  35589. };
  35590. this.decodeGeometry( buffer, taskConfig ).then( onLoad ).catch( onError );
  35591. }, onProgress, onError );
  35592. }
  35593. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  35594. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  35595. const taskConfig = {
  35596. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  35597. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  35598. useUniqueIDs: !! attributeIDs
  35599. };
  35600. this.decodeGeometry( buffer, taskConfig ).then( callback );
  35601. }
  35602. decodeGeometry( buffer, taskConfig ) {
  35603. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  35604. // references (rather than names) to typed array constructors. These must be
  35605. // serialized before sending them to the worker.
  35606. for ( const attribute in taskConfig.attributeTypes ) {
  35607. const type = taskConfig.attributeTypes[ attribute ];
  35608. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  35609. taskConfig.attributeTypes[ attribute ] = type.name;
  35610. }
  35611. } //
  35612. const taskKey = JSON.stringify( taskConfig ); // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  35613. // again from this thread.
  35614. if ( _taskCache.has( buffer ) ) {
  35615. const cachedTask = _taskCache.get( buffer );
  35616. if ( cachedTask.key === taskKey ) {
  35617. return cachedTask.promise;
  35618. } else if ( buffer.byteLength === 0 ) {
  35619. // Technically, it would be possible to wait for the previous task to complete,
  35620. // transfer the buffer back, and decode again with the second configuration. That
  35621. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  35622. // different ways, so this is left unimplemented.
  35623. throw new Error( 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.' );
  35624. }
  35625. } //
  35626. let worker;
  35627. const taskID = this.workerNextTaskID ++;
  35628. const taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance
  35629. // when the task completes.
  35630. const geometryPending = this._getWorker( taskID, taskCost ).then( _worker => {
  35631. worker = _worker;
  35632. return new Promise( ( resolve, reject ) => {
  35633. worker._callbacks[ taskID ] = {
  35634. resolve,
  35635. reject
  35636. };
  35637. worker.postMessage( {
  35638. type: 'decode',
  35639. id: taskID,
  35640. taskConfig,
  35641. buffer
  35642. }, [ buffer ] ); // this.debug();
  35643. } );
  35644. } ).then( message => this._createGeometry( message.geometry ) ); // Remove task from the task list.
  35645. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  35646. geometryPending.catch( () => true ).then( () => {
  35647. if ( worker && taskID ) {
  35648. this._releaseTask( worker, taskID ); // this.debug();
  35649. }
  35650. } ); // Cache the task result.
  35651. _taskCache.set( buffer, {
  35652. key: taskKey,
  35653. promise: geometryPending
  35654. } );
  35655. return geometryPending;
  35656. }
  35657. _createGeometry( geometryData ) {
  35658. const geometry = new THREE.BufferGeometry();
  35659. if ( geometryData.index ) {
  35660. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  35661. }
  35662. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  35663. const attribute = geometryData.attributes[ i ];
  35664. const name = attribute.name;
  35665. const array = attribute.array;
  35666. const itemSize = attribute.itemSize;
  35667. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  35668. }
  35669. return geometry;
  35670. }
  35671. _loadLibrary( url, responseType ) {
  35672. const loader = new THREE.FileLoader( this.manager );
  35673. loader.setPath( this.decoderPath );
  35674. loader.setResponseType( responseType );
  35675. loader.setWithCredentials( this.withCredentials );
  35676. return new Promise( ( resolve, reject ) => {
  35677. loader.load( url, resolve, undefined, reject );
  35678. } );
  35679. }
  35680. preload() {
  35681. this._initDecoder();
  35682. return this;
  35683. }
  35684. _initDecoder() {
  35685. if ( this.decoderPending ) return this.decoderPending;
  35686. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  35687. const librariesPending = [];
  35688. if ( useJS ) {
  35689. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  35690. } else {
  35691. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  35692. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  35693. }
  35694. this.decoderPending = Promise.all( librariesPending ).then( libraries => {
  35695. const jsContent = libraries[ 0 ];
  35696. if ( ! useJS ) {
  35697. this.decoderConfig.wasmBinary = libraries[ 1 ];
  35698. }
  35699. const fn = DRACOWorker.toString();
  35700. const body = [ '/* draco decoder */', jsContent, '', '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' );
  35701. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  35702. } );
  35703. return this.decoderPending;
  35704. }
  35705. _getWorker( taskID, taskCost ) {
  35706. return this._initDecoder().then( () => {
  35707. if ( this.workerPool.length < this.workerLimit ) {
  35708. const worker = new Worker( this.workerSourceURL );
  35709. worker._callbacks = {};
  35710. worker._taskCosts = {};
  35711. worker._taskLoad = 0;
  35712. worker.postMessage( {
  35713. type: 'init',
  35714. decoderConfig: this.decoderConfig
  35715. } );
  35716. worker.onmessage = function ( e ) {
  35717. const message = e.data;
  35718. switch ( message.type ) {
  35719. case 'decode':
  35720. worker._callbacks[ message.id ].resolve( message );
  35721. break;
  35722. case 'error':
  35723. worker._callbacks[ message.id ].reject( message );
  35724. break;
  35725. default:
  35726. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  35727. }
  35728. };
  35729. this.workerPool.push( worker );
  35730. } else {
  35731. this.workerPool.sort( function ( a, b ) {
  35732. return a._taskLoad > b._taskLoad ? - 1 : 1;
  35733. } );
  35734. }
  35735. const worker = this.workerPool[ this.workerPool.length - 1 ];
  35736. worker._taskCosts[ taskID ] = taskCost;
  35737. worker._taskLoad += taskCost;
  35738. return worker;
  35739. } );
  35740. }
  35741. _releaseTask( worker, taskID ) {
  35742. worker._taskLoad -= worker._taskCosts[ taskID ];
  35743. delete worker._callbacks[ taskID ];
  35744. delete worker._taskCosts[ taskID ];
  35745. }
  35746. debug() {
  35747. console.log( 'Task load: ', this.workerPool.map( worker => worker._taskLoad ) );
  35748. }
  35749. dispose() {
  35750. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  35751. this.workerPool[ i ].terminate();
  35752. }
  35753. this.workerPool.length = 0;
  35754. return this;
  35755. }
  35756. }
  35757. /* WEB WORKER */
  35758. function DRACOWorker() {
  35759. let decoderConfig;
  35760. let decoderPending;
  35761. onmessage = function ( e ) {
  35762. const message = e.data;
  35763. switch ( message.type ) {
  35764. case 'init':
  35765. decoderConfig = message.decoderConfig;
  35766. decoderPending = new Promise( function ( resolve
  35767. /*, reject*/
  35768. ) {
  35769. decoderConfig.onModuleLoaded = function ( draco ) {
  35770. // Module is Promise-like. Wrap before resolving to avoid loop.
  35771. resolve( {
  35772. draco: draco
  35773. } );
  35774. };
  35775. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  35776. } );
  35777. break;
  35778. case 'decode':
  35779. const buffer = message.buffer;
  35780. const taskConfig = message.taskConfig;
  35781. decoderPending.then( module => {
  35782. const draco = module.draco;
  35783. const decoder = new draco.Decoder();
  35784. const decoderBuffer = new draco.DecoderBuffer();
  35785. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  35786. try {
  35787. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  35788. const buffers = geometry.attributes.map( attr => attr.array.buffer );
  35789. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  35790. self.postMessage( {
  35791. type: 'decode',
  35792. id: message.id,
  35793. geometry
  35794. }, buffers );
  35795. } catch ( error ) {
  35796. console.error( error );
  35797. self.postMessage( {
  35798. type: 'error',
  35799. id: message.id,
  35800. error: error.message
  35801. } );
  35802. } finally {
  35803. draco.destroy( decoderBuffer );
  35804. draco.destroy( decoder );
  35805. }
  35806. } );
  35807. break;
  35808. }
  35809. };
  35810. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  35811. const attributeIDs = taskConfig.attributeIDs;
  35812. const attributeTypes = taskConfig.attributeTypes;
  35813. let dracoGeometry;
  35814. let decodingStatus;
  35815. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  35816. if ( geometryType === draco.TRIANGULAR_MESH ) {
  35817. dracoGeometry = new draco.Mesh();
  35818. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  35819. } else if ( geometryType === draco.POINT_CLOUD ) {
  35820. dracoGeometry = new draco.PointCloud();
  35821. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  35822. } else {
  35823. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  35824. }
  35825. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  35826. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  35827. }
  35828. const geometry = {
  35829. index: null,
  35830. attributes: []
  35831. }; // Gather all vertex attributes.
  35832. for ( const attributeName in attributeIDs ) {
  35833. const attributeType = self[ attributeTypes[ attributeName ] ];
  35834. let attribute;
  35835. let attributeID; // A Draco file may be created with default vertex attributes, whose attribute IDs
  35836. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  35837. // a Draco file may contain a custom set of attributes, identified by known unique
  35838. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  35839. if ( taskConfig.useUniqueIDs ) {
  35840. attributeID = attributeIDs[ attributeName ];
  35841. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  35842. } else {
  35843. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  35844. if ( attributeID === - 1 ) continue;
  35845. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  35846. }
  35847. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  35848. } // Add index.
  35849. if ( geometryType === draco.TRIANGULAR_MESH ) {
  35850. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  35851. }
  35852. draco.destroy( dracoGeometry );
  35853. return geometry;
  35854. }
  35855. function decodeIndex( draco, decoder, dracoGeometry ) {
  35856. const numFaces = dracoGeometry.num_faces();
  35857. const numIndices = numFaces * 3;
  35858. const byteLength = numIndices * 4;
  35859. const ptr = draco._malloc( byteLength );
  35860. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  35861. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  35862. draco._free( ptr );
  35863. return {
  35864. array: index,
  35865. itemSize: 1
  35866. };
  35867. }
  35868. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  35869. const numComponents = attribute.num_components();
  35870. const numPoints = dracoGeometry.num_points();
  35871. const numValues = numPoints * numComponents;
  35872. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  35873. const dataType = getDracoDataType( draco, attributeType );
  35874. const ptr = draco._malloc( byteLength );
  35875. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  35876. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  35877. draco._free( ptr );
  35878. return {
  35879. name: attributeName,
  35880. array: array,
  35881. itemSize: numComponents
  35882. };
  35883. }
  35884. function getDracoDataType( draco, attributeType ) {
  35885. switch ( attributeType ) {
  35886. case Float32Array:
  35887. return draco.DT_FLOAT32;
  35888. case Int8Array:
  35889. return draco.DT_INT8;
  35890. case Int16Array:
  35891. return draco.DT_INT16;
  35892. case Int32Array:
  35893. return draco.DT_INT32;
  35894. case Uint8Array:
  35895. return draco.DT_UINT8;
  35896. case Uint16Array:
  35897. return draco.DT_UINT16;
  35898. case Uint32Array:
  35899. return draco.DT_UINT32;
  35900. }
  35901. }
  35902. }
  35903. THREE.DRACOLoader = DRACOLoader;
  35904. } )();
  35905. },{}],60:[function(require,module,exports){
  35906. ( function () {
  35907. class GLTFLoader extends THREE.Loader {
  35908. constructor( manager ) {
  35909. super( manager );
  35910. this.dracoLoader = null;
  35911. this.ktx2Loader = null;
  35912. this.meshoptDecoder = null;
  35913. this.pluginCallbacks = [];
  35914. this.register( function ( parser ) {
  35915. return new GLTFMaterialsClearcoatExtension( parser );
  35916. } );
  35917. this.register( function ( parser ) {
  35918. return new GLTFTextureBasisUExtension( parser );
  35919. } );
  35920. this.register( function ( parser ) {
  35921. return new GLTFTextureWebPExtension( parser );
  35922. } );
  35923. this.register( function ( parser ) {
  35924. return new GLTFMaterialsTransmissionExtension( parser );
  35925. } );
  35926. this.register( function ( parser ) {
  35927. return new GLTFMaterialsVolumeExtension( parser );
  35928. } );
  35929. this.register( function ( parser ) {
  35930. return new GLTFMaterialsIorExtension( parser );
  35931. } );
  35932. this.register( function ( parser ) {
  35933. return new GLTFMaterialsSpecularExtension( parser );
  35934. } );
  35935. this.register( function ( parser ) {
  35936. return new GLTFLightsExtension( parser );
  35937. } );
  35938. this.register( function ( parser ) {
  35939. return new GLTFMeshoptCompression( parser );
  35940. } );
  35941. }
  35942. load( url, onLoad, onProgress, onError ) {
  35943. const scope = this;
  35944. let resourcePath;
  35945. if ( this.resourcePath !== '' ) {
  35946. resourcePath = this.resourcePath;
  35947. } else if ( this.path !== '' ) {
  35948. resourcePath = this.path;
  35949. } else {
  35950. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  35951. } // Tells the LoadingManager to track an extra item, which resolves after
  35952. // the model is fully loaded. This means the count of items loaded will
  35953. // be incorrect, but ensures manager.onLoad() does not fire early.
  35954. this.manager.itemStart( url );
  35955. const _onError = function ( e ) {
  35956. if ( onError ) {
  35957. onError( e );
  35958. } else {
  35959. console.error( e );
  35960. }
  35961. scope.manager.itemError( url );
  35962. scope.manager.itemEnd( url );
  35963. };
  35964. const loader = new THREE.FileLoader( this.manager );
  35965. loader.setPath( this.path );
  35966. loader.setResponseType( 'arraybuffer' );
  35967. loader.setRequestHeader( this.requestHeader );
  35968. loader.setWithCredentials( this.withCredentials );
  35969. loader.load( url, function ( data ) {
  35970. try {
  35971. scope.parse( data, resourcePath, function ( gltf ) {
  35972. onLoad( gltf );
  35973. scope.manager.itemEnd( url );
  35974. }, _onError );
  35975. } catch ( e ) {
  35976. _onError( e );
  35977. }
  35978. }, onProgress, _onError );
  35979. }
  35980. setDRACOLoader( dracoLoader ) {
  35981. this.dracoLoader = dracoLoader;
  35982. return this;
  35983. }
  35984. setDDSLoader() {
  35985. throw new Error( 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' );
  35986. }
  35987. setKTX2Loader( ktx2Loader ) {
  35988. this.ktx2Loader = ktx2Loader;
  35989. return this;
  35990. }
  35991. setMeshoptDecoder( meshoptDecoder ) {
  35992. this.meshoptDecoder = meshoptDecoder;
  35993. return this;
  35994. }
  35995. register( callback ) {
  35996. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  35997. this.pluginCallbacks.push( callback );
  35998. }
  35999. return this;
  36000. }
  36001. unregister( callback ) {
  36002. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  36003. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  36004. }
  36005. return this;
  36006. }
  36007. parse( data, path, onLoad, onError ) {
  36008. let content;
  36009. const extensions = {};
  36010. const plugins = {};
  36011. if ( typeof data === 'string' ) {
  36012. content = data;
  36013. } else {
  36014. const magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  36015. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  36016. try {
  36017. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  36018. } catch ( error ) {
  36019. if ( onError ) onError( error );
  36020. return;
  36021. }
  36022. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36023. } else {
  36024. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  36025. }
  36026. }
  36027. const json = JSON.parse( content );
  36028. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  36029. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  36030. return;
  36031. }
  36032. const parser = new GLTFParser( json, {
  36033. path: path || this.resourcePath || '',
  36034. crossOrigin: this.crossOrigin,
  36035. requestHeader: this.requestHeader,
  36036. manager: this.manager,
  36037. ktx2Loader: this.ktx2Loader,
  36038. meshoptDecoder: this.meshoptDecoder
  36039. } );
  36040. parser.fileLoader.setRequestHeader( this.requestHeader );
  36041. for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
  36042. const plugin = this.pluginCallbacks[ i ]( parser );
  36043. plugins[ plugin.name ] = plugin; // Workaround to avoid determining as unknown extension
  36044. // in addUnknownExtensionsToUserData().
  36045. // Remove this workaround if we move all the existing
  36046. // extension handlers to plugin system
  36047. extensions[ plugin.name ] = true;
  36048. }
  36049. if ( json.extensionsUsed ) {
  36050. for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
  36051. const extensionName = json.extensionsUsed[ i ];
  36052. const extensionsRequired = json.extensionsRequired || [];
  36053. switch ( extensionName ) {
  36054. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  36055. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  36056. break;
  36057. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  36058. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  36059. break;
  36060. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  36061. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  36062. break;
  36063. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  36064. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  36065. break;
  36066. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  36067. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  36068. break;
  36069. default:
  36070. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  36071. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  36072. }
  36073. }
  36074. }
  36075. }
  36076. parser.setExtensions( extensions );
  36077. parser.setPlugins( plugins );
  36078. parser.parse( onLoad, onError );
  36079. }
  36080. }
  36081. /* GLTFREGISTRY */
  36082. function GLTFRegistry() {
  36083. let objects = {};
  36084. return {
  36085. get: function ( key ) {
  36086. return objects[ key ];
  36087. },
  36088. add: function ( key, object ) {
  36089. objects[ key ] = object;
  36090. },
  36091. remove: function ( key ) {
  36092. delete objects[ key ];
  36093. },
  36094. removeAll: function () {
  36095. objects = {};
  36096. }
  36097. };
  36098. }
  36099. /*********************************/
  36100. /********** EXTENSIONS ***********/
  36101. /*********************************/
  36102. const EXTENSIONS = {
  36103. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  36104. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  36105. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  36106. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  36107. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  36108. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  36109. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  36110. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  36111. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  36112. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  36113. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  36114. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  36115. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  36116. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  36117. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression'
  36118. };
  36119. /**
  36120. * Punctual Lights Extension
  36121. *
  36122. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  36123. */
  36124. class GLTFLightsExtension {
  36125. constructor( parser ) {
  36126. this.parser = parser;
  36127. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // THREE.Object3D instance caches
  36128. this.cache = {
  36129. refs: {},
  36130. uses: {}
  36131. };
  36132. }
  36133. _markDefs() {
  36134. const parser = this.parser;
  36135. const nodeDefs = this.parser.json.nodes || [];
  36136. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  36137. const nodeDef = nodeDefs[ nodeIndex ];
  36138. if ( nodeDef.extensions && nodeDef.extensions[ this.name ] && nodeDef.extensions[ this.name ].light !== undefined ) {
  36139. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  36140. }
  36141. }
  36142. }
  36143. _loadLight( lightIndex ) {
  36144. const parser = this.parser;
  36145. const cacheKey = 'light:' + lightIndex;
  36146. let dependency = parser.cache.get( cacheKey );
  36147. if ( dependency ) return dependency;
  36148. const json = parser.json;
  36149. const extensions = json.extensions && json.extensions[ this.name ] || {};
  36150. const lightDefs = extensions.lights || [];
  36151. const lightDef = lightDefs[ lightIndex ];
  36152. let lightNode;
  36153. const color = new THREE.Color( 0xffffff );
  36154. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  36155. const range = lightDef.range !== undefined ? lightDef.range : 0;
  36156. switch ( lightDef.type ) {
  36157. case 'directional':
  36158. lightNode = new THREE.DirectionalLight( color );
  36159. lightNode.target.position.set( 0, 0, - 1 );
  36160. lightNode.add( lightNode.target );
  36161. break;
  36162. case 'point':
  36163. lightNode = new THREE.PointLight( color );
  36164. lightNode.distance = range;
  36165. break;
  36166. case 'spot':
  36167. lightNode = new THREE.SpotLight( color );
  36168. lightNode.distance = range; // Handle spotlight properties.
  36169. lightDef.spot = lightDef.spot || {};
  36170. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  36171. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  36172. lightNode.angle = lightDef.spot.outerConeAngle;
  36173. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  36174. lightNode.target.position.set( 0, 0, - 1 );
  36175. lightNode.add( lightNode.target );
  36176. break;
  36177. default:
  36178. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  36179. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  36180. // here, because node-level parsing will only override position if explicitly specified.
  36181. lightNode.position.set( 0, 0, 0 );
  36182. lightNode.decay = 2;
  36183. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  36184. lightNode.name = parser.createUniqueName( lightDef.name || 'light_' + lightIndex );
  36185. dependency = Promise.resolve( lightNode );
  36186. parser.cache.add( cacheKey, dependency );
  36187. return dependency;
  36188. }
  36189. createNodeAttachment( nodeIndex ) {
  36190. const self = this;
  36191. const parser = this.parser;
  36192. const json = parser.json;
  36193. const nodeDef = json.nodes[ nodeIndex ];
  36194. const lightDef = nodeDef.extensions && nodeDef.extensions[ this.name ] || {};
  36195. const lightIndex = lightDef.light;
  36196. if ( lightIndex === undefined ) return null;
  36197. return this._loadLight( lightIndex ).then( function ( light ) {
  36198. return parser._getNodeRef( self.cache, lightIndex, light );
  36199. } );
  36200. }
  36201. }
  36202. /**
  36203. * Unlit Materials Extension
  36204. *
  36205. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  36206. */
  36207. class GLTFMaterialsUnlitExtension {
  36208. constructor() {
  36209. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  36210. }
  36211. getMaterialType() {
  36212. return THREE.MeshBasicMaterial;
  36213. }
  36214. extendParams( materialParams, materialDef, parser ) {
  36215. const pending = [];
  36216. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  36217. materialParams.opacity = 1.0;
  36218. const metallicRoughness = materialDef.pbrMetallicRoughness;
  36219. if ( metallicRoughness ) {
  36220. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  36221. const array = metallicRoughness.baseColorFactor;
  36222. materialParams.color.fromArray( array );
  36223. materialParams.opacity = array[ 3 ];
  36224. }
  36225. if ( metallicRoughness.baseColorTexture !== undefined ) {
  36226. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  36227. }
  36228. }
  36229. return Promise.all( pending );
  36230. }
  36231. }
  36232. /**
  36233. * Clearcoat Materials Extension
  36234. *
  36235. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  36236. */
  36237. class GLTFMaterialsClearcoatExtension {
  36238. constructor( parser ) {
  36239. this.parser = parser;
  36240. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  36241. }
  36242. getMaterialType( materialIndex ) {
  36243. const parser = this.parser;
  36244. const materialDef = parser.json.materials[ materialIndex ];
  36245. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  36246. return THREE.MeshPhysicalMaterial;
  36247. }
  36248. extendMaterialParams( materialIndex, materialParams ) {
  36249. const parser = this.parser;
  36250. const materialDef = parser.json.materials[ materialIndex ];
  36251. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  36252. return Promise.resolve();
  36253. }
  36254. const pending = [];
  36255. const extension = materialDef.extensions[ this.name ];
  36256. if ( extension.clearcoatFactor !== undefined ) {
  36257. materialParams.clearcoat = extension.clearcoatFactor;
  36258. }
  36259. if ( extension.clearcoatTexture !== undefined ) {
  36260. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  36261. }
  36262. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  36263. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  36264. }
  36265. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  36266. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  36267. }
  36268. if ( extension.clearcoatNormalTexture !== undefined ) {
  36269. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  36270. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  36271. const scale = extension.clearcoatNormalTexture.scale;
  36272. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  36273. }
  36274. }
  36275. return Promise.all( pending );
  36276. }
  36277. }
  36278. /**
  36279. * Transmission Materials Extension
  36280. *
  36281. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  36282. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  36283. */
  36284. class GLTFMaterialsTransmissionExtension {
  36285. constructor( parser ) {
  36286. this.parser = parser;
  36287. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  36288. }
  36289. getMaterialType( materialIndex ) {
  36290. const parser = this.parser;
  36291. const materialDef = parser.json.materials[ materialIndex ];
  36292. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  36293. return THREE.MeshPhysicalMaterial;
  36294. }
  36295. extendMaterialParams( materialIndex, materialParams ) {
  36296. const parser = this.parser;
  36297. const materialDef = parser.json.materials[ materialIndex ];
  36298. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  36299. return Promise.resolve();
  36300. }
  36301. const pending = [];
  36302. const extension = materialDef.extensions[ this.name ];
  36303. if ( extension.transmissionFactor !== undefined ) {
  36304. materialParams.transmission = extension.transmissionFactor;
  36305. }
  36306. if ( extension.transmissionTexture !== undefined ) {
  36307. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  36308. }
  36309. return Promise.all( pending );
  36310. }
  36311. }
  36312. /**
  36313. * Materials Volume Extension
  36314. *
  36315. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  36316. */
  36317. class GLTFMaterialsVolumeExtension {
  36318. constructor( parser ) {
  36319. this.parser = parser;
  36320. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  36321. }
  36322. getMaterialType( materialIndex ) {
  36323. const parser = this.parser;
  36324. const materialDef = parser.json.materials[ materialIndex ];
  36325. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  36326. return THREE.MeshPhysicalMaterial;
  36327. }
  36328. extendMaterialParams( materialIndex, materialParams ) {
  36329. const parser = this.parser;
  36330. const materialDef = parser.json.materials[ materialIndex ];
  36331. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  36332. return Promise.resolve();
  36333. }
  36334. const pending = [];
  36335. const extension = materialDef.extensions[ this.name ];
  36336. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
  36337. if ( extension.thicknessTexture !== undefined ) {
  36338. pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
  36339. }
  36340. materialParams.attenuationDistance = extension.attenuationDistance || 0;
  36341. const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
  36342. materialParams.attenuationTint = new THREE.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  36343. return Promise.all( pending );
  36344. }
  36345. }
  36346. /**
  36347. * Materials ior Extension
  36348. *
  36349. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  36350. */
  36351. class GLTFMaterialsIorExtension {
  36352. constructor( parser ) {
  36353. this.parser = parser;
  36354. this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  36355. }
  36356. getMaterialType( materialIndex ) {
  36357. const parser = this.parser;
  36358. const materialDef = parser.json.materials[ materialIndex ];
  36359. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  36360. return THREE.MeshPhysicalMaterial;
  36361. }
  36362. extendMaterialParams( materialIndex, materialParams ) {
  36363. const parser = this.parser;
  36364. const materialDef = parser.json.materials[ materialIndex ];
  36365. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  36366. return Promise.resolve();
  36367. }
  36368. const extension = materialDef.extensions[ this.name ];
  36369. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
  36370. return Promise.resolve();
  36371. }
  36372. }
  36373. /**
  36374. * Materials specular Extension
  36375. *
  36376. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  36377. */
  36378. class GLTFMaterialsSpecularExtension {
  36379. constructor( parser ) {
  36380. this.parser = parser;
  36381. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  36382. }
  36383. getMaterialType( materialIndex ) {
  36384. const parser = this.parser;
  36385. const materialDef = parser.json.materials[ materialIndex ];
  36386. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  36387. return THREE.MeshPhysicalMaterial;
  36388. }
  36389. extendMaterialParams( materialIndex, materialParams ) {
  36390. const parser = this.parser;
  36391. const materialDef = parser.json.materials[ materialIndex ];
  36392. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  36393. return Promise.resolve();
  36394. }
  36395. const pending = [];
  36396. const extension = materialDef.extensions[ this.name ];
  36397. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
  36398. if ( extension.specularTexture !== undefined ) {
  36399. pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
  36400. }
  36401. const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
  36402. materialParams.specularTint = new THREE.Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  36403. if ( extension.specularColorTexture !== undefined ) {
  36404. pending.push( parser.assignTexture( materialParams, 'specularTintMap', extension.specularColorTexture ).then( function ( texture ) {
  36405. texture.encoding = THREE.sRGBEncoding;
  36406. } ) );
  36407. }
  36408. return Promise.all( pending );
  36409. }
  36410. }
  36411. /**
  36412. * BasisU THREE.Texture Extension
  36413. *
  36414. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  36415. */
  36416. class GLTFTextureBasisUExtension {
  36417. constructor( parser ) {
  36418. this.parser = parser;
  36419. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  36420. }
  36421. loadTexture( textureIndex ) {
  36422. const parser = this.parser;
  36423. const json = parser.json;
  36424. const textureDef = json.textures[ textureIndex ];
  36425. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  36426. return null;
  36427. }
  36428. const extension = textureDef.extensions[ this.name ];
  36429. const source = json.images[ extension.source ];
  36430. const loader = parser.options.ktx2Loader;
  36431. if ( ! loader ) {
  36432. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  36433. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  36434. } else {
  36435. // Assumes that the extension is optional and that a fallback texture is present
  36436. return null;
  36437. }
  36438. }
  36439. return parser.loadTextureImage( textureIndex, source, loader );
  36440. }
  36441. }
  36442. /**
  36443. * WebP THREE.Texture Extension
  36444. *
  36445. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  36446. */
  36447. class GLTFTextureWebPExtension {
  36448. constructor( parser ) {
  36449. this.parser = parser;
  36450. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  36451. this.isSupported = null;
  36452. }
  36453. loadTexture( textureIndex ) {
  36454. const name = this.name;
  36455. const parser = this.parser;
  36456. const json = parser.json;
  36457. const textureDef = json.textures[ textureIndex ];
  36458. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  36459. return null;
  36460. }
  36461. const extension = textureDef.extensions[ name ];
  36462. const source = json.images[ extension.source ];
  36463. let loader = parser.textureLoader;
  36464. if ( source.uri ) {
  36465. const handler = parser.options.manager.getHandler( source.uri );
  36466. if ( handler !== null ) loader = handler;
  36467. }
  36468. return this.detectSupport().then( function ( isSupported ) {
  36469. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  36470. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  36471. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  36472. } // Fall back to PNG or JPEG.
  36473. return parser.loadTexture( textureIndex );
  36474. } );
  36475. }
  36476. detectSupport() {
  36477. if ( ! this.isSupported ) {
  36478. this.isSupported = new Promise( function ( resolve ) {
  36479. const image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all
  36480. // WebP images, unfortunately.
  36481. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  36482. image.onload = image.onerror = function () {
  36483. resolve( image.height === 1 );
  36484. };
  36485. } );
  36486. }
  36487. return this.isSupported;
  36488. }
  36489. }
  36490. /**
  36491. * meshopt BufferView Compression Extension
  36492. *
  36493. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  36494. */
  36495. class GLTFMeshoptCompression {
  36496. constructor( parser ) {
  36497. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  36498. this.parser = parser;
  36499. }
  36500. loadBufferView( index ) {
  36501. const json = this.parser.json;
  36502. const bufferView = json.bufferViews[ index ];
  36503. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  36504. const extensionDef = bufferView.extensions[ this.name ];
  36505. const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  36506. const decoder = this.parser.options.meshoptDecoder;
  36507. if ( ! decoder || ! decoder.supported ) {
  36508. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  36509. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  36510. } else {
  36511. // Assumes that the extension is optional and that fallback buffer data is present
  36512. return null;
  36513. }
  36514. }
  36515. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  36516. const byteOffset = extensionDef.byteOffset || 0;
  36517. const byteLength = extensionDef.byteLength || 0;
  36518. const count = extensionDef.count;
  36519. const stride = extensionDef.byteStride;
  36520. const result = new ArrayBuffer( count * stride );
  36521. const source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  36522. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  36523. return result;
  36524. } );
  36525. } else {
  36526. return null;
  36527. }
  36528. }
  36529. }
  36530. /* BINARY EXTENSION */
  36531. const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  36532. const BINARY_EXTENSION_HEADER_LENGTH = 12;
  36533. const BINARY_EXTENSION_CHUNK_TYPES = {
  36534. JSON: 0x4E4F534A,
  36535. BIN: 0x004E4942
  36536. };
  36537. class GLTFBinaryExtension {
  36538. constructor( data ) {
  36539. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  36540. this.content = null;
  36541. this.body = null;
  36542. const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  36543. this.header = {
  36544. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  36545. version: headerView.getUint32( 4, true ),
  36546. length: headerView.getUint32( 8, true )
  36547. };
  36548. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  36549. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  36550. } else if ( this.header.version < 2.0 ) {
  36551. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  36552. }
  36553. const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  36554. const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  36555. let chunkIndex = 0;
  36556. while ( chunkIndex < chunkContentsLength ) {
  36557. const chunkLength = chunkView.getUint32( chunkIndex, true );
  36558. chunkIndex += 4;
  36559. const chunkType = chunkView.getUint32( chunkIndex, true );
  36560. chunkIndex += 4;
  36561. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  36562. const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  36563. this.content = THREE.LoaderUtils.decodeText( contentArray );
  36564. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  36565. const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  36566. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  36567. } // Clients must ignore chunks with unknown types.
  36568. chunkIndex += chunkLength;
  36569. }
  36570. if ( this.content === null ) {
  36571. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  36572. }
  36573. }
  36574. }
  36575. /**
  36576. * DRACO THREE.Mesh Compression Extension
  36577. *
  36578. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  36579. */
  36580. class GLTFDracoMeshCompressionExtension {
  36581. constructor( json, dracoLoader ) {
  36582. if ( ! dracoLoader ) {
  36583. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  36584. }
  36585. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  36586. this.json = json;
  36587. this.dracoLoader = dracoLoader;
  36588. this.dracoLoader.preload();
  36589. }
  36590. decodePrimitive( primitive, parser ) {
  36591. const json = this.json;
  36592. const dracoLoader = this.dracoLoader;
  36593. const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  36594. const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  36595. const threeAttributeMap = {};
  36596. const attributeNormalizedMap = {};
  36597. const attributeTypeMap = {};
  36598. for ( const attributeName in gltfAttributeMap ) {
  36599. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  36600. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  36601. }
  36602. for ( const attributeName in primitive.attributes ) {
  36603. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  36604. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  36605. const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  36606. const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  36607. attributeTypeMap[ threeAttributeName ] = componentType;
  36608. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  36609. }
  36610. }
  36611. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  36612. return new Promise( function ( resolve ) {
  36613. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  36614. for ( const attributeName in geometry.attributes ) {
  36615. const attribute = geometry.attributes[ attributeName ];
  36616. const normalized = attributeNormalizedMap[ attributeName ];
  36617. if ( normalized !== undefined ) attribute.normalized = normalized;
  36618. }
  36619. resolve( geometry );
  36620. }, threeAttributeMap, attributeTypeMap );
  36621. } );
  36622. } );
  36623. }
  36624. }
  36625. /**
  36626. * THREE.Texture Transform Extension
  36627. *
  36628. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  36629. */
  36630. class GLTFTextureTransformExtension {
  36631. constructor() {
  36632. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  36633. }
  36634. extendTexture( texture, transform ) {
  36635. if ( transform.texCoord !== undefined ) {
  36636. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  36637. }
  36638. if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) {
  36639. // See https://github.com/mrdoob/three.js/issues/21819.
  36640. return texture;
  36641. }
  36642. texture = texture.clone();
  36643. if ( transform.offset !== undefined ) {
  36644. texture.offset.fromArray( transform.offset );
  36645. }
  36646. if ( transform.rotation !== undefined ) {
  36647. texture.rotation = transform.rotation;
  36648. }
  36649. if ( transform.scale !== undefined ) {
  36650. texture.repeat.fromArray( transform.scale );
  36651. }
  36652. texture.needsUpdate = true;
  36653. return texture;
  36654. }
  36655. }
  36656. /**
  36657. * Specular-Glossiness Extension
  36658. *
  36659. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  36660. */
  36661. /**
  36662. * A sub class of StandardMaterial with some of the functionality
  36663. * changed via the `onBeforeCompile` callback
  36664. * @pailhead
  36665. */
  36666. class GLTFMeshStandardSGMaterial extends THREE.MeshStandardMaterial {
  36667. constructor( params ) {
  36668. super();
  36669. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  36670. const specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' );
  36671. const glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' );
  36672. const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' );
  36673. const glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif' ].join( '\n' );
  36674. const lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.roughness += geometryRoughness;', 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;' ].join( '\n' );
  36675. const uniforms = {
  36676. specular: {
  36677. value: new THREE.Color().setHex( 0xffffff )
  36678. },
  36679. glossiness: {
  36680. value: 1
  36681. },
  36682. specularMap: {
  36683. value: null
  36684. },
  36685. glossinessMap: {
  36686. value: null
  36687. }
  36688. };
  36689. this._extraUniforms = uniforms;
  36690. this.onBeforeCompile = function ( shader ) {
  36691. for ( const uniformName in uniforms ) {
  36692. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  36693. }
  36694. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' ).replace( 'uniform float metalness;', 'uniform float glossiness;' ).replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk ).replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk ).replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk ).replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk ).replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  36695. };
  36696. Object.defineProperties( this, {
  36697. specular: {
  36698. get: function () {
  36699. return uniforms.specular.value;
  36700. },
  36701. set: function ( v ) {
  36702. uniforms.specular.value = v;
  36703. }
  36704. },
  36705. specularMap: {
  36706. get: function () {
  36707. return uniforms.specularMap.value;
  36708. },
  36709. set: function ( v ) {
  36710. uniforms.specularMap.value = v;
  36711. if ( v ) {
  36712. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  36713. } else {
  36714. delete this.defines.USE_SPECULARMAP;
  36715. }
  36716. }
  36717. },
  36718. glossiness: {
  36719. get: function () {
  36720. return uniforms.glossiness.value;
  36721. },
  36722. set: function ( v ) {
  36723. uniforms.glossiness.value = v;
  36724. }
  36725. },
  36726. glossinessMap: {
  36727. get: function () {
  36728. return uniforms.glossinessMap.value;
  36729. },
  36730. set: function ( v ) {
  36731. uniforms.glossinessMap.value = v;
  36732. if ( v ) {
  36733. this.defines.USE_GLOSSINESSMAP = '';
  36734. this.defines.USE_UV = '';
  36735. } else {
  36736. delete this.defines.USE_GLOSSINESSMAP;
  36737. delete this.defines.USE_UV;
  36738. }
  36739. }
  36740. }
  36741. } );
  36742. delete this.metalness;
  36743. delete this.roughness;
  36744. delete this.metalnessMap;
  36745. delete this.roughnessMap;
  36746. this.setValues( params );
  36747. }
  36748. copy( source ) {
  36749. super.copy( source );
  36750. this.specularMap = source.specularMap;
  36751. this.specular.copy( source.specular );
  36752. this.glossinessMap = source.glossinessMap;
  36753. this.glossiness = source.glossiness;
  36754. delete this.metalness;
  36755. delete this.roughness;
  36756. delete this.metalnessMap;
  36757. delete this.roughnessMap;
  36758. return this;
  36759. }
  36760. }
  36761. class GLTFMaterialsPbrSpecularGlossinessExtension {
  36762. constructor() {
  36763. this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS;
  36764. this.specularGlossinessParams = [ 'color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio' ];
  36765. }
  36766. getMaterialType() {
  36767. return GLTFMeshStandardSGMaterial;
  36768. }
  36769. extendParams( materialParams, materialDef, parser ) {
  36770. const pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  36771. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  36772. materialParams.opacity = 1.0;
  36773. const pending = [];
  36774. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  36775. const array = pbrSpecularGlossiness.diffuseFactor;
  36776. materialParams.color.fromArray( array );
  36777. materialParams.opacity = array[ 3 ];
  36778. }
  36779. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  36780. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  36781. }
  36782. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  36783. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  36784. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  36785. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  36786. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  36787. }
  36788. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  36789. const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  36790. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  36791. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  36792. }
  36793. return Promise.all( pending );
  36794. }
  36795. createMaterial( materialParams ) {
  36796. const material = new GLTFMeshStandardSGMaterial( materialParams );
  36797. material.fog = true;
  36798. material.color = materialParams.color;
  36799. material.map = materialParams.map === undefined ? null : materialParams.map;
  36800. material.lightMap = null;
  36801. material.lightMapIntensity = 1.0;
  36802. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  36803. material.aoMapIntensity = 1.0;
  36804. material.emissive = materialParams.emissive;
  36805. material.emissiveIntensity = 1.0;
  36806. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  36807. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  36808. material.bumpScale = 1;
  36809. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  36810. material.normalMapType = THREE.TangentSpaceNormalMap;
  36811. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  36812. material.displacementMap = null;
  36813. material.displacementScale = 1;
  36814. material.displacementBias = 0;
  36815. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  36816. material.specular = materialParams.specular;
  36817. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  36818. material.glossiness = materialParams.glossiness;
  36819. material.alphaMap = null;
  36820. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  36821. material.envMapIntensity = 1.0;
  36822. material.refractionRatio = 0.98;
  36823. return material;
  36824. }
  36825. }
  36826. /**
  36827. * THREE.Mesh Quantization Extension
  36828. *
  36829. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  36830. */
  36831. class GLTFMeshQuantizationExtension {
  36832. constructor() {
  36833. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  36834. }
  36835. }
  36836. /*********************************/
  36837. /********** INTERPOLATION ********/
  36838. /*********************************/
  36839. // Spline Interpolation
  36840. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  36841. class GLTFCubicSplineInterpolant extends THREE.Interpolant {
  36842. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  36843. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  36844. }
  36845. copySampleValue_( index ) {
  36846. // Copies a sample value to the result buffer. See description of glTF
  36847. // CUBICSPLINE values layout in interpolate_() function below.
  36848. const result = this.resultBuffer,
  36849. values = this.sampleValues,
  36850. valueSize = this.valueSize,
  36851. offset = index * valueSize * 3 + valueSize;
  36852. for ( let i = 0; i !== valueSize; i ++ ) {
  36853. result[ i ] = values[ offset + i ];
  36854. }
  36855. return result;
  36856. }
  36857. }
  36858. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36859. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  36860. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  36861. const result = this.resultBuffer;
  36862. const values = this.sampleValues;
  36863. const stride = this.valueSize;
  36864. const stride2 = stride * 2;
  36865. const stride3 = stride * 3;
  36866. const td = t1 - t0;
  36867. const p = ( t - t0 ) / td;
  36868. const pp = p * p;
  36869. const ppp = pp * p;
  36870. const offset1 = i1 * stride3;
  36871. const offset0 = offset1 - stride3;
  36872. const s2 = - 2 * ppp + 3 * pp;
  36873. const s3 = ppp - pp;
  36874. const s0 = 1 - s2;
  36875. const s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  36876. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  36877. for ( let i = 0; i !== stride; i ++ ) {
  36878. const p0 = values[ offset0 + i + stride ]; // splineVertex_k
  36879. const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  36880. const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  36881. const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  36882. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  36883. }
  36884. return result;
  36885. };
  36886. const _q = new THREE.Quaternion();
  36887. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  36888. interpolate_( i1, t0, t, t1 ) {
  36889. const result = super.interpolate_( i1, t0, t, t1 );
  36890. _q.fromArray( result ).normalize().toArray( result );
  36891. return result;
  36892. }
  36893. }
  36894. /*********************************/
  36895. /********** INTERNALS ************/
  36896. /*********************************/
  36897. /* CONSTANTS */
  36898. const WEBGL_CONSTANTS = {
  36899. FLOAT: 5126,
  36900. //FLOAT_MAT2: 35674,
  36901. FLOAT_MAT3: 35675,
  36902. FLOAT_MAT4: 35676,
  36903. FLOAT_VEC2: 35664,
  36904. FLOAT_VEC3: 35665,
  36905. FLOAT_VEC4: 35666,
  36906. LINEAR: 9729,
  36907. REPEAT: 10497,
  36908. SAMPLER_2D: 35678,
  36909. POINTS: 0,
  36910. LINES: 1,
  36911. LINE_LOOP: 2,
  36912. LINE_STRIP: 3,
  36913. TRIANGLES: 4,
  36914. TRIANGLE_STRIP: 5,
  36915. TRIANGLE_FAN: 6,
  36916. UNSIGNED_BYTE: 5121,
  36917. UNSIGNED_SHORT: 5123
  36918. };
  36919. const WEBGL_COMPONENT_TYPES = {
  36920. 5120: Int8Array,
  36921. 5121: Uint8Array,
  36922. 5122: Int16Array,
  36923. 5123: Uint16Array,
  36924. 5125: Uint32Array,
  36925. 5126: Float32Array
  36926. };
  36927. const WEBGL_FILTERS = {
  36928. 9728: THREE.NearestFilter,
  36929. 9729: THREE.LinearFilter,
  36930. 9984: THREE.NearestMipmapNearestFilter,
  36931. 9985: THREE.LinearMipmapNearestFilter,
  36932. 9986: THREE.NearestMipmapLinearFilter,
  36933. 9987: THREE.LinearMipmapLinearFilter
  36934. };
  36935. const WEBGL_WRAPPINGS = {
  36936. 33071: THREE.ClampToEdgeWrapping,
  36937. 33648: THREE.MirroredRepeatWrapping,
  36938. 10497: THREE.RepeatWrapping
  36939. };
  36940. const WEBGL_TYPE_SIZES = {
  36941. 'SCALAR': 1,
  36942. 'VEC2': 2,
  36943. 'VEC3': 3,
  36944. 'VEC4': 4,
  36945. 'MAT2': 4,
  36946. 'MAT3': 9,
  36947. 'MAT4': 16
  36948. };
  36949. const ATTRIBUTES = {
  36950. POSITION: 'position',
  36951. NORMAL: 'normal',
  36952. TANGENT: 'tangent',
  36953. TEXCOORD_0: 'uv',
  36954. TEXCOORD_1: 'uv2',
  36955. COLOR_0: 'color',
  36956. WEIGHTS_0: 'skinWeight',
  36957. JOINTS_0: 'skinIndex'
  36958. };
  36959. const PATH_PROPERTIES = {
  36960. scale: 'scale',
  36961. translation: 'position',
  36962. rotation: 'quaternion',
  36963. weights: 'morphTargetInfluences'
  36964. };
  36965. const INTERPOLATION = {
  36966. CUBICSPLINE: undefined,
  36967. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  36968. // keyframe track will be initialized with a default interpolation type, then modified.
  36969. LINEAR: THREE.InterpolateLinear,
  36970. STEP: THREE.InterpolateDiscrete
  36971. };
  36972. const ALPHA_MODES = {
  36973. OPAQUE: 'OPAQUE',
  36974. MASK: 'MASK',
  36975. BLEND: 'BLEND'
  36976. };
  36977. /* UTILITY FUNCTIONS */
  36978. function resolveURL( url, path ) {
  36979. // Invalid URL
  36980. if ( typeof url !== 'string' || url === '' ) return ''; // Host Relative URL
  36981. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  36982. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  36983. } // Absolute URL http://,https://,//
  36984. if ( /^(https?:)?\/\//i.test( url ) ) return url; // Data URI
  36985. if ( /^data:.*,.*$/i.test( url ) ) return url; // Blob URL
  36986. if ( /^blob:.*$/i.test( url ) ) return url; // Relative URL
  36987. return path + url;
  36988. }
  36989. /**
  36990. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  36991. */
  36992. function createDefaultMaterial( cache ) {
  36993. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  36994. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  36995. color: 0xFFFFFF,
  36996. emissive: 0x000000,
  36997. metalness: 1,
  36998. roughness: 1,
  36999. transparent: false,
  37000. depthTest: true,
  37001. side: THREE.FrontSide
  37002. } );
  37003. }
  37004. return cache[ 'DefaultMaterial' ];
  37005. }
  37006. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  37007. // Add unknown glTF extensions to an object's userData.
  37008. for ( const name in objectDef.extensions ) {
  37009. if ( knownExtensions[ name ] === undefined ) {
  37010. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  37011. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  37012. }
  37013. }
  37014. }
  37015. /**
  37016. * @param {Object3D|Material|BufferGeometry} object
  37017. * @param {GLTF.definition} gltfDef
  37018. */
  37019. function assignExtrasToUserData( object, gltfDef ) {
  37020. if ( gltfDef.extras !== undefined ) {
  37021. if ( typeof gltfDef.extras === 'object' ) {
  37022. Object.assign( object.userData, gltfDef.extras );
  37023. } else {
  37024. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  37025. }
  37026. }
  37027. }
  37028. /**
  37029. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  37030. *
  37031. * @param {BufferGeometry} geometry
  37032. * @param {Array<GLTF.Target>} targets
  37033. * @param {GLTFParser} parser
  37034. * @return {Promise<BufferGeometry>}
  37035. */
  37036. function addMorphTargets( geometry, targets, parser ) {
  37037. let hasMorphPosition = false;
  37038. let hasMorphNormal = false;
  37039. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  37040. const target = targets[ i ];
  37041. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  37042. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  37043. if ( hasMorphPosition && hasMorphNormal ) break;
  37044. }
  37045. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  37046. const pendingPositionAccessors = [];
  37047. const pendingNormalAccessors = [];
  37048. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  37049. const target = targets[ i ];
  37050. if ( hasMorphPosition ) {
  37051. const pendingAccessor = target.POSITION !== undefined ? parser.getDependency( 'accessor', target.POSITION ) : geometry.attributes.position;
  37052. pendingPositionAccessors.push( pendingAccessor );
  37053. }
  37054. if ( hasMorphNormal ) {
  37055. const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency( 'accessor', target.NORMAL ) : geometry.attributes.normal;
  37056. pendingNormalAccessors.push( pendingAccessor );
  37057. }
  37058. }
  37059. return Promise.all( [ Promise.all( pendingPositionAccessors ), Promise.all( pendingNormalAccessors ) ] ).then( function ( accessors ) {
  37060. const morphPositions = accessors[ 0 ];
  37061. const morphNormals = accessors[ 1 ];
  37062. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  37063. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  37064. geometry.morphTargetsRelative = true;
  37065. return geometry;
  37066. } );
  37067. }
  37068. /**
  37069. * @param {Mesh} mesh
  37070. * @param {GLTF.Mesh} meshDef
  37071. */
  37072. function updateMorphTargets( mesh, meshDef ) {
  37073. mesh.updateMorphTargets();
  37074. if ( meshDef.weights !== undefined ) {
  37075. for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  37076. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  37077. }
  37078. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  37079. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  37080. const targetNames = meshDef.extras.targetNames;
  37081. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  37082. mesh.morphTargetDictionary = {};
  37083. for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
  37084. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  37085. }
  37086. } else {
  37087. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  37088. }
  37089. }
  37090. }
  37091. function createPrimitiveKey( primitiveDef ) {
  37092. const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  37093. let geometryKey;
  37094. if ( dracoExtension ) {
  37095. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey( dracoExtension.attributes );
  37096. } else {
  37097. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  37098. }
  37099. return geometryKey;
  37100. }
  37101. function createAttributesKey( attributes ) {
  37102. let attributesKey = '';
  37103. const keys = Object.keys( attributes ).sort();
  37104. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  37105. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  37106. }
  37107. return attributesKey;
  37108. }
  37109. function getNormalizedComponentScale( constructor ) {
  37110. // Reference:
  37111. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  37112. switch ( constructor ) {
  37113. case Int8Array:
  37114. return 1 / 127;
  37115. case Uint8Array:
  37116. return 1 / 255;
  37117. case Int16Array:
  37118. return 1 / 32767;
  37119. case Uint16Array:
  37120. return 1 / 65535;
  37121. default:
  37122. throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
  37123. }
  37124. }
  37125. /* GLTF PARSER */
  37126. class GLTFParser {
  37127. constructor( json = {}, options = {} ) {
  37128. this.json = json;
  37129. this.extensions = {};
  37130. this.plugins = {};
  37131. this.options = options; // loader object cache
  37132. this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements
  37133. this.associations = new Map(); // THREE.BufferGeometry caching
  37134. this.primitiveCache = {}; // THREE.Object3D instance caches
  37135. this.meshCache = {
  37136. refs: {},
  37137. uses: {}
  37138. };
  37139. this.cameraCache = {
  37140. refs: {},
  37141. uses: {}
  37142. };
  37143. this.lightCache = {
  37144. refs: {},
  37145. uses: {}
  37146. };
  37147. this.textureCache = {}; // Track node names, to ensure no duplicates
  37148. this.nodeNamesUsed = {}; // Use an THREE.ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  37149. // expensive work of uploading a texture to the GPU off the main thread.
  37150. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  37151. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  37152. } else {
  37153. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  37154. }
  37155. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  37156. this.textureLoader.setRequestHeader( this.options.requestHeader );
  37157. this.fileLoader = new THREE.FileLoader( this.options.manager );
  37158. this.fileLoader.setResponseType( 'arraybuffer' );
  37159. if ( this.options.crossOrigin === 'use-credentials' ) {
  37160. this.fileLoader.setWithCredentials( true );
  37161. }
  37162. }
  37163. setExtensions( extensions ) {
  37164. this.extensions = extensions;
  37165. }
  37166. setPlugins( plugins ) {
  37167. this.plugins = plugins;
  37168. }
  37169. parse( onLoad, onError ) {
  37170. const parser = this;
  37171. const json = this.json;
  37172. const extensions = this.extensions; // Clear the loader cache
  37173. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  37174. this._invokeAll( function ( ext ) {
  37175. return ext._markDefs && ext._markDefs();
  37176. } );
  37177. Promise.all( this._invokeAll( function ( ext ) {
  37178. return ext.beforeRoot && ext.beforeRoot();
  37179. } ) ).then( function () {
  37180. return Promise.all( [ parser.getDependencies( 'scene' ), parser.getDependencies( 'animation' ), parser.getDependencies( 'camera' ) ] );
  37181. } ).then( function ( dependencies ) {
  37182. const result = {
  37183. scene: dependencies[ 0 ][ json.scene || 0 ],
  37184. scenes: dependencies[ 0 ],
  37185. animations: dependencies[ 1 ],
  37186. cameras: dependencies[ 2 ],
  37187. asset: json.asset,
  37188. parser: parser,
  37189. userData: {}
  37190. };
  37191. addUnknownExtensionsToUserData( extensions, result, json );
  37192. assignExtrasToUserData( result, json );
  37193. Promise.all( parser._invokeAll( function ( ext ) {
  37194. return ext.afterRoot && ext.afterRoot( result );
  37195. } ) ).then( function () {
  37196. onLoad( result );
  37197. } );
  37198. } ).catch( onError );
  37199. }
  37200. /**
  37201. * Marks the special nodes/meshes in json for efficient parse.
  37202. */
  37203. _markDefs() {
  37204. const nodeDefs = this.json.nodes || [];
  37205. const skinDefs = this.json.skins || [];
  37206. const meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a THREE.Bone or an
  37207. // THREE.Object3D. Use the skins' joint references to mark bones.
  37208. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  37209. const joints = skinDefs[ skinIndex ].joints;
  37210. for ( let i = 0, il = joints.length; i < il; i ++ ) {
  37211. nodeDefs[ joints[ i ] ].isBone = true;
  37212. }
  37213. } // Iterate over all nodes, marking references to shared resources,
  37214. // as well as skeleton joints.
  37215. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37216. const nodeDef = nodeDefs[ nodeIndex ];
  37217. if ( nodeDef.mesh !== undefined ) {
  37218. this._addNodeRef( this.meshCache, nodeDef.mesh ); // Nothing in the mesh definition indicates whether it is
  37219. // a THREE.SkinnedMesh or THREE.Mesh. Use the node's mesh reference
  37220. // to mark THREE.SkinnedMesh if node has skin.
  37221. if ( nodeDef.skin !== undefined ) {
  37222. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  37223. }
  37224. }
  37225. if ( nodeDef.camera !== undefined ) {
  37226. this._addNodeRef( this.cameraCache, nodeDef.camera );
  37227. }
  37228. }
  37229. }
  37230. /**
  37231. * Counts references to shared node / THREE.Object3D resources. These resources
  37232. * can be reused, or "instantiated", at multiple nodes in the scene
  37233. * hierarchy. THREE.Mesh, Camera, and Light instances are instantiated and must
  37234. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  37235. * Textures) can be reused directly and are not marked here.
  37236. *
  37237. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  37238. */
  37239. _addNodeRef( cache, index ) {
  37240. if ( index === undefined ) return;
  37241. if ( cache.refs[ index ] === undefined ) {
  37242. cache.refs[ index ] = cache.uses[ index ] = 0;
  37243. }
  37244. cache.refs[ index ] ++;
  37245. }
  37246. /** Returns a reference to a shared resource, cloning it if necessary. */
  37247. _getNodeRef( cache, index, object ) {
  37248. if ( cache.refs[ index ] <= 1 ) return object;
  37249. const ref = object.clone(); // Propagates mappings to the cloned object, prevents mappings on the
  37250. // original object from being lost.
  37251. const updateMappings = ( original, clone ) => {
  37252. const mappings = this.associations.get( original );
  37253. if ( mappings != null ) {
  37254. this.associations.set( clone, mappings );
  37255. }
  37256. for ( const [ i, child ] of original.children.entries() ) {
  37257. updateMappings( child, clone.children[ i ] );
  37258. }
  37259. };
  37260. updateMappings( object, ref );
  37261. ref.name += '_instance_' + cache.uses[ index ] ++;
  37262. return ref;
  37263. }
  37264. _invokeOne( func ) {
  37265. const extensions = Object.values( this.plugins );
  37266. extensions.push( this );
  37267. for ( let i = 0; i < extensions.length; i ++ ) {
  37268. const result = func( extensions[ i ] );
  37269. if ( result ) return result;
  37270. }
  37271. return null;
  37272. }
  37273. _invokeAll( func ) {
  37274. const extensions = Object.values( this.plugins );
  37275. extensions.unshift( this );
  37276. const pending = [];
  37277. for ( let i = 0; i < extensions.length; i ++ ) {
  37278. const result = func( extensions[ i ] );
  37279. if ( result ) pending.push( result );
  37280. }
  37281. return pending;
  37282. }
  37283. /**
  37284. * Requests the specified dependency asynchronously, with caching.
  37285. * @param {string} type
  37286. * @param {number} index
  37287. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  37288. */
  37289. getDependency( type, index ) {
  37290. const cacheKey = type + ':' + index;
  37291. let dependency = this.cache.get( cacheKey );
  37292. if ( ! dependency ) {
  37293. switch ( type ) {
  37294. case 'scene':
  37295. dependency = this.loadScene( index );
  37296. break;
  37297. case 'node':
  37298. dependency = this.loadNode( index );
  37299. break;
  37300. case 'mesh':
  37301. dependency = this._invokeOne( function ( ext ) {
  37302. return ext.loadMesh && ext.loadMesh( index );
  37303. } );
  37304. break;
  37305. case 'accessor':
  37306. dependency = this.loadAccessor( index );
  37307. break;
  37308. case 'bufferView':
  37309. dependency = this._invokeOne( function ( ext ) {
  37310. return ext.loadBufferView && ext.loadBufferView( index );
  37311. } );
  37312. break;
  37313. case 'buffer':
  37314. dependency = this.loadBuffer( index );
  37315. break;
  37316. case 'material':
  37317. dependency = this._invokeOne( function ( ext ) {
  37318. return ext.loadMaterial && ext.loadMaterial( index );
  37319. } );
  37320. break;
  37321. case 'texture':
  37322. dependency = this._invokeOne( function ( ext ) {
  37323. return ext.loadTexture && ext.loadTexture( index );
  37324. } );
  37325. break;
  37326. case 'skin':
  37327. dependency = this.loadSkin( index );
  37328. break;
  37329. case 'animation':
  37330. dependency = this.loadAnimation( index );
  37331. break;
  37332. case 'camera':
  37333. dependency = this.loadCamera( index );
  37334. break;
  37335. default:
  37336. throw new Error( 'Unknown type: ' + type );
  37337. }
  37338. this.cache.add( cacheKey, dependency );
  37339. }
  37340. return dependency;
  37341. }
  37342. /**
  37343. * Requests all dependencies of the specified type asynchronously, with caching.
  37344. * @param {string} type
  37345. * @return {Promise<Array<Object>>}
  37346. */
  37347. getDependencies( type ) {
  37348. let dependencies = this.cache.get( type );
  37349. if ( ! dependencies ) {
  37350. const parser = this;
  37351. const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  37352. dependencies = Promise.all( defs.map( function ( def, index ) {
  37353. return parser.getDependency( type, index );
  37354. } ) );
  37355. this.cache.add( type, dependencies );
  37356. }
  37357. return dependencies;
  37358. }
  37359. /**
  37360. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  37361. * @param {number} bufferIndex
  37362. * @return {Promise<ArrayBuffer>}
  37363. */
  37364. loadBuffer( bufferIndex ) {
  37365. const bufferDef = this.json.buffers[ bufferIndex ];
  37366. const loader = this.fileLoader;
  37367. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  37368. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  37369. } // If present, GLB container is required to be the first buffer.
  37370. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  37371. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  37372. }
  37373. const options = this.options;
  37374. return new Promise( function ( resolve, reject ) {
  37375. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  37376. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  37377. } );
  37378. } );
  37379. }
  37380. /**
  37381. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  37382. * @param {number} bufferViewIndex
  37383. * @return {Promise<ArrayBuffer>}
  37384. */
  37385. loadBufferView( bufferViewIndex ) {
  37386. const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  37387. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  37388. const byteLength = bufferViewDef.byteLength || 0;
  37389. const byteOffset = bufferViewDef.byteOffset || 0;
  37390. return buffer.slice( byteOffset, byteOffset + byteLength );
  37391. } );
  37392. }
  37393. /**
  37394. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  37395. * @param {number} accessorIndex
  37396. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  37397. */
  37398. loadAccessor( accessorIndex ) {
  37399. const parser = this;
  37400. const json = this.json;
  37401. const accessorDef = this.json.accessors[ accessorIndex ];
  37402. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  37403. // Ignore empty accessors, which may be used to declare runtime
  37404. // information about attributes coming from another source (e.g. Draco
  37405. // compression extension).
  37406. return Promise.resolve( null );
  37407. }
  37408. const pendingBufferViews = [];
  37409. if ( accessorDef.bufferView !== undefined ) {
  37410. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  37411. } else {
  37412. pendingBufferViews.push( null );
  37413. }
  37414. if ( accessorDef.sparse !== undefined ) {
  37415. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  37416. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  37417. }
  37418. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  37419. const bufferView = bufferViews[ 0 ];
  37420. const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  37421. const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  37422. const elementBytes = TypedArray.BYTES_PER_ELEMENT;
  37423. const itemBytes = elementBytes * itemSize;
  37424. const byteOffset = accessorDef.byteOffset || 0;
  37425. const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  37426. const normalized = accessorDef.normalized === true;
  37427. let array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  37428. if ( byteStride && byteStride !== itemBytes ) {
  37429. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own THREE.InterleavedBuffer
  37430. // This makes sure that IBA.count reflects accessor.count properly
  37431. const ibSlice = Math.floor( byteOffset / byteStride );
  37432. const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  37433. let ib = parser.cache.get( ibCacheKey );
  37434. if ( ! ib ) {
  37435. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes ); // Integer parameters to IB/IBA are in array elements, not bytes.
  37436. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  37437. parser.cache.add( ibCacheKey, ib );
  37438. }
  37439. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset % byteStride / elementBytes, normalized );
  37440. } else {
  37441. if ( bufferView === null ) {
  37442. array = new TypedArray( accessorDef.count * itemSize );
  37443. } else {
  37444. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  37445. }
  37446. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  37447. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  37448. if ( accessorDef.sparse !== undefined ) {
  37449. const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  37450. const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  37451. const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  37452. const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  37453. const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  37454. const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  37455. if ( bufferView !== null ) {
  37456. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  37457. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  37458. }
  37459. for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
  37460. const index = sparseIndices[ i ];
  37461. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  37462. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  37463. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  37464. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  37465. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse THREE.BufferAttribute.' );
  37466. }
  37467. }
  37468. return bufferAttribute;
  37469. } );
  37470. }
  37471. /**
  37472. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  37473. * @param {number} textureIndex
  37474. * @return {Promise<THREE.Texture>}
  37475. */
  37476. loadTexture( textureIndex ) {
  37477. const json = this.json;
  37478. const options = this.options;
  37479. const textureDef = json.textures[ textureIndex ];
  37480. const source = json.images[ textureDef.source ];
  37481. let loader = this.textureLoader;
  37482. if ( source.uri ) {
  37483. const handler = options.manager.getHandler( source.uri );
  37484. if ( handler !== null ) loader = handler;
  37485. }
  37486. return this.loadTextureImage( textureIndex, source, loader );
  37487. }
  37488. loadTextureImage( textureIndex, source, loader ) {
  37489. const parser = this;
  37490. const json = this.json;
  37491. const options = this.options;
  37492. const textureDef = json.textures[ textureIndex ];
  37493. const cacheKey = ( source.uri || source.bufferView ) + ':' + textureDef.sampler;
  37494. if ( this.textureCache[ cacheKey ] ) {
  37495. // See https://github.com/mrdoob/three.js/issues/21559.
  37496. return this.textureCache[ cacheKey ];
  37497. }
  37498. const URL = self.URL || self.webkitURL;
  37499. let sourceURI = source.uri || '';
  37500. let isObjectURL = false;
  37501. if ( source.bufferView !== undefined ) {
  37502. // Load binary image data from bufferView, if provided.
  37503. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  37504. isObjectURL = true;
  37505. const blob = new Blob( [ bufferView ], {
  37506. type: source.mimeType
  37507. } );
  37508. sourceURI = URL.createObjectURL( blob );
  37509. return sourceURI;
  37510. } );
  37511. } else if ( source.uri === undefined ) {
  37512. throw new Error( 'THREE.GLTFLoader: Image ' + textureIndex + ' is missing URI and bufferView' );
  37513. }
  37514. const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  37515. return new Promise( function ( resolve, reject ) {
  37516. let onLoad = resolve;
  37517. if ( loader.isImageBitmapLoader === true ) {
  37518. onLoad = function ( imageBitmap ) {
  37519. const texture = new THREE.Texture( imageBitmap );
  37520. texture.needsUpdate = true;
  37521. resolve( texture );
  37522. };
  37523. }
  37524. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  37525. } );
  37526. } ).then( function ( texture ) {
  37527. // Clean up resources and configure THREE.Texture.
  37528. if ( isObjectURL === true ) {
  37529. URL.revokeObjectURL( sourceURI );
  37530. }
  37531. texture.flipY = false;
  37532. if ( textureDef.name ) texture.name = textureDef.name;
  37533. const samplers = json.samplers || {};
  37534. const sampler = samplers[ textureDef.sampler ] || {};
  37535. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  37536. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  37537. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  37538. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  37539. parser.associations.set( texture, {
  37540. textures: textureIndex
  37541. } );
  37542. return texture;
  37543. } ).catch( function () {
  37544. console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
  37545. return null;
  37546. } );
  37547. this.textureCache[ cacheKey ] = promise;
  37548. return promise;
  37549. }
  37550. /**
  37551. * Asynchronously assigns a texture to the given material parameters.
  37552. * @param {Object} materialParams
  37553. * @param {string} mapName
  37554. * @param {Object} mapDef
  37555. * @return {Promise<Texture>}
  37556. */
  37557. assignTexture( materialParams, mapName, mapDef ) {
  37558. const parser = this;
  37559. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  37560. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  37561. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  37562. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  37563. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  37564. }
  37565. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  37566. const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  37567. if ( transform ) {
  37568. const gltfReference = parser.associations.get( texture );
  37569. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  37570. parser.associations.set( texture, gltfReference );
  37571. }
  37572. }
  37573. materialParams[ mapName ] = texture;
  37574. return texture;
  37575. } );
  37576. }
  37577. /**
  37578. * Assigns final material to a THREE.Mesh, THREE.Line, or THREE.Points instance. The instance
  37579. * already has a material (generated from the glTF material options alone)
  37580. * but reuse of the same glTF material may require multiple threejs materials
  37581. * to accommodate different primitive types, defines, etc. New materials will
  37582. * be created if necessary, and reused from a cache.
  37583. * @param {Object3D} mesh THREE.Mesh, THREE.Line, or THREE.Points instance.
  37584. */
  37585. assignFinalMaterial( mesh ) {
  37586. const geometry = mesh.geometry;
  37587. let material = mesh.material;
  37588. const useDerivativeTangents = geometry.attributes.tangent === undefined;
  37589. const useVertexColors = geometry.attributes.color !== undefined;
  37590. const useFlatShading = geometry.attributes.normal === undefined;
  37591. if ( mesh.isPoints ) {
  37592. const cacheKey = 'PointsMaterial:' + material.uuid;
  37593. let pointsMaterial = this.cache.get( cacheKey );
  37594. if ( ! pointsMaterial ) {
  37595. pointsMaterial = new THREE.PointsMaterial();
  37596. THREE.Material.prototype.copy.call( pointsMaterial, material );
  37597. pointsMaterial.color.copy( material.color );
  37598. pointsMaterial.map = material.map;
  37599. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  37600. this.cache.add( cacheKey, pointsMaterial );
  37601. }
  37602. material = pointsMaterial;
  37603. } else if ( mesh.isLine ) {
  37604. const cacheKey = 'LineBasicMaterial:' + material.uuid;
  37605. let lineMaterial = this.cache.get( cacheKey );
  37606. if ( ! lineMaterial ) {
  37607. lineMaterial = new THREE.LineBasicMaterial();
  37608. THREE.Material.prototype.copy.call( lineMaterial, material );
  37609. lineMaterial.color.copy( material.color );
  37610. this.cache.add( cacheKey, lineMaterial );
  37611. }
  37612. material = lineMaterial;
  37613. } // Clone the material if it will be modified
  37614. if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
  37615. let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  37616. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  37617. if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
  37618. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  37619. if ( useFlatShading ) cacheKey += 'flat-shading:';
  37620. let cachedMaterial = this.cache.get( cacheKey );
  37621. if ( ! cachedMaterial ) {
  37622. cachedMaterial = material.clone();
  37623. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  37624. if ( useFlatShading ) cachedMaterial.flatShading = true;
  37625. if ( useDerivativeTangents ) {
  37626. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  37627. if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
  37628. if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
  37629. }
  37630. this.cache.add( cacheKey, cachedMaterial );
  37631. this.associations.set( cachedMaterial, this.associations.get( material ) );
  37632. }
  37633. material = cachedMaterial;
  37634. } // workarounds for mesh and geometry
  37635. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  37636. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  37637. }
  37638. mesh.material = material;
  37639. }
  37640. getMaterialType() {
  37641. return THREE.MeshStandardMaterial;
  37642. }
  37643. /**
  37644. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  37645. * @param {number} materialIndex
  37646. * @return {Promise<Material>}
  37647. */
  37648. loadMaterial( materialIndex ) {
  37649. const parser = this;
  37650. const json = this.json;
  37651. const extensions = this.extensions;
  37652. const materialDef = json.materials[ materialIndex ];
  37653. let materialType;
  37654. const materialParams = {};
  37655. const materialExtensions = materialDef.extensions || {};
  37656. const pending = [];
  37657. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  37658. const sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  37659. materialType = sgExtension.getMaterialType();
  37660. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  37661. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  37662. const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  37663. materialType = kmuExtension.getMaterialType();
  37664. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  37665. } else {
  37666. // Specification:
  37667. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  37668. const metallicRoughness = materialDef.pbrMetallicRoughness || {};
  37669. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37670. materialParams.opacity = 1.0;
  37671. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37672. const array = metallicRoughness.baseColorFactor;
  37673. materialParams.color.fromArray( array );
  37674. materialParams.opacity = array[ 3 ];
  37675. }
  37676. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37677. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37678. }
  37679. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  37680. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  37681. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  37682. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37683. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  37684. }
  37685. materialType = this._invokeOne( function ( ext ) {
  37686. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  37687. } );
  37688. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  37689. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  37690. } ) ) );
  37691. }
  37692. if ( materialDef.doubleSided === true ) {
  37693. materialParams.side = THREE.DoubleSide;
  37694. }
  37695. const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  37696. if ( alphaMode === ALPHA_MODES.BLEND ) {
  37697. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  37698. materialParams.depthWrite = false;
  37699. } else {
  37700. materialParams.format = THREE.RGBFormat;
  37701. materialParams.transparent = false;
  37702. if ( alphaMode === ALPHA_MODES.MASK ) {
  37703. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  37704. }
  37705. }
  37706. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37707. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  37708. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  37709. if ( materialDef.normalTexture.scale !== undefined ) {
  37710. const scale = materialDef.normalTexture.scale;
  37711. materialParams.normalScale.set( scale, scale );
  37712. }
  37713. }
  37714. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37715. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  37716. if ( materialDef.occlusionTexture.strength !== undefined ) {
  37717. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  37718. }
  37719. }
  37720. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37721. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  37722. }
  37723. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  37724. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  37725. }
  37726. return Promise.all( pending ).then( function () {
  37727. let material;
  37728. if ( materialType === GLTFMeshStandardSGMaterial ) {
  37729. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  37730. } else {
  37731. material = new materialType( materialParams );
  37732. }
  37733. if ( materialDef.name ) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  37734. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  37735. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  37736. assignExtrasToUserData( material, materialDef );
  37737. parser.associations.set( material, {
  37738. materials: materialIndex
  37739. } );
  37740. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  37741. return material;
  37742. } );
  37743. }
  37744. /** When THREE.Object3D instances are targeted by animation, they need unique names. */
  37745. createUniqueName( originalName ) {
  37746. const sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
  37747. let name = sanitizedName;
  37748. for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  37749. name = sanitizedName + '_' + i;
  37750. }
  37751. this.nodeNamesUsed[ name ] = true;
  37752. return name;
  37753. }
  37754. /**
  37755. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  37756. *
  37757. * Creates BufferGeometries from primitives.
  37758. *
  37759. * @param {Array<GLTF.Primitive>} primitives
  37760. * @return {Promise<Array<BufferGeometry>>}
  37761. */
  37762. loadGeometries( primitives ) {
  37763. const parser = this;
  37764. const extensions = this.extensions;
  37765. const cache = this.primitiveCache;
  37766. function createDracoPrimitive( primitive ) {
  37767. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ].decodePrimitive( primitive, parser ).then( function ( geometry ) {
  37768. return addPrimitiveAttributes( geometry, primitive, parser );
  37769. } );
  37770. }
  37771. const pending = [];
  37772. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  37773. const primitive = primitives[ i ];
  37774. const cacheKey = createPrimitiveKey( primitive ); // See if we've already created this geometry
  37775. const cached = cache[ cacheKey ];
  37776. if ( cached ) {
  37777. // Use the cached geometry if it exists
  37778. pending.push( cached.promise );
  37779. } else {
  37780. let geometryPromise;
  37781. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  37782. // Use DRACO geometry if available
  37783. geometryPromise = createDracoPrimitive( primitive );
  37784. } else {
  37785. // Otherwise create a new geometry
  37786. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  37787. } // Cache this geometry
  37788. cache[ cacheKey ] = {
  37789. primitive: primitive,
  37790. promise: geometryPromise
  37791. };
  37792. pending.push( geometryPromise );
  37793. }
  37794. }
  37795. return Promise.all( pending );
  37796. }
  37797. /**
  37798. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  37799. * @param {number} meshIndex
  37800. * @return {Promise<Group|Mesh|SkinnedMesh>}
  37801. */
  37802. loadMesh( meshIndex ) {
  37803. const parser = this;
  37804. const json = this.json;
  37805. const extensions = this.extensions;
  37806. const meshDef = json.meshes[ meshIndex ];
  37807. const primitives = meshDef.primitives;
  37808. const pending = [];
  37809. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  37810. const material = primitives[ i ].material === undefined ? createDefaultMaterial( this.cache ) : this.getDependency( 'material', primitives[ i ].material );
  37811. pending.push( material );
  37812. }
  37813. pending.push( parser.loadGeometries( primitives ) );
  37814. return Promise.all( pending ).then( function ( results ) {
  37815. const materials = results.slice( 0, results.length - 1 );
  37816. const geometries = results[ results.length - 1 ];
  37817. const meshes = [];
  37818. for ( let i = 0, il = geometries.length; i < il; i ++ ) {
  37819. const geometry = geometries[ i ];
  37820. const primitive = primitives[ i ]; // 1. create THREE.Mesh
  37821. let mesh;
  37822. const material = materials[ i ];
  37823. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined ) {
  37824. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  37825. mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh( geometry, material ) : new THREE.Mesh( geometry, material );
  37826. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  37827. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  37828. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  37829. mesh.normalizeSkinWeights();
  37830. }
  37831. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  37832. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  37833. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  37834. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  37835. }
  37836. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  37837. mesh = new THREE.LineSegments( geometry, material );
  37838. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  37839. mesh = new THREE.Line( geometry, material );
  37840. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  37841. mesh = new THREE.LineLoop( geometry, material );
  37842. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  37843. mesh = new THREE.Points( geometry, material );
  37844. } else {
  37845. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  37846. }
  37847. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  37848. updateMorphTargets( mesh, meshDef );
  37849. }
  37850. mesh.name = parser.createUniqueName( meshDef.name || 'mesh_' + meshIndex );
  37851. assignExtrasToUserData( mesh, meshDef );
  37852. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  37853. parser.assignFinalMaterial( mesh );
  37854. meshes.push( mesh );
  37855. }
  37856. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  37857. parser.associations.set( meshes[ i ], {
  37858. meshes: meshIndex,
  37859. primitives: i
  37860. } );
  37861. }
  37862. if ( meshes.length === 1 ) {
  37863. return meshes[ 0 ];
  37864. }
  37865. const group = new THREE.Group();
  37866. parser.associations.set( group, {
  37867. meshes: meshIndex
  37868. } );
  37869. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  37870. group.add( meshes[ i ] );
  37871. }
  37872. return group;
  37873. } );
  37874. }
  37875. /**
  37876. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  37877. * @param {number} cameraIndex
  37878. * @return {Promise<THREE.Camera>}
  37879. */
  37880. loadCamera( cameraIndex ) {
  37881. let camera;
  37882. const cameraDef = this.json.cameras[ cameraIndex ];
  37883. const params = cameraDef[ cameraDef.type ];
  37884. if ( ! params ) {
  37885. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  37886. return;
  37887. }
  37888. if ( cameraDef.type === 'perspective' ) {
  37889. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  37890. } else if ( cameraDef.type === 'orthographic' ) {
  37891. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  37892. }
  37893. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  37894. assignExtrasToUserData( camera, cameraDef );
  37895. return Promise.resolve( camera );
  37896. }
  37897. /**
  37898. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  37899. * @param {number} skinIndex
  37900. * @return {Promise<Object>}
  37901. */
  37902. loadSkin( skinIndex ) {
  37903. const skinDef = this.json.skins[ skinIndex ];
  37904. const skinEntry = {
  37905. joints: skinDef.joints
  37906. };
  37907. if ( skinDef.inverseBindMatrices === undefined ) {
  37908. return Promise.resolve( skinEntry );
  37909. }
  37910. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  37911. skinEntry.inverseBindMatrices = accessor;
  37912. return skinEntry;
  37913. } );
  37914. }
  37915. /**
  37916. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  37917. * @param {number} animationIndex
  37918. * @return {Promise<AnimationClip>}
  37919. */
  37920. loadAnimation( animationIndex ) {
  37921. const json = this.json;
  37922. const animationDef = json.animations[ animationIndex ];
  37923. const pendingNodes = [];
  37924. const pendingInputAccessors = [];
  37925. const pendingOutputAccessors = [];
  37926. const pendingSamplers = [];
  37927. const pendingTargets = [];
  37928. for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  37929. const channel = animationDef.channels[ i ];
  37930. const sampler = animationDef.samplers[ channel.sampler ];
  37931. const target = channel.target;
  37932. const name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  37933. const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  37934. const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  37935. pendingNodes.push( this.getDependency( 'node', name ) );
  37936. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  37937. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  37938. pendingSamplers.push( sampler );
  37939. pendingTargets.push( target );
  37940. }
  37941. return Promise.all( [ Promise.all( pendingNodes ), Promise.all( pendingInputAccessors ), Promise.all( pendingOutputAccessors ), Promise.all( pendingSamplers ), Promise.all( pendingTargets ) ] ).then( function ( dependencies ) {
  37942. const nodes = dependencies[ 0 ];
  37943. const inputAccessors = dependencies[ 1 ];
  37944. const outputAccessors = dependencies[ 2 ];
  37945. const samplers = dependencies[ 3 ];
  37946. const targets = dependencies[ 4 ];
  37947. const tracks = [];
  37948. for ( let i = 0, il = nodes.length; i < il; i ++ ) {
  37949. const node = nodes[ i ];
  37950. const inputAccessor = inputAccessors[ i ];
  37951. const outputAccessor = outputAccessors[ i ];
  37952. const sampler = samplers[ i ];
  37953. const target = targets[ i ];
  37954. if ( node === undefined ) continue;
  37955. node.updateMatrix();
  37956. node.matrixAutoUpdate = true;
  37957. let TypedKeyframeTrack;
  37958. switch ( PATH_PROPERTIES[ target.path ] ) {
  37959. case PATH_PROPERTIES.weights:
  37960. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  37961. break;
  37962. case PATH_PROPERTIES.rotation:
  37963. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  37964. break;
  37965. case PATH_PROPERTIES.position:
  37966. case PATH_PROPERTIES.scale:
  37967. default:
  37968. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  37969. break;
  37970. }
  37971. const targetName = node.name ? node.name : node.uuid;
  37972. const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  37973. const targetNames = [];
  37974. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  37975. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  37976. node.traverse( function ( object ) {
  37977. if ( object.isMesh === true && object.morphTargetInfluences ) {
  37978. targetNames.push( object.name ? object.name : object.uuid );
  37979. }
  37980. } );
  37981. } else {
  37982. targetNames.push( targetName );
  37983. }
  37984. let outputArray = outputAccessor.array;
  37985. if ( outputAccessor.normalized ) {
  37986. const scale = getNormalizedComponentScale( outputArray.constructor );
  37987. const scaled = new Float32Array( outputArray.length );
  37988. for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
  37989. scaled[ j ] = outputArray[ j ] * scale;
  37990. }
  37991. outputArray = scaled;
  37992. }
  37993. for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
  37994. const track = new TypedKeyframeTrack( targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], inputAccessor.array, outputArray, interpolation ); // Override interpolation with custom factory method.
  37995. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  37996. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  37997. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  37998. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  37999. // must be divided by three to get the interpolant's sampleSize argument.
  38000. const interpolantType = this instanceof THREE.QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
  38001. return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
  38002. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  38003. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  38004. }
  38005. tracks.push( track );
  38006. }
  38007. }
  38008. const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  38009. return new THREE.AnimationClip( name, undefined, tracks );
  38010. } );
  38011. }
  38012. createNodeMesh( nodeIndex ) {
  38013. const json = this.json;
  38014. const parser = this;
  38015. const nodeDef = json.nodes[ nodeIndex ];
  38016. if ( nodeDef.mesh === undefined ) return null;
  38017. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  38018. const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); // if weights are provided on the node, override weights on the mesh.
  38019. if ( nodeDef.weights !== undefined ) {
  38020. node.traverse( function ( o ) {
  38021. if ( ! o.isMesh ) return;
  38022. for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  38023. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  38024. }
  38025. } );
  38026. }
  38027. return node;
  38028. } );
  38029. }
  38030. /**
  38031. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  38032. * @param {number} nodeIndex
  38033. * @return {Promise<Object3D>}
  38034. */
  38035. loadNode( nodeIndex ) {
  38036. const json = this.json;
  38037. const extensions = this.extensions;
  38038. const parser = this;
  38039. const nodeDef = json.nodes[ nodeIndex ]; // reserve node's name before its dependencies, so the root has the intended name.
  38040. const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  38041. return function () {
  38042. const pending = [];
  38043. const meshPromise = parser._invokeOne( function ( ext ) {
  38044. return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
  38045. } );
  38046. if ( meshPromise ) {
  38047. pending.push( meshPromise );
  38048. }
  38049. if ( nodeDef.camera !== undefined ) {
  38050. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  38051. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  38052. } ) );
  38053. }
  38054. parser._invokeAll( function ( ext ) {
  38055. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  38056. } ).forEach( function ( promise ) {
  38057. pending.push( promise );
  38058. } );
  38059. return Promise.all( pending );
  38060. }().then( function ( objects ) {
  38061. let node; // .isBone isn't in glTF spec. See ._markDefs
  38062. if ( nodeDef.isBone === true ) {
  38063. node = new THREE.Bone();
  38064. } else if ( objects.length > 1 ) {
  38065. node = new THREE.Group();
  38066. } else if ( objects.length === 1 ) {
  38067. node = objects[ 0 ];
  38068. } else {
  38069. node = new THREE.Object3D();
  38070. }
  38071. if ( node !== objects[ 0 ] ) {
  38072. for ( let i = 0, il = objects.length; i < il; i ++ ) {
  38073. node.add( objects[ i ] );
  38074. }
  38075. }
  38076. if ( nodeDef.name ) {
  38077. node.userData.name = nodeDef.name;
  38078. node.name = nodeName;
  38079. }
  38080. assignExtrasToUserData( node, nodeDef );
  38081. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  38082. if ( nodeDef.matrix !== undefined ) {
  38083. const matrix = new THREE.Matrix4();
  38084. matrix.fromArray( nodeDef.matrix );
  38085. node.applyMatrix4( matrix );
  38086. } else {
  38087. if ( nodeDef.translation !== undefined ) {
  38088. node.position.fromArray( nodeDef.translation );
  38089. }
  38090. if ( nodeDef.rotation !== undefined ) {
  38091. node.quaternion.fromArray( nodeDef.rotation );
  38092. }
  38093. if ( nodeDef.scale !== undefined ) {
  38094. node.scale.fromArray( nodeDef.scale );
  38095. }
  38096. }
  38097. if ( ! parser.associations.has( node ) ) {
  38098. parser.associations.set( node, {} );
  38099. }
  38100. parser.associations.get( node ).nodes = nodeIndex;
  38101. return node;
  38102. } );
  38103. }
  38104. /**
  38105. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  38106. * @param {number} sceneIndex
  38107. * @return {Promise<Group>}
  38108. */
  38109. loadScene( sceneIndex ) {
  38110. const json = this.json;
  38111. const extensions = this.extensions;
  38112. const sceneDef = this.json.scenes[ sceneIndex ];
  38113. const parser = this; // THREE.Loader returns THREE.Group, not Scene.
  38114. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  38115. const scene = new THREE.Group();
  38116. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  38117. assignExtrasToUserData( scene, sceneDef );
  38118. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  38119. const nodeIds = sceneDef.nodes || [];
  38120. const pending = [];
  38121. for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
  38122. pending.push( buildNodeHierarchy( nodeIds[ i ], scene, json, parser ) );
  38123. }
  38124. return Promise.all( pending ).then( function () {
  38125. // Removes dangling associations, associations that reference a node that
  38126. // didn't make it into the scene.
  38127. const reduceAssociations = node => {
  38128. const reducedAssociations = new Map();
  38129. for ( const [ key, value ] of parser.associations ) {
  38130. if ( key instanceof THREE.Material || key instanceof THREE.Texture ) {
  38131. reducedAssociations.set( key, value );
  38132. }
  38133. }
  38134. node.traverse( node => {
  38135. const mappings = parser.associations.get( node );
  38136. if ( mappings != null ) {
  38137. reducedAssociations.set( node, mappings );
  38138. }
  38139. } );
  38140. return reducedAssociations;
  38141. };
  38142. parser.associations = reduceAssociations( scene );
  38143. return scene;
  38144. } );
  38145. }
  38146. }
  38147. function buildNodeHierarchy( nodeId, parentObject, json, parser ) {
  38148. const nodeDef = json.nodes[ nodeId ];
  38149. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  38150. if ( nodeDef.skin === undefined ) return node; // build skeleton here as well
  38151. let skinEntry;
  38152. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  38153. skinEntry = skin;
  38154. const pendingJoints = [];
  38155. for ( let i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  38156. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  38157. }
  38158. return Promise.all( pendingJoints );
  38159. } ).then( function ( jointNodes ) {
  38160. node.traverse( function ( mesh ) {
  38161. if ( ! mesh.isMesh ) return;
  38162. const bones = [];
  38163. const boneInverses = [];
  38164. for ( let j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  38165. const jointNode = jointNodes[ j ];
  38166. if ( jointNode ) {
  38167. bones.push( jointNode );
  38168. const mat = new THREE.Matrix4();
  38169. if ( skinEntry.inverseBindMatrices !== undefined ) {
  38170. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  38171. }
  38172. boneInverses.push( mat );
  38173. } else {
  38174. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  38175. }
  38176. }
  38177. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  38178. } );
  38179. return node;
  38180. } );
  38181. } ).then( function ( node ) {
  38182. // build node hierachy
  38183. parentObject.add( node );
  38184. const pending = [];
  38185. if ( nodeDef.children ) {
  38186. const children = nodeDef.children;
  38187. for ( let i = 0, il = children.length; i < il; i ++ ) {
  38188. const child = children[ i ];
  38189. pending.push( buildNodeHierarchy( child, node, json, parser ) );
  38190. }
  38191. }
  38192. return Promise.all( pending );
  38193. } );
  38194. }
  38195. /**
  38196. * @param {BufferGeometry} geometry
  38197. * @param {GLTF.Primitive} primitiveDef
  38198. * @param {GLTFParser} parser
  38199. */
  38200. function computeBounds( geometry, primitiveDef, parser ) {
  38201. const attributes = primitiveDef.attributes;
  38202. const box = new THREE.Box3();
  38203. if ( attributes.POSITION !== undefined ) {
  38204. const accessor = parser.json.accessors[ attributes.POSITION ];
  38205. const min = accessor.min;
  38206. const max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38207. if ( min !== undefined && max !== undefined ) {
  38208. box.set( new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  38209. if ( accessor.normalized ) {
  38210. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  38211. box.min.multiplyScalar( boxScale );
  38212. box.max.multiplyScalar( boxScale );
  38213. }
  38214. } else {
  38215. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38216. return;
  38217. }
  38218. } else {
  38219. return;
  38220. }
  38221. const targets = primitiveDef.targets;
  38222. if ( targets !== undefined ) {
  38223. const maxDisplacement = new THREE.Vector3();
  38224. const vector = new THREE.Vector3();
  38225. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  38226. const target = targets[ i ];
  38227. if ( target.POSITION !== undefined ) {
  38228. const accessor = parser.json.accessors[ target.POSITION ];
  38229. const min = accessor.min;
  38230. const max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38231. if ( min !== undefined && max !== undefined ) {
  38232. // we need to get max of absolute components because target weight is [-1,1]
  38233. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  38234. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  38235. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  38236. if ( accessor.normalized ) {
  38237. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  38238. vector.multiplyScalar( boxScale );
  38239. } // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  38240. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  38241. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  38242. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  38243. maxDisplacement.max( vector );
  38244. } else {
  38245. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38246. }
  38247. }
  38248. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  38249. box.expandByVector( maxDisplacement );
  38250. }
  38251. geometry.boundingBox = box;
  38252. const sphere = new THREE.Sphere();
  38253. box.getCenter( sphere.center );
  38254. sphere.radius = box.min.distanceTo( box.max ) / 2;
  38255. geometry.boundingSphere = sphere;
  38256. }
  38257. /**
  38258. * @param {BufferGeometry} geometry
  38259. * @param {GLTF.Primitive} primitiveDef
  38260. * @param {GLTFParser} parser
  38261. * @return {Promise<BufferGeometry>}
  38262. */
  38263. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  38264. const attributes = primitiveDef.attributes;
  38265. const pending = [];
  38266. function assignAttributeAccessor( accessorIndex, attributeName ) {
  38267. return parser.getDependency( 'accessor', accessorIndex ).then( function ( accessor ) {
  38268. geometry.setAttribute( attributeName, accessor );
  38269. } );
  38270. }
  38271. for ( const gltfAttributeName in attributes ) {
  38272. const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  38273. if ( threeAttributeName in geometry.attributes ) continue;
  38274. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  38275. }
  38276. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  38277. const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  38278. geometry.setIndex( accessor );
  38279. } );
  38280. pending.push( accessor );
  38281. }
  38282. assignExtrasToUserData( geometry, primitiveDef );
  38283. computeBounds( geometry, primitiveDef, parser );
  38284. return Promise.all( pending ).then( function () {
  38285. return primitiveDef.targets !== undefined ? addMorphTargets( geometry, primitiveDef.targets, parser ) : geometry;
  38286. } );
  38287. }
  38288. /**
  38289. * @param {BufferGeometry} geometry
  38290. * @param {Number} drawMode
  38291. * @return {BufferGeometry}
  38292. */
  38293. function toTrianglesDrawMode( geometry, drawMode ) {
  38294. let index = geometry.getIndex(); // generate index if not present
  38295. if ( index === null ) {
  38296. const indices = [];
  38297. const position = geometry.getAttribute( 'position' );
  38298. if ( position !== undefined ) {
  38299. for ( let i = 0; i < position.count; i ++ ) {
  38300. indices.push( i );
  38301. }
  38302. geometry.setIndex( indices );
  38303. index = geometry.getIndex();
  38304. } else {
  38305. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  38306. return geometry;
  38307. }
  38308. } //
  38309. const numberOfTriangles = index.count - 2;
  38310. const newIndices = [];
  38311. if ( drawMode === THREE.TriangleFanDrawMode ) {
  38312. // gl.TRIANGLE_FAN
  38313. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  38314. newIndices.push( index.getX( 0 ) );
  38315. newIndices.push( index.getX( i ) );
  38316. newIndices.push( index.getX( i + 1 ) );
  38317. }
  38318. } else {
  38319. // gl.TRIANGLE_STRIP
  38320. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  38321. if ( i % 2 === 0 ) {
  38322. newIndices.push( index.getX( i ) );
  38323. newIndices.push( index.getX( i + 1 ) );
  38324. newIndices.push( index.getX( i + 2 ) );
  38325. } else {
  38326. newIndices.push( index.getX( i + 2 ) );
  38327. newIndices.push( index.getX( i + 1 ) );
  38328. newIndices.push( index.getX( i ) );
  38329. }
  38330. }
  38331. }
  38332. if ( newIndices.length / 3 !== numberOfTriangles ) {
  38333. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  38334. } // build final geometry
  38335. const newGeometry = geometry.clone();
  38336. newGeometry.setIndex( newIndices );
  38337. return newGeometry;
  38338. }
  38339. THREE.GLTFLoader = GLTFLoader;
  38340. } )();
  38341. },{}],61:[function(require,module,exports){
  38342. ( function () {
  38343. /**
  38344. * Loads a Wavefront .mtl file specifying materials
  38345. */
  38346. class MTLLoader extends THREE.Loader {
  38347. constructor( manager ) {
  38348. super( manager );
  38349. }
  38350. /**
  38351. * Loads and parses a MTL asset from a URL.
  38352. *
  38353. * @param {String} url - URL to the MTL file.
  38354. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  38355. * @param {Function} [onProgress] - Callback for download progress.
  38356. * @param {Function} [onError] - Callback for download errors.
  38357. *
  38358. * @see setPath setResourcePath
  38359. *
  38360. * @note In order for relative texture references to resolve correctly
  38361. * you must call setResourcePath() explicitly prior to load.
  38362. */
  38363. load( url, onLoad, onProgress, onError ) {
  38364. const scope = this;
  38365. const path = this.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  38366. const loader = new THREE.FileLoader( this.manager );
  38367. loader.setPath( this.path );
  38368. loader.setRequestHeader( this.requestHeader );
  38369. loader.setWithCredentials( this.withCredentials );
  38370. loader.load( url, function ( text ) {
  38371. try {
  38372. onLoad( scope.parse( text, path ) );
  38373. } catch ( e ) {
  38374. if ( onError ) {
  38375. onError( e );
  38376. } else {
  38377. console.error( e );
  38378. }
  38379. scope.manager.itemError( url );
  38380. }
  38381. }, onProgress, onError );
  38382. }
  38383. setMaterialOptions( value ) {
  38384. this.materialOptions = value;
  38385. return this;
  38386. }
  38387. /**
  38388. * Parses a MTL file.
  38389. *
  38390. * @param {String} text - Content of MTL file
  38391. * @return {MaterialCreator}
  38392. *
  38393. * @see setPath setResourcePath
  38394. *
  38395. * @note In order for relative texture references to resolve correctly
  38396. * you must call setResourcePath() explicitly prior to parse.
  38397. */
  38398. parse( text, path ) {
  38399. const lines = text.split( '\n' );
  38400. let info = {};
  38401. const delimiter_pattern = /\s+/;
  38402. const materialsInfo = {};
  38403. for ( let i = 0; i < lines.length; i ++ ) {
  38404. let line = lines[ i ];
  38405. line = line.trim();
  38406. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  38407. // Blank line or comment ignore
  38408. continue;
  38409. }
  38410. const pos = line.indexOf( ' ' );
  38411. let key = pos >= 0 ? line.substring( 0, pos ) : line;
  38412. key = key.toLowerCase();
  38413. let value = pos >= 0 ? line.substring( pos + 1 ) : '';
  38414. value = value.trim();
  38415. if ( key === 'newmtl' ) {
  38416. // New material
  38417. info = {
  38418. name: value
  38419. };
  38420. materialsInfo[ value ] = info;
  38421. } else {
  38422. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  38423. const ss = value.split( delimiter_pattern, 3 );
  38424. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  38425. } else {
  38426. info[ key ] = value;
  38427. }
  38428. }
  38429. }
  38430. const materialCreator = new MaterialCreator( this.resourcePath || path, this.materialOptions );
  38431. materialCreator.setCrossOrigin( this.crossOrigin );
  38432. materialCreator.setManager( this.manager );
  38433. materialCreator.setMaterials( materialsInfo );
  38434. return materialCreator;
  38435. }
  38436. }
  38437. /**
  38438. * Create a new MTLLoader.MaterialCreator
  38439. * @param baseUrl - Url relative to which textures are loaded
  38440. * @param options - Set of options on how to construct the materials
  38441. * side: Which side to apply the material
  38442. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  38443. * wrap: What type of wrapping to apply for textures
  38444. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  38445. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  38446. * Default: false, assumed to be already normalized
  38447. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  38448. * Default: false
  38449. * @constructor
  38450. */
  38451. class MaterialCreator {
  38452. constructor( baseUrl = '', options = {} ) {
  38453. this.baseUrl = baseUrl;
  38454. this.options = options;
  38455. this.materialsInfo = {};
  38456. this.materials = {};
  38457. this.materialsArray = [];
  38458. this.nameLookup = {};
  38459. this.crossOrigin = 'anonymous';
  38460. this.side = this.options.side !== undefined ? this.options.side : THREE.FrontSide;
  38461. this.wrap = this.options.wrap !== undefined ? this.options.wrap : THREE.RepeatWrapping;
  38462. }
  38463. setCrossOrigin( value ) {
  38464. this.crossOrigin = value;
  38465. return this;
  38466. }
  38467. setManager( value ) {
  38468. this.manager = value;
  38469. }
  38470. setMaterials( materialsInfo ) {
  38471. this.materialsInfo = this.convert( materialsInfo );
  38472. this.materials = {};
  38473. this.materialsArray = [];
  38474. this.nameLookup = {};
  38475. }
  38476. convert( materialsInfo ) {
  38477. if ( ! this.options ) return materialsInfo;
  38478. const converted = {};
  38479. for ( const mn in materialsInfo ) {
  38480. // Convert materials info into normalized form based on options
  38481. const mat = materialsInfo[ mn ];
  38482. const covmat = {};
  38483. converted[ mn ] = covmat;
  38484. for ( const prop in mat ) {
  38485. let save = true;
  38486. let value = mat[ prop ];
  38487. const lprop = prop.toLowerCase();
  38488. switch ( lprop ) {
  38489. case 'kd':
  38490. case 'ka':
  38491. case 'ks':
  38492. // Diffuse color (color under white light) using RGB values
  38493. if ( this.options && this.options.normalizeRGB ) {
  38494. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  38495. }
  38496. if ( this.options && this.options.ignoreZeroRGBs ) {
  38497. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  38498. // ignore
  38499. save = false;
  38500. }
  38501. }
  38502. break;
  38503. default:
  38504. break;
  38505. }
  38506. if ( save ) {
  38507. covmat[ lprop ] = value;
  38508. }
  38509. }
  38510. }
  38511. return converted;
  38512. }
  38513. preload() {
  38514. for ( const mn in this.materialsInfo ) {
  38515. this.create( mn );
  38516. }
  38517. }
  38518. getIndex( materialName ) {
  38519. return this.nameLookup[ materialName ];
  38520. }
  38521. getAsArray() {
  38522. let index = 0;
  38523. for ( const mn in this.materialsInfo ) {
  38524. this.materialsArray[ index ] = this.create( mn );
  38525. this.nameLookup[ mn ] = index;
  38526. index ++;
  38527. }
  38528. return this.materialsArray;
  38529. }
  38530. create( materialName ) {
  38531. if ( this.materials[ materialName ] === undefined ) {
  38532. this.createMaterial_( materialName );
  38533. }
  38534. return this.materials[ materialName ];
  38535. }
  38536. createMaterial_( materialName ) {
  38537. // Create material
  38538. const scope = this;
  38539. const mat = this.materialsInfo[ materialName ];
  38540. const params = {
  38541. name: materialName,
  38542. side: this.side
  38543. };
  38544. function resolveURL( baseUrl, url ) {
  38545. if ( typeof url !== 'string' || url === '' ) return ''; // Absolute URL
  38546. if ( /^https?:\/\//i.test( url ) ) return url;
  38547. return baseUrl + url;
  38548. }
  38549. function setMapForType( mapType, value ) {
  38550. if ( params[ mapType ] ) return; // Keep the first encountered texture
  38551. const texParams = scope.getTextureParams( value, params );
  38552. const map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  38553. map.repeat.copy( texParams.scale );
  38554. map.offset.copy( texParams.offset );
  38555. map.wrapS = scope.wrap;
  38556. map.wrapT = scope.wrap;
  38557. params[ mapType ] = map;
  38558. }
  38559. for ( const prop in mat ) {
  38560. const value = mat[ prop ];
  38561. let n;
  38562. if ( value === '' ) continue;
  38563. switch ( prop.toLowerCase() ) {
  38564. // Ns is material specular exponent
  38565. case 'kd':
  38566. // Diffuse color (color under white light) using RGB values
  38567. params.color = new THREE.Color().fromArray( value );
  38568. break;
  38569. case 'ks':
  38570. // Specular color (color when light is reflected from shiny surface) using RGB values
  38571. params.specular = new THREE.Color().fromArray( value );
  38572. break;
  38573. case 'ke':
  38574. // Emissive using RGB values
  38575. params.emissive = new THREE.Color().fromArray( value );
  38576. break;
  38577. case 'map_kd':
  38578. // Diffuse texture map
  38579. setMapForType( 'map', value );
  38580. break;
  38581. case 'map_ks':
  38582. // Specular map
  38583. setMapForType( 'specularMap', value );
  38584. break;
  38585. case 'map_ke':
  38586. // Emissive map
  38587. setMapForType( 'emissiveMap', value );
  38588. break;
  38589. case 'norm':
  38590. setMapForType( 'normalMap', value );
  38591. break;
  38592. case 'map_bump':
  38593. case 'bump':
  38594. // Bump texture map
  38595. setMapForType( 'bumpMap', value );
  38596. break;
  38597. case 'map_d':
  38598. // Alpha map
  38599. setMapForType( 'alphaMap', value );
  38600. params.transparent = true;
  38601. break;
  38602. case 'ns':
  38603. // The specular exponent (defines the focus of the specular highlight)
  38604. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  38605. params.shininess = parseFloat( value );
  38606. break;
  38607. case 'd':
  38608. n = parseFloat( value );
  38609. if ( n < 1 ) {
  38610. params.opacity = n;
  38611. params.transparent = true;
  38612. }
  38613. break;
  38614. case 'tr':
  38615. n = parseFloat( value );
  38616. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  38617. if ( n > 0 ) {
  38618. params.opacity = 1 - n;
  38619. params.transparent = true;
  38620. }
  38621. break;
  38622. default:
  38623. break;
  38624. }
  38625. }
  38626. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  38627. return this.materials[ materialName ];
  38628. }
  38629. getTextureParams( value, matParams ) {
  38630. const texParams = {
  38631. scale: new THREE.Vector2( 1, 1 ),
  38632. offset: new THREE.Vector2( 0, 0 )
  38633. };
  38634. const items = value.split( /\s+/ );
  38635. let pos;
  38636. pos = items.indexOf( '-bm' );
  38637. if ( pos >= 0 ) {
  38638. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  38639. items.splice( pos, 2 );
  38640. }
  38641. pos = items.indexOf( '-s' );
  38642. if ( pos >= 0 ) {
  38643. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  38644. items.splice( pos, 4 ); // we expect 3 parameters here!
  38645. }
  38646. pos = items.indexOf( '-o' );
  38647. if ( pos >= 0 ) {
  38648. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  38649. items.splice( pos, 4 ); // we expect 3 parameters here!
  38650. }
  38651. texParams.url = items.join( ' ' ).trim();
  38652. return texParams;
  38653. }
  38654. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  38655. const manager = this.manager !== undefined ? this.manager : THREE.DefaultLoadingManager;
  38656. let loader = manager.getHandler( url );
  38657. if ( loader === null ) {
  38658. loader = new THREE.TextureLoader( manager );
  38659. }
  38660. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  38661. const texture = loader.load( url, onLoad, onProgress, onError );
  38662. if ( mapping !== undefined ) texture.mapping = mapping;
  38663. return texture;
  38664. }
  38665. }
  38666. THREE.MTLLoader = MTLLoader;
  38667. } )();
  38668. },{}],62:[function(require,module,exports){
  38669. ( function () {
  38670. const _object_pattern = /^[og]\s*(.+)?/; // mtllib file_reference
  38671. const _material_library_pattern = /^mtllib /; // usemtl material_name
  38672. const _material_use_pattern = /^usemtl /; // usemap map_name
  38673. const _map_use_pattern = /^usemap /;
  38674. const _vA = new THREE.Vector3();
  38675. const _vB = new THREE.Vector3();
  38676. const _vC = new THREE.Vector3();
  38677. const _ab = new THREE.Vector3();
  38678. const _cb = new THREE.Vector3();
  38679. function ParserState() {
  38680. const state = {
  38681. objects: [],
  38682. object: {},
  38683. vertices: [],
  38684. normals: [],
  38685. colors: [],
  38686. uvs: [],
  38687. materials: {},
  38688. materialLibraries: [],
  38689. startObject: function ( name, fromDeclaration ) {
  38690. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  38691. // file. We need to use it for the first parsed g/o to keep things in sync.
  38692. if ( this.object && this.object.fromDeclaration === false ) {
  38693. this.object.name = name;
  38694. this.object.fromDeclaration = fromDeclaration !== false;
  38695. return;
  38696. }
  38697. const previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined;
  38698. if ( this.object && typeof this.object._finalize === 'function' ) {
  38699. this.object._finalize( true );
  38700. }
  38701. this.object = {
  38702. name: name || '',
  38703. fromDeclaration: fromDeclaration !== false,
  38704. geometry: {
  38705. vertices: [],
  38706. normals: [],
  38707. colors: [],
  38708. uvs: [],
  38709. hasUVIndices: false
  38710. },
  38711. materials: [],
  38712. smooth: true,
  38713. startMaterial: function ( name, libraries ) {
  38714. const previous = this._finalize( false ); // New usemtl declaration overwrites an inherited material, except if faces were declared
  38715. // after the material, then it must be preserved for proper MultiMaterial continuation.
  38716. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  38717. this.materials.splice( previous.index, 1 );
  38718. }
  38719. const material = {
  38720. index: this.materials.length,
  38721. name: name || '',
  38722. mtllib: Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '',
  38723. smooth: previous !== undefined ? previous.smooth : this.smooth,
  38724. groupStart: previous !== undefined ? previous.groupEnd : 0,
  38725. groupEnd: - 1,
  38726. groupCount: - 1,
  38727. inherited: false,
  38728. clone: function ( index ) {
  38729. const cloned = {
  38730. index: typeof index === 'number' ? index : this.index,
  38731. name: this.name,
  38732. mtllib: this.mtllib,
  38733. smooth: this.smooth,
  38734. groupStart: 0,
  38735. groupEnd: - 1,
  38736. groupCount: - 1,
  38737. inherited: false
  38738. };
  38739. cloned.clone = this.clone.bind( cloned );
  38740. return cloned;
  38741. }
  38742. };
  38743. this.materials.push( material );
  38744. return material;
  38745. },
  38746. currentMaterial: function () {
  38747. if ( this.materials.length > 0 ) {
  38748. return this.materials[ this.materials.length - 1 ];
  38749. }
  38750. return undefined;
  38751. },
  38752. _finalize: function ( end ) {
  38753. const lastMultiMaterial = this.currentMaterial();
  38754. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  38755. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  38756. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  38757. lastMultiMaterial.inherited = false;
  38758. } // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  38759. if ( end && this.materials.length > 1 ) {
  38760. for ( let mi = this.materials.length - 1; mi >= 0; mi -- ) {
  38761. if ( this.materials[ mi ].groupCount <= 0 ) {
  38762. this.materials.splice( mi, 1 );
  38763. }
  38764. }
  38765. } // Guarantee at least one empty material, this makes the creation later more straight forward.
  38766. if ( end && this.materials.length === 0 ) {
  38767. this.materials.push( {
  38768. name: '',
  38769. smooth: this.smooth
  38770. } );
  38771. }
  38772. return lastMultiMaterial;
  38773. }
  38774. }; // Inherit previous objects material.
  38775. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  38776. // If a usemtl declaration is encountered while this new object is being parsed, it will
  38777. // overwrite the inherited material. Exception being that there was already face declarations
  38778. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  38779. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  38780. const declared = previousMaterial.clone( 0 );
  38781. declared.inherited = true;
  38782. this.object.materials.push( declared );
  38783. }
  38784. this.objects.push( this.object );
  38785. },
  38786. finalize: function () {
  38787. if ( this.object && typeof this.object._finalize === 'function' ) {
  38788. this.object._finalize( true );
  38789. }
  38790. },
  38791. parseVertexIndex: function ( value, len ) {
  38792. const index = parseInt( value, 10 );
  38793. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38794. },
  38795. parseNormalIndex: function ( value, len ) {
  38796. const index = parseInt( value, 10 );
  38797. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  38798. },
  38799. parseUVIndex: function ( value, len ) {
  38800. const index = parseInt( value, 10 );
  38801. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  38802. },
  38803. addVertex: function ( a, b, c ) {
  38804. const src = this.vertices;
  38805. const dst = this.object.geometry.vertices;
  38806. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38807. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38808. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38809. },
  38810. addVertexPoint: function ( a ) {
  38811. const src = this.vertices;
  38812. const dst = this.object.geometry.vertices;
  38813. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38814. },
  38815. addVertexLine: function ( a ) {
  38816. const src = this.vertices;
  38817. const dst = this.object.geometry.vertices;
  38818. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38819. },
  38820. addNormal: function ( a, b, c ) {
  38821. const src = this.normals;
  38822. const dst = this.object.geometry.normals;
  38823. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38824. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38825. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38826. },
  38827. addFaceNormal: function ( a, b, c ) {
  38828. const src = this.vertices;
  38829. const dst = this.object.geometry.normals;
  38830. _vA.fromArray( src, a );
  38831. _vB.fromArray( src, b );
  38832. _vC.fromArray( src, c );
  38833. _cb.subVectors( _vC, _vB );
  38834. _ab.subVectors( _vA, _vB );
  38835. _cb.cross( _ab );
  38836. _cb.normalize();
  38837. dst.push( _cb.x, _cb.y, _cb.z );
  38838. dst.push( _cb.x, _cb.y, _cb.z );
  38839. dst.push( _cb.x, _cb.y, _cb.z );
  38840. },
  38841. addColor: function ( a, b, c ) {
  38842. const src = this.colors;
  38843. const dst = this.object.geometry.colors;
  38844. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  38845. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  38846. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  38847. },
  38848. addUV: function ( a, b, c ) {
  38849. const src = this.uvs;
  38850. const dst = this.object.geometry.uvs;
  38851. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38852. dst.push( src[ b + 0 ], src[ b + 1 ] );
  38853. dst.push( src[ c + 0 ], src[ c + 1 ] );
  38854. },
  38855. addDefaultUV: function () {
  38856. const dst = this.object.geometry.uvs;
  38857. dst.push( 0, 0 );
  38858. dst.push( 0, 0 );
  38859. dst.push( 0, 0 );
  38860. },
  38861. addUVLine: function ( a ) {
  38862. const src = this.uvs;
  38863. const dst = this.object.geometry.uvs;
  38864. dst.push( src[ a + 0 ], src[ a + 1 ] );
  38865. },
  38866. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  38867. const vLen = this.vertices.length;
  38868. let ia = this.parseVertexIndex( a, vLen );
  38869. let ib = this.parseVertexIndex( b, vLen );
  38870. let ic = this.parseVertexIndex( c, vLen );
  38871. this.addVertex( ia, ib, ic );
  38872. this.addColor( ia, ib, ic ); // normals
  38873. if ( na !== undefined && na !== '' ) {
  38874. const nLen = this.normals.length;
  38875. ia = this.parseNormalIndex( na, nLen );
  38876. ib = this.parseNormalIndex( nb, nLen );
  38877. ic = this.parseNormalIndex( nc, nLen );
  38878. this.addNormal( ia, ib, ic );
  38879. } else {
  38880. this.addFaceNormal( ia, ib, ic );
  38881. } // uvs
  38882. if ( ua !== undefined && ua !== '' ) {
  38883. const uvLen = this.uvs.length;
  38884. ia = this.parseUVIndex( ua, uvLen );
  38885. ib = this.parseUVIndex( ub, uvLen );
  38886. ic = this.parseUVIndex( uc, uvLen );
  38887. this.addUV( ia, ib, ic );
  38888. this.object.geometry.hasUVIndices = true;
  38889. } else {
  38890. // add placeholder values (for inconsistent face definitions)
  38891. this.addDefaultUV();
  38892. }
  38893. },
  38894. addPointGeometry: function ( vertices ) {
  38895. this.object.geometry.type = 'Points';
  38896. const vLen = this.vertices.length;
  38897. for ( let vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38898. const index = this.parseVertexIndex( vertices[ vi ], vLen );
  38899. this.addVertexPoint( index );
  38900. this.addColor( index );
  38901. }
  38902. },
  38903. addLineGeometry: function ( vertices, uvs ) {
  38904. this.object.geometry.type = 'Line';
  38905. const vLen = this.vertices.length;
  38906. const uvLen = this.uvs.length;
  38907. for ( let vi = 0, l = vertices.length; vi < l; vi ++ ) {
  38908. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  38909. }
  38910. for ( let uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  38911. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  38912. }
  38913. }
  38914. };
  38915. state.startObject( '', false );
  38916. return state;
  38917. } //
  38918. class OBJLoader extends THREE.Loader {
  38919. constructor( manager ) {
  38920. super( manager );
  38921. this.materials = null;
  38922. }
  38923. load( url, onLoad, onProgress, onError ) {
  38924. const scope = this;
  38925. const loader = new THREE.FileLoader( this.manager );
  38926. loader.setPath( this.path );
  38927. loader.setRequestHeader( this.requestHeader );
  38928. loader.setWithCredentials( this.withCredentials );
  38929. loader.load( url, function ( text ) {
  38930. try {
  38931. onLoad( scope.parse( text ) );
  38932. } catch ( e ) {
  38933. if ( onError ) {
  38934. onError( e );
  38935. } else {
  38936. console.error( e );
  38937. }
  38938. scope.manager.itemError( url );
  38939. }
  38940. }, onProgress, onError );
  38941. }
  38942. setMaterials( materials ) {
  38943. this.materials = materials;
  38944. return this;
  38945. }
  38946. parse( text ) {
  38947. const state = new ParserState();
  38948. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  38949. // This is faster than String.split with regex that splits on both
  38950. text = text.replace( /\r\n/g, '\n' );
  38951. }
  38952. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  38953. // join lines separated by a line continuation character (\)
  38954. text = text.replace( /\\\n/g, '' );
  38955. }
  38956. const lines = text.split( '\n' );
  38957. let line = '',
  38958. lineFirstChar = '';
  38959. let lineLength = 0;
  38960. let result = []; // Faster to just trim left side of the line. Use if available.
  38961. const trimLeft = typeof ''.trimLeft === 'function';
  38962. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  38963. line = lines[ i ];
  38964. line = trimLeft ? line.trimLeft() : line.trim();
  38965. lineLength = line.length;
  38966. if ( lineLength === 0 ) continue;
  38967. lineFirstChar = line.charAt( 0 ); // @todo invoke passed in handler if any
  38968. if ( lineFirstChar === '#' ) continue;
  38969. if ( lineFirstChar === 'v' ) {
  38970. const data = line.split( /\s+/ );
  38971. switch ( data[ 0 ] ) {
  38972. case 'v':
  38973. state.vertices.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ), parseFloat( data[ 3 ] ) );
  38974. if ( data.length >= 7 ) {
  38975. state.colors.push( parseFloat( data[ 4 ] ), parseFloat( data[ 5 ] ), parseFloat( data[ 6 ] ) );
  38976. } else {
  38977. // if no colors are defined, add placeholders so color and vertex indices match
  38978. state.colors.push( undefined, undefined, undefined );
  38979. }
  38980. break;
  38981. case 'vn':
  38982. state.normals.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ), parseFloat( data[ 3 ] ) );
  38983. break;
  38984. case 'vt':
  38985. state.uvs.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ) );
  38986. break;
  38987. }
  38988. } else if ( lineFirstChar === 'f' ) {
  38989. const lineData = line.substr( 1 ).trim();
  38990. const vertexData = lineData.split( /\s+/ );
  38991. const faceVertices = []; // Parse the face vertex data into an easy to work with format
  38992. for ( let j = 0, jl = vertexData.length; j < jl; j ++ ) {
  38993. const vertex = vertexData[ j ];
  38994. if ( vertex.length > 0 ) {
  38995. const vertexParts = vertex.split( '/' );
  38996. faceVertices.push( vertexParts );
  38997. }
  38998. } // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  38999. const v1 = faceVertices[ 0 ];
  39000. for ( let j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  39001. const v2 = faceVertices[ j ];
  39002. const v3 = faceVertices[ j + 1 ];
  39003. state.addFace( v1[ 0 ], v2[ 0 ], v3[ 0 ], v1[ 1 ], v2[ 1 ], v3[ 1 ], v1[ 2 ], v2[ 2 ], v3[ 2 ] );
  39004. }
  39005. } else if ( lineFirstChar === 'l' ) {
  39006. const lineParts = line.substring( 1 ).trim().split( ' ' );
  39007. let lineVertices = [];
  39008. const lineUVs = [];
  39009. if ( line.indexOf( '/' ) === - 1 ) {
  39010. lineVertices = lineParts;
  39011. } else {
  39012. for ( let li = 0, llen = lineParts.length; li < llen; li ++ ) {
  39013. const parts = lineParts[ li ].split( '/' );
  39014. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  39015. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  39016. }
  39017. }
  39018. state.addLineGeometry( lineVertices, lineUVs );
  39019. } else if ( lineFirstChar === 'p' ) {
  39020. const lineData = line.substr( 1 ).trim();
  39021. const pointData = lineData.split( ' ' );
  39022. state.addPointGeometry( pointData );
  39023. } else if ( ( result = _object_pattern.exec( line ) ) !== null ) {
  39024. // o object_name
  39025. // or
  39026. // g group_name
  39027. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  39028. // let name = result[ 0 ].substr( 1 ).trim();
  39029. const name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  39030. state.startObject( name );
  39031. } else if ( _material_use_pattern.test( line ) ) {
  39032. // material
  39033. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  39034. } else if ( _material_library_pattern.test( line ) ) {
  39035. // mtl file
  39036. state.materialLibraries.push( line.substring( 7 ).trim() );
  39037. } else if ( _map_use_pattern.test( line ) ) {
  39038. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  39039. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  39040. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  39041. } else if ( lineFirstChar === 's' ) {
  39042. result = line.split( ' ' ); // smooth shading
  39043. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  39044. // but does not define a usemtl for each face set.
  39045. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  39046. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  39047. // where explicit usemtl defines geometry groups.
  39048. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  39049. /*
  39050. * http://paulbourke.net/dataformats/obj/
  39051. * or
  39052. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  39053. *
  39054. * From chapter "Grouping" Syntax explanation "s group_number":
  39055. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  39056. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  39057. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  39058. * than 0."
  39059. */
  39060. if ( result.length > 1 ) {
  39061. const value = result[ 1 ].trim().toLowerCase();
  39062. state.object.smooth = value !== '0' && value !== 'off';
  39063. } else {
  39064. // ZBrush can produce "s" lines #11707
  39065. state.object.smooth = true;
  39066. }
  39067. const material = state.object.currentMaterial();
  39068. if ( material ) material.smooth = state.object.smooth;
  39069. } else {
  39070. // Handle null terminated files without exception
  39071. if ( line === '\0' ) continue;
  39072. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  39073. }
  39074. }
  39075. state.finalize();
  39076. const container = new THREE.Group();
  39077. container.materialLibraries = [].concat( state.materialLibraries );
  39078. const hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  39079. if ( hasPrimitives === true ) {
  39080. for ( let i = 0, l = state.objects.length; i < l; i ++ ) {
  39081. const object = state.objects[ i ];
  39082. const geometry = object.geometry;
  39083. const materials = object.materials;
  39084. const isLine = geometry.type === 'Line';
  39085. const isPoints = geometry.type === 'Points';
  39086. let hasVertexColors = false; // Skip o/g line declarations that did not follow with any faces
  39087. if ( geometry.vertices.length === 0 ) continue;
  39088. const buffergeometry = new THREE.BufferGeometry();
  39089. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  39090. if ( geometry.normals.length > 0 ) {
  39091. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  39092. }
  39093. if ( geometry.colors.length > 0 ) {
  39094. hasVertexColors = true;
  39095. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  39096. }
  39097. if ( geometry.hasUVIndices === true ) {
  39098. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  39099. } // Create materials
  39100. const createdMaterials = [];
  39101. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39102. const sourceMaterial = materials[ mi ];
  39103. const materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  39104. let material = state.materials[ materialHash ];
  39105. if ( this.materials !== null ) {
  39106. material = this.materials.create( sourceMaterial.name ); // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  39107. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  39108. const materialLine = new THREE.LineBasicMaterial();
  39109. THREE.Material.prototype.copy.call( materialLine, material );
  39110. materialLine.color.copy( material.color );
  39111. material = materialLine;
  39112. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  39113. const materialPoints = new THREE.PointsMaterial( {
  39114. size: 10,
  39115. sizeAttenuation: false
  39116. } );
  39117. THREE.Material.prototype.copy.call( materialPoints, material );
  39118. materialPoints.color.copy( material.color );
  39119. materialPoints.map = material.map;
  39120. material = materialPoints;
  39121. }
  39122. }
  39123. if ( material === undefined ) {
  39124. if ( isLine ) {
  39125. material = new THREE.LineBasicMaterial();
  39126. } else if ( isPoints ) {
  39127. material = new THREE.PointsMaterial( {
  39128. size: 1,
  39129. sizeAttenuation: false
  39130. } );
  39131. } else {
  39132. material = new THREE.MeshPhongMaterial();
  39133. }
  39134. material.name = sourceMaterial.name;
  39135. material.flatShading = sourceMaterial.smooth ? false : true;
  39136. material.vertexColors = hasVertexColors;
  39137. state.materials[ materialHash ] = material;
  39138. }
  39139. createdMaterials.push( material );
  39140. } // Create mesh
  39141. let mesh;
  39142. if ( createdMaterials.length > 1 ) {
  39143. for ( let mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39144. const sourceMaterial = materials[ mi ];
  39145. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  39146. }
  39147. if ( isLine ) {
  39148. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  39149. } else if ( isPoints ) {
  39150. mesh = new THREE.Points( buffergeometry, createdMaterials );
  39151. } else {
  39152. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  39153. }
  39154. } else {
  39155. if ( isLine ) {
  39156. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  39157. } else if ( isPoints ) {
  39158. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  39159. } else {
  39160. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  39161. }
  39162. }
  39163. mesh.name = object.name;
  39164. container.add( mesh );
  39165. }
  39166. } else {
  39167. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  39168. if ( state.vertices.length > 0 ) {
  39169. const material = new THREE.PointsMaterial( {
  39170. size: 1,
  39171. sizeAttenuation: false
  39172. } );
  39173. const buffergeometry = new THREE.BufferGeometry();
  39174. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( state.vertices, 3 ) );
  39175. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  39176. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( state.colors, 3 ) );
  39177. material.vertexColors = true;
  39178. }
  39179. const points = new THREE.Points( buffergeometry, material );
  39180. container.add( points );
  39181. }
  39182. }
  39183. return container;
  39184. }
  39185. }
  39186. THREE.OBJLoader = OBJLoader;
  39187. } )();
  39188. },{}],63:[function(require,module,exports){
  39189. ( function () {
  39190. function computeTangents( geometry ) {
  39191. geometry.computeTangents();
  39192. console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use THREE.BufferGeometry.computeTangents() instead.' );
  39193. }
  39194. /**
  39195. * @param {Array<BufferGeometry>} geometries
  39196. * @param {Boolean} useGroups
  39197. * @return {BufferGeometry}
  39198. */
  39199. function mergeBufferGeometries( geometries, useGroups = false ) {
  39200. const isIndexed = geometries[ 0 ].index !== null;
  39201. const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  39202. const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  39203. const attributes = {};
  39204. const morphAttributes = {};
  39205. const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  39206. const mergedGeometry = new THREE.BufferGeometry();
  39207. let offset = 0;
  39208. for ( let i = 0; i < geometries.length; ++ i ) {
  39209. const geometry = geometries[ i ];
  39210. let attributesCount = 0; // ensure that all geometries are indexed, or none
  39211. if ( isIndexed !== ( geometry.index !== null ) ) {
  39212. 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.' );
  39213. return null;
  39214. } // gather attributes, exit early if they're different
  39215. for ( const name in geometry.attributes ) {
  39216. if ( ! attributesUsed.has( name ) ) {
  39217. 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.' );
  39218. return null;
  39219. }
  39220. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  39221. attributes[ name ].push( geometry.attributes[ name ] );
  39222. attributesCount ++;
  39223. } // ensure geometries have the same number of attributes
  39224. if ( attributesCount !== attributesUsed.size ) {
  39225. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  39226. return null;
  39227. } // gather morph attributes, exit early if they're different
  39228. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  39229. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  39230. return null;
  39231. }
  39232. for ( const name in geometry.morphAttributes ) {
  39233. if ( ! morphAttributesUsed.has( name ) ) {
  39234. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  39235. return null;
  39236. }
  39237. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  39238. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  39239. } // gather .userData
  39240. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  39241. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  39242. if ( useGroups ) {
  39243. let count;
  39244. if ( isIndexed ) {
  39245. count = geometry.index.count;
  39246. } else if ( geometry.attributes.position !== undefined ) {
  39247. count = geometry.attributes.position.count;
  39248. } else {
  39249. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  39250. return null;
  39251. }
  39252. mergedGeometry.addGroup( offset, count, i );
  39253. offset += count;
  39254. }
  39255. } // merge indices
  39256. if ( isIndexed ) {
  39257. let indexOffset = 0;
  39258. const mergedIndex = [];
  39259. for ( let i = 0; i < geometries.length; ++ i ) {
  39260. const index = geometries[ i ].index;
  39261. for ( let j = 0; j < index.count; ++ j ) {
  39262. mergedIndex.push( index.getX( j ) + indexOffset );
  39263. }
  39264. indexOffset += geometries[ i ].attributes.position.count;
  39265. }
  39266. mergedGeometry.setIndex( mergedIndex );
  39267. } // merge attributes
  39268. for ( const name in attributes ) {
  39269. const mergedAttribute = mergeBufferAttributes( attributes[ name ] );
  39270. if ( ! mergedAttribute ) {
  39271. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  39272. return null;
  39273. }
  39274. mergedGeometry.setAttribute( name, mergedAttribute );
  39275. } // merge morph attributes
  39276. for ( const name in morphAttributes ) {
  39277. const numMorphTargets = morphAttributes[ name ][ 0 ].length;
  39278. if ( numMorphTargets === 0 ) break;
  39279. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  39280. mergedGeometry.morphAttributes[ name ] = [];
  39281. for ( let i = 0; i < numMorphTargets; ++ i ) {
  39282. const morphAttributesToMerge = [];
  39283. for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
  39284. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  39285. }
  39286. const mergedMorphAttribute = mergeBufferAttributes( morphAttributesToMerge );
  39287. if ( ! mergedMorphAttribute ) {
  39288. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  39289. return null;
  39290. }
  39291. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  39292. }
  39293. }
  39294. return mergedGeometry;
  39295. }
  39296. /**
  39297. * @param {Array<BufferAttribute>} attributes
  39298. * @return {BufferAttribute}
  39299. */
  39300. function mergeBufferAttributes( attributes ) {
  39301. let TypedArray;
  39302. let itemSize;
  39303. let normalized;
  39304. let arrayLength = 0;
  39305. for ( let i = 0; i < attributes.length; ++ i ) {
  39306. const attribute = attributes[ i ];
  39307. if ( attribute.isInterleavedBufferAttribute ) {
  39308. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  39309. return null;
  39310. }
  39311. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  39312. if ( TypedArray !== attribute.array.constructor ) {
  39313. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.array must be of consistent array types across matching attributes.' );
  39314. return null;
  39315. }
  39316. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  39317. if ( itemSize !== attribute.itemSize ) {
  39318. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.itemSize must be consistent across matching attributes.' );
  39319. return null;
  39320. }
  39321. if ( normalized === undefined ) normalized = attribute.normalized;
  39322. if ( normalized !== attribute.normalized ) {
  39323. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.normalized must be consistent across matching attributes.' );
  39324. return null;
  39325. }
  39326. arrayLength += attribute.array.length;
  39327. }
  39328. const array = new TypedArray( arrayLength );
  39329. let offset = 0;
  39330. for ( let i = 0; i < attributes.length; ++ i ) {
  39331. array.set( attributes[ i ].array, offset );
  39332. offset += attributes[ i ].array.length;
  39333. }
  39334. return new THREE.BufferAttribute( array, itemSize, normalized );
  39335. }
  39336. /**
  39337. * @param {Array<BufferAttribute>} attributes
  39338. * @return {Array<InterleavedBufferAttribute>}
  39339. */
  39340. function interleaveAttributes( attributes ) {
  39341. // Interleaves the provided attributes into an THREE.InterleavedBuffer and returns
  39342. // a set of InterleavedBufferAttributes for each attribute
  39343. let TypedArray;
  39344. let arrayLength = 0;
  39345. let stride = 0; // calculate the the length and type of the interleavedBuffer
  39346. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  39347. const attribute = attributes[ i ];
  39348. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  39349. if ( TypedArray !== attribute.array.constructor ) {
  39350. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  39351. return null;
  39352. }
  39353. arrayLength += attribute.array.length;
  39354. stride += attribute.itemSize;
  39355. } // Create the set of buffer attributes
  39356. const interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  39357. let offset = 0;
  39358. const res = [];
  39359. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  39360. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  39361. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  39362. const attribute = attributes[ j ];
  39363. const itemSize = attribute.itemSize;
  39364. const count = attribute.count;
  39365. const iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  39366. res.push( iba );
  39367. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  39368. // at the appropriate offset
  39369. for ( let c = 0; c < count; c ++ ) {
  39370. for ( let k = 0; k < itemSize; k ++ ) {
  39371. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  39372. }
  39373. }
  39374. }
  39375. return res;
  39376. }
  39377. /**
  39378. * @param {Array<BufferGeometry>} geometry
  39379. * @return {number}
  39380. */
  39381. function estimateBytesUsed( geometry ) {
  39382. // Return the estimated memory used by this geometry in bytes
  39383. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  39384. // for InterleavedBufferAttributes.
  39385. let mem = 0;
  39386. for ( const name in geometry.attributes ) {
  39387. const attr = geometry.getAttribute( name );
  39388. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  39389. }
  39390. const indices = geometry.getIndex();
  39391. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  39392. return mem;
  39393. }
  39394. /**
  39395. * @param {BufferGeometry} geometry
  39396. * @param {number} tolerance
  39397. * @return {BufferGeometry>}
  39398. */
  39399. function mergeVertices( geometry, tolerance = 1e-4 ) {
  39400. tolerance = Math.max( tolerance, Number.EPSILON ); // Generate an index buffer if the geometry doesn't have one, or optimize it
  39401. // if it's already available.
  39402. const hashToIndex = {};
  39403. const indices = geometry.getIndex();
  39404. const positions = geometry.getAttribute( 'position' );
  39405. const vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  39406. let nextIndex = 0; // attributes and new attribute arrays
  39407. const attributeNames = Object.keys( geometry.attributes );
  39408. const attrArrays = {};
  39409. const morphAttrsArrays = {};
  39410. const newIndices = [];
  39411. const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; // initialize the arrays
  39412. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  39413. const name = attributeNames[ i ];
  39414. attrArrays[ name ] = [];
  39415. const morphAttr = geometry.morphAttributes[ name ];
  39416. if ( morphAttr ) {
  39417. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  39418. }
  39419. } // convert the error tolerance to an amount of decimal places to truncate to
  39420. const decimalShift = Math.log10( 1 / tolerance );
  39421. const shiftMultiplier = Math.pow( 10, decimalShift );
  39422. for ( let i = 0; i < vertexCount; i ++ ) {
  39423. const index = indices ? indices.getX( i ) : i; // Generate a hash for the vertex attributes at the current index 'i'
  39424. let hash = '';
  39425. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  39426. const name = attributeNames[ j ];
  39427. const attribute = geometry.getAttribute( name );
  39428. const itemSize = attribute.itemSize;
  39429. for ( let k = 0; k < itemSize; k ++ ) {
  39430. // double tilde truncates the decimal value
  39431. hash += `${~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier )},`;
  39432. }
  39433. } // Add another reference to the vertex if it's already
  39434. // used by another index
  39435. if ( hash in hashToIndex ) {
  39436. newIndices.push( hashToIndex[ hash ] );
  39437. } else {
  39438. // copy data to the new index in the attribute arrays
  39439. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  39440. const name = attributeNames[ j ];
  39441. const attribute = geometry.getAttribute( name );
  39442. const morphAttr = geometry.morphAttributes[ name ];
  39443. const itemSize = attribute.itemSize;
  39444. const newarray = attrArrays[ name ];
  39445. const newMorphArrays = morphAttrsArrays[ name ];
  39446. for ( let k = 0; k < itemSize; k ++ ) {
  39447. const getterFunc = getters[ k ];
  39448. newarray.push( attribute[ getterFunc ]( index ) );
  39449. if ( morphAttr ) {
  39450. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  39451. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  39452. }
  39453. }
  39454. }
  39455. }
  39456. hashToIndex[ hash ] = nextIndex;
  39457. newIndices.push( nextIndex );
  39458. nextIndex ++;
  39459. }
  39460. } // Generate typed arrays from new attribute arrays and update
  39461. // the attributeBuffers
  39462. const result = geometry.clone();
  39463. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  39464. const name = attributeNames[ i ];
  39465. const oldAttribute = geometry.getAttribute( name );
  39466. const buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  39467. const attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  39468. result.setAttribute( name, attribute ); // Update the attribute arrays
  39469. if ( name in morphAttrsArrays ) {
  39470. for ( let j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  39471. const oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  39472. const buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  39473. const morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  39474. result.morphAttributes[ name ][ j ] = morphAttribute;
  39475. }
  39476. }
  39477. } // indices
  39478. result.setIndex( newIndices );
  39479. return result;
  39480. }
  39481. /**
  39482. * @param {BufferGeometry} geometry
  39483. * @param {number} drawMode
  39484. * @return {BufferGeometry>}
  39485. */
  39486. function toTrianglesDrawMode( geometry, drawMode ) {
  39487. if ( drawMode === THREE.TrianglesDrawMode ) {
  39488. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  39489. return geometry;
  39490. }
  39491. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  39492. let index = geometry.getIndex(); // generate index if not present
  39493. if ( index === null ) {
  39494. const indices = [];
  39495. const position = geometry.getAttribute( 'position' );
  39496. if ( position !== undefined ) {
  39497. for ( let i = 0; i < position.count; i ++ ) {
  39498. indices.push( i );
  39499. }
  39500. geometry.setIndex( indices );
  39501. index = geometry.getIndex();
  39502. } else {
  39503. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  39504. return geometry;
  39505. }
  39506. } //
  39507. const numberOfTriangles = index.count - 2;
  39508. const newIndices = [];
  39509. if ( drawMode === THREE.TriangleFanDrawMode ) {
  39510. // gl.TRIANGLE_FAN
  39511. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  39512. newIndices.push( index.getX( 0 ) );
  39513. newIndices.push( index.getX( i ) );
  39514. newIndices.push( index.getX( i + 1 ) );
  39515. }
  39516. } else {
  39517. // gl.TRIANGLE_STRIP
  39518. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  39519. if ( i % 2 === 0 ) {
  39520. newIndices.push( index.getX( i ) );
  39521. newIndices.push( index.getX( i + 1 ) );
  39522. newIndices.push( index.getX( i + 2 ) );
  39523. } else {
  39524. newIndices.push( index.getX( i + 2 ) );
  39525. newIndices.push( index.getX( i + 1 ) );
  39526. newIndices.push( index.getX( i ) );
  39527. }
  39528. }
  39529. }
  39530. if ( newIndices.length / 3 !== numberOfTriangles ) {
  39531. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  39532. } // build final geometry
  39533. const newGeometry = geometry.clone();
  39534. newGeometry.setIndex( newIndices );
  39535. newGeometry.clearGroups();
  39536. return newGeometry;
  39537. } else {
  39538. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  39539. return geometry;
  39540. }
  39541. }
  39542. /**
  39543. * Calculates the morphed attributes of a morphed/skinned THREE.BufferGeometry.
  39544. * Helpful for Raytracing or Decals.
  39545. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  39546. * @return {Object} An Object with original position/normal attributes and morphed ones.
  39547. */
  39548. function computeMorphedAttributes( object ) {
  39549. if ( object.geometry.isBufferGeometry !== true ) {
  39550. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type THREE.BufferGeometry.' );
  39551. return null;
  39552. }
  39553. const _vA = new THREE.Vector3();
  39554. const _vB = new THREE.Vector3();
  39555. const _vC = new THREE.Vector3();
  39556. const _tempA = new THREE.Vector3();
  39557. const _tempB = new THREE.Vector3();
  39558. const _tempC = new THREE.Vector3();
  39559. const _morphA = new THREE.Vector3();
  39560. const _morphB = new THREE.Vector3();
  39561. const _morphC = new THREE.Vector3();
  39562. function _calculateMorphedAttributeData( object, material, attribute, morphAttribute, morphTargetsRelative, a, b, c, modifiedAttributeArray ) {
  39563. _vA.fromBufferAttribute( attribute, a );
  39564. _vB.fromBufferAttribute( attribute, b );
  39565. _vC.fromBufferAttribute( attribute, c );
  39566. const morphInfluences = object.morphTargetInfluences;
  39567. if ( material.morphTargets && morphAttribute && morphInfluences ) {
  39568. _morphA.set( 0, 0, 0 );
  39569. _morphB.set( 0, 0, 0 );
  39570. _morphC.set( 0, 0, 0 );
  39571. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  39572. const influence = morphInfluences[ i ];
  39573. const morph = morphAttribute[ i ];
  39574. if ( influence === 0 ) continue;
  39575. _tempA.fromBufferAttribute( morph, a );
  39576. _tempB.fromBufferAttribute( morph, b );
  39577. _tempC.fromBufferAttribute( morph, c );
  39578. if ( morphTargetsRelative ) {
  39579. _morphA.addScaledVector( _tempA, influence );
  39580. _morphB.addScaledVector( _tempB, influence );
  39581. _morphC.addScaledVector( _tempC, influence );
  39582. } else {
  39583. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  39584. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  39585. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  39586. }
  39587. }
  39588. _vA.add( _morphA );
  39589. _vB.add( _morphB );
  39590. _vC.add( _morphC );
  39591. }
  39592. if ( object.isSkinnedMesh ) {
  39593. object.boneTransform( a, _vA );
  39594. object.boneTransform( b, _vB );
  39595. object.boneTransform( c, _vC );
  39596. }
  39597. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  39598. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  39599. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  39600. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  39601. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  39602. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  39603. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  39604. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  39605. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  39606. }
  39607. const geometry = object.geometry;
  39608. const material = object.material;
  39609. let a, b, c;
  39610. const index = geometry.index;
  39611. const positionAttribute = geometry.attributes.position;
  39612. const morphPosition = geometry.morphAttributes.position;
  39613. const morphTargetsRelative = geometry.morphTargetsRelative;
  39614. const normalAttribute = geometry.attributes.normal;
  39615. const morphNormal = geometry.morphAttributes.position;
  39616. const groups = geometry.groups;
  39617. const drawRange = geometry.drawRange;
  39618. let i, j, il, jl;
  39619. let group, groupMaterial;
  39620. let start, end;
  39621. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  39622. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  39623. if ( index !== null ) {
  39624. // indexed buffer geometry
  39625. if ( Array.isArray( material ) ) {
  39626. for ( i = 0, il = groups.length; i < il; i ++ ) {
  39627. group = groups[ i ];
  39628. groupMaterial = material[ group.materialIndex ];
  39629. start = Math.max( group.start, drawRange.start );
  39630. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  39631. for ( j = start, jl = end; j < jl; j += 3 ) {
  39632. a = index.getX( j );
  39633. b = index.getX( j + 1 );
  39634. c = index.getX( j + 2 );
  39635. _calculateMorphedAttributeData( object, groupMaterial, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  39636. _calculateMorphedAttributeData( object, groupMaterial, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  39637. }
  39638. }
  39639. } else {
  39640. start = Math.max( 0, drawRange.start );
  39641. end = Math.min( index.count, drawRange.start + drawRange.count );
  39642. for ( i = start, il = end; i < il; i += 3 ) {
  39643. a = index.getX( i );
  39644. b = index.getX( i + 1 );
  39645. c = index.getX( i + 2 );
  39646. _calculateMorphedAttributeData( object, material, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  39647. _calculateMorphedAttributeData( object, material, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  39648. }
  39649. }
  39650. } else if ( positionAttribute !== undefined ) {
  39651. // non-indexed buffer geometry
  39652. if ( Array.isArray( material ) ) {
  39653. for ( i = 0, il = groups.length; i < il; i ++ ) {
  39654. group = groups[ i ];
  39655. groupMaterial = material[ group.materialIndex ];
  39656. start = Math.max( group.start, drawRange.start );
  39657. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  39658. for ( j = start, jl = end; j < jl; j += 3 ) {
  39659. a = j;
  39660. b = j + 1;
  39661. c = j + 2;
  39662. _calculateMorphedAttributeData( object, groupMaterial, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  39663. _calculateMorphedAttributeData( object, groupMaterial, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  39664. }
  39665. }
  39666. } else {
  39667. start = Math.max( 0, drawRange.start );
  39668. end = Math.min( positionAttribute.count, drawRange.start + drawRange.count );
  39669. for ( i = start, il = end; i < il; i += 3 ) {
  39670. a = i;
  39671. b = i + 1;
  39672. c = i + 2;
  39673. _calculateMorphedAttributeData( object, material, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  39674. _calculateMorphedAttributeData( object, material, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  39675. }
  39676. }
  39677. }
  39678. const morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  39679. const morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  39680. return {
  39681. positionAttribute: positionAttribute,
  39682. normalAttribute: normalAttribute,
  39683. morphedPositionAttribute: morphedPositionAttribute,
  39684. morphedNormalAttribute: morphedNormalAttribute
  39685. };
  39686. }
  39687. THREE.BufferGeometryUtils = {};
  39688. THREE.BufferGeometryUtils.computeMorphedAttributes = computeMorphedAttributes;
  39689. THREE.BufferGeometryUtils.computeTangents = computeTangents;
  39690. THREE.BufferGeometryUtils.estimateBytesUsed = estimateBytesUsed;
  39691. THREE.BufferGeometryUtils.interleaveAttributes = interleaveAttributes;
  39692. THREE.BufferGeometryUtils.mergeBufferAttributes = mergeBufferAttributes;
  39693. THREE.BufferGeometryUtils.mergeBufferGeometries = mergeBufferGeometries;
  39694. THREE.BufferGeometryUtils.mergeVertices = mergeVertices;
  39695. THREE.BufferGeometryUtils.toTrianglesDrawMode = toTrianglesDrawMode;
  39696. } )();
  39697. },{}],64:[function(require,module,exports){
  39698. var createLayout = require('layout-bmfont-text')
  39699. var inherits = require('inherits')
  39700. var createIndices = require('quad-indices')
  39701. var buffer = require('three-buffer-vertex-data')
  39702. var assign = require('object-assign')
  39703. var vertices = require('./lib/vertices')
  39704. var utils = require('./lib/utils')
  39705. module.exports = function createTextGeometry (opt) {
  39706. return new TextGeometry(opt)
  39707. }
  39708. class TextGeometry extends THREE.BufferGeometry {
  39709. constructor (opt) {
  39710. super()
  39711. if (typeof opt === 'string') {
  39712. opt = { text: opt }
  39713. }
  39714. // use these as default values for any subsequent
  39715. // calls to update()
  39716. this._opt = assign({}, opt)
  39717. // also do an initial setup...
  39718. if (opt) this.update(opt)
  39719. }
  39720. update(opt) {
  39721. if (typeof opt === 'string') {
  39722. opt = { text: opt }
  39723. }
  39724. // use constructor defaults
  39725. opt = assign({}, this._opt, opt)
  39726. if (!opt.font) {
  39727. throw new TypeError('must specify a { font } in options')
  39728. }
  39729. this.layout = createLayout(opt)
  39730. // get vec2 texcoords
  39731. var flipY = opt.flipY !== false
  39732. // the desired BMFont data
  39733. var font = opt.font
  39734. // determine texture size from font file
  39735. var texWidth = font.common.scaleW
  39736. var texHeight = font.common.scaleH
  39737. // get visible glyphs
  39738. var glyphs = this.layout.glyphs.filter(function (glyph) {
  39739. var bitmap = glyph.data
  39740. return bitmap.width * bitmap.height > 0
  39741. })
  39742. // provide visible glyphs for convenience
  39743. this.visibleGlyphs = glyphs
  39744. // get common vertex data
  39745. var positions = vertices.positions(glyphs)
  39746. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  39747. var indices = createIndices({
  39748. clockwise: true,
  39749. type: 'uint16',
  39750. count: glyphs.length
  39751. })
  39752. // update vertex data
  39753. buffer.index(this, indices, 1, 'uint16')
  39754. buffer.attr(this, 'position', positions, 2)
  39755. buffer.attr(this, 'uv', uvs, 2)
  39756. // update multipage data
  39757. if (!opt.multipage && 'page' in this.attributes) {
  39758. // disable multipage rendering
  39759. this.removeAttribute('page')
  39760. } else if (opt.multipage) {
  39761. var pages = vertices.pages(glyphs)
  39762. // enable multipage rendering
  39763. buffer.attr(this, 'page', pages, 1)
  39764. }
  39765. }
  39766. computeBoundingSphere() {
  39767. if (this.boundingSphere === null) {
  39768. this.boundingSphere = new THREE.Sphere()
  39769. }
  39770. var positions = this.attributes.position.array
  39771. var itemSize = this.attributes.position.itemSize
  39772. if (!positions || !itemSize || positions.length < 2) {
  39773. this.boundingSphere.radius = 0
  39774. this.boundingSphere.center.set(0, 0, 0)
  39775. return
  39776. }
  39777. utils.computeSphere(positions, this.boundingSphere)
  39778. if (isNaN(this.boundingSphere.radius)) {
  39779. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  39780. 'Computed radius is NaN. The ' +
  39781. '"position" attribute is likely to have NaN values.')
  39782. }
  39783. }
  39784. computeBoundingBox() {
  39785. if (this.boundingBox === null) {
  39786. this.boundingBox = new THREE.Box3()
  39787. }
  39788. var bbox = this.boundingBox
  39789. var positions = this.attributes.position.array
  39790. var itemSize = this.attributes.position.itemSize
  39791. if (!positions || !itemSize || positions.length < 2) {
  39792. bbox.makeEmpty()
  39793. return
  39794. }
  39795. utils.computeBox(positions, bbox)
  39796. }
  39797. }
  39798. },{"./lib/utils":65,"./lib/vertices":66,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":67}],65:[function(require,module,exports){
  39799. var itemSize = 2
  39800. var box = { min: [0, 0], max: [0, 0] }
  39801. function bounds (positions) {
  39802. var count = positions.length / itemSize
  39803. box.min[0] = positions[0]
  39804. box.min[1] = positions[1]
  39805. box.max[0] = positions[0]
  39806. box.max[1] = positions[1]
  39807. for (var i = 0; i < count; i++) {
  39808. var x = positions[i * itemSize + 0]
  39809. var y = positions[i * itemSize + 1]
  39810. box.min[0] = Math.min(x, box.min[0])
  39811. box.min[1] = Math.min(y, box.min[1])
  39812. box.max[0] = Math.max(x, box.max[0])
  39813. box.max[1] = Math.max(y, box.max[1])
  39814. }
  39815. }
  39816. module.exports.computeBox = function (positions, output) {
  39817. bounds(positions)
  39818. output.min.set(box.min[0], box.min[1], 0)
  39819. output.max.set(box.max[0], box.max[1], 0)
  39820. }
  39821. module.exports.computeSphere = function (positions, output) {
  39822. bounds(positions)
  39823. var minX = box.min[0]
  39824. var minY = box.min[1]
  39825. var maxX = box.max[0]
  39826. var maxY = box.max[1]
  39827. var width = maxX - minX
  39828. var height = maxY - minY
  39829. var length = Math.sqrt(width * width + height * height)
  39830. output.center.set(minX + width / 2, minY + height / 2, 0)
  39831. output.radius = length / 2
  39832. }
  39833. },{}],66:[function(require,module,exports){
  39834. module.exports.pages = function pages (glyphs) {
  39835. var pages = new Float32Array(glyphs.length * 4 * 1)
  39836. var i = 0
  39837. glyphs.forEach(function (glyph) {
  39838. var id = glyph.data.page || 0
  39839. pages[i++] = id
  39840. pages[i++] = id
  39841. pages[i++] = id
  39842. pages[i++] = id
  39843. })
  39844. return pages
  39845. }
  39846. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  39847. var uvs = new Float32Array(glyphs.length * 4 * 2)
  39848. var i = 0
  39849. glyphs.forEach(function (glyph) {
  39850. var bitmap = glyph.data
  39851. var bw = (bitmap.x + bitmap.width)
  39852. var bh = (bitmap.y + bitmap.height)
  39853. // top left position
  39854. var u0 = bitmap.x / texWidth
  39855. var v1 = bitmap.y / texHeight
  39856. var u1 = bw / texWidth
  39857. var v0 = bh / texHeight
  39858. if (flipY) {
  39859. v1 = (texHeight - bitmap.y) / texHeight
  39860. v0 = (texHeight - bh) / texHeight
  39861. }
  39862. // BL
  39863. uvs[i++] = u0
  39864. uvs[i++] = v1
  39865. // TL
  39866. uvs[i++] = u0
  39867. uvs[i++] = v0
  39868. // TR
  39869. uvs[i++] = u1
  39870. uvs[i++] = v0
  39871. // BR
  39872. uvs[i++] = u1
  39873. uvs[i++] = v1
  39874. })
  39875. return uvs
  39876. }
  39877. module.exports.positions = function positions (glyphs) {
  39878. var positions = new Float32Array(glyphs.length * 4 * 2)
  39879. var i = 0
  39880. glyphs.forEach(function (glyph) {
  39881. var bitmap = glyph.data
  39882. // bottom left position
  39883. var x = glyph.position[0] + bitmap.xoffset
  39884. var y = glyph.position[1] + bitmap.yoffset
  39885. // quad size
  39886. var w = bitmap.width
  39887. var h = bitmap.height
  39888. // BL
  39889. positions[i++] = x
  39890. positions[i++] = y
  39891. // TL
  39892. positions[i++] = x
  39893. positions[i++] = y + h
  39894. // TR
  39895. positions[i++] = x + w
  39896. positions[i++] = y + h
  39897. // BR
  39898. positions[i++] = x + w
  39899. positions[i++] = y
  39900. })
  39901. return positions
  39902. }
  39903. },{}],67:[function(require,module,exports){
  39904. var flatten = require('flatten-vertex-data')
  39905. var warned = false;
  39906. module.exports.attr = setAttribute
  39907. module.exports.index = setIndex
  39908. function setIndex (geometry, data, itemSize, dtype) {
  39909. if (typeof itemSize !== 'number') itemSize = 1
  39910. if (typeof dtype !== 'string') dtype = 'uint16'
  39911. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  39912. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  39913. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  39914. if (newAttrib) {
  39915. if (isR69) geometry.addAttribute('index', newAttrib)
  39916. else geometry.index = newAttrib
  39917. }
  39918. }
  39919. function setAttribute (geometry, key, data, itemSize, dtype) {
  39920. if (typeof itemSize !== 'number') itemSize = 3
  39921. if (typeof dtype !== 'string') dtype = 'float32'
  39922. if (Array.isArray(data) &&
  39923. Array.isArray(data[0]) &&
  39924. data[0].length !== itemSize) {
  39925. throw new Error('Nested vertex array has unexpected size; expected ' +
  39926. itemSize + ' but found ' + data[0].length)
  39927. }
  39928. var attrib = geometry.getAttribute(key)
  39929. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  39930. geometry.setAttribute(key, newAttrib)
  39931. }
  39932. function updateAttribute (attrib, data, itemSize, dtype) {
  39933. data = data || []
  39934. // create a new array with desired type
  39935. data = flatten(data, dtype)
  39936. attrib = new THREE.BufferAttribute(data, itemSize);
  39937. attrib.itemSize = itemSize;
  39938. attrib.needsUpdate = true;
  39939. return attrib
  39940. }
  39941. // Test whether the attribute needs to be re-created,
  39942. // returns false if we can re-use it as-is.
  39943. function rebuildAttribute (attrib, data, itemSize) {
  39944. if (attrib.itemSize !== itemSize) return true
  39945. if (!attrib.array) return true
  39946. var attribLength = attrib.array.length
  39947. if (Array.isArray(data) && Array.isArray(data[0])) {
  39948. // [ [ x, y, z ] ]
  39949. return attribLength !== data.length * itemSize
  39950. } else {
  39951. // [ x, y, z ]
  39952. return attribLength !== data.length
  39953. }
  39954. return false
  39955. }
  39956. },{"flatten-vertex-data":23}],68:[function(require,module,exports){
  39957. (function (setImmediate,clearImmediate){
  39958. var nextTick = require('process/browser.js').nextTick;
  39959. var apply = Function.prototype.apply;
  39960. var slice = Array.prototype.slice;
  39961. var immediateIds = {};
  39962. var nextImmediateId = 0;
  39963. // DOM APIs, for completeness
  39964. exports.setTimeout = function() {
  39965. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  39966. };
  39967. exports.setInterval = function() {
  39968. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  39969. };
  39970. exports.clearTimeout =
  39971. exports.clearInterval = function(timeout) { timeout.close(); };
  39972. function Timeout(id, clearFn) {
  39973. this._id = id;
  39974. this._clearFn = clearFn;
  39975. }
  39976. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  39977. Timeout.prototype.close = function() {
  39978. this._clearFn.call(window, this._id);
  39979. };
  39980. // Does not start the time, just sets up the members needed.
  39981. exports.enroll = function(item, msecs) {
  39982. clearTimeout(item._idleTimeoutId);
  39983. item._idleTimeout = msecs;
  39984. };
  39985. exports.unenroll = function(item) {
  39986. clearTimeout(item._idleTimeoutId);
  39987. item._idleTimeout = -1;
  39988. };
  39989. exports._unrefActive = exports.active = function(item) {
  39990. clearTimeout(item._idleTimeoutId);
  39991. var msecs = item._idleTimeout;
  39992. if (msecs >= 0) {
  39993. item._idleTimeoutId = setTimeout(function onTimeout() {
  39994. if (item._onTimeout)
  39995. item._onTimeout();
  39996. }, msecs);
  39997. }
  39998. };
  39999. // That's not how node.js implements it but the exposed api is the same.
  40000. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  40001. var id = nextImmediateId++;
  40002. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  40003. immediateIds[id] = true;
  40004. nextTick(function onNextTick() {
  40005. if (immediateIds[id]) {
  40006. // fn.call() is faster so we optimize for the common use-case
  40007. // @see http://jsperf.com/call-apply-segu
  40008. if (args) {
  40009. fn.apply(null, args);
  40010. } else {
  40011. fn.call(null);
  40012. }
  40013. // Prevent ids from leaking
  40014. exports.clearImmediate(id);
  40015. }
  40016. });
  40017. return id;
  40018. };
  40019. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  40020. delete immediateIds[id];
  40021. };
  40022. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  40023. },{"process/browser.js":49,"timers":68}],69:[function(require,module,exports){
  40024. (function (global){
  40025. /**
  40026. * @license
  40027. * webvr-polyfill
  40028. * Copyright (c) 2015-2017 Google
  40029. * Licensed under the Apache License, Version 2.0 (the "License");
  40030. * you may not use this file except in compliance with the License.
  40031. * You may obtain a copy of the License at
  40032. *
  40033. * http://www.apache.org/licenses/LICENSE-2.0
  40034. *
  40035. * Unless required by applicable law or agreed to in writing, software
  40036. * distributed under the License is distributed on an "AS IS" BASIS,
  40037. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40038. * See the License for the specific language governing permissions and
  40039. * limitations under the License.
  40040. */
  40041. /**
  40042. * @license
  40043. * cardboard-vr-display
  40044. * Copyright (c) 2015-2017 Google
  40045. * Licensed under the Apache License, Version 2.0 (the "License");
  40046. * you may not use this file except in compliance with the License.
  40047. * You may obtain a copy of the License at
  40048. *
  40049. * http://www.apache.org/licenses/LICENSE-2.0
  40050. *
  40051. * Unless required by applicable law or agreed to in writing, software
  40052. * distributed under the License is distributed on an "AS IS" BASIS,
  40053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40054. * See the License for the specific language governing permissions and
  40055. * limitations under the License.
  40056. */
  40057. /**
  40058. * @license
  40059. * webvr-polyfill-dpdb
  40060. * Copyright (c) 2017 Google
  40061. * Licensed under the Apache License, Version 2.0 (the "License");
  40062. * you may not use this file except in compliance with the License.
  40063. * You may obtain a copy of the License at
  40064. *
  40065. * http://www.apache.org/licenses/LICENSE-2.0
  40066. *
  40067. * Unless required by applicable law or agreed to in writing, software
  40068. * distributed under the License is distributed on an "AS IS" BASIS,
  40069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40070. * See the License for the specific language governing permissions and
  40071. * limitations under the License.
  40072. */
  40073. /**
  40074. * @license
  40075. * wglu-preserve-state
  40076. * Copyright (c) 2016, Brandon Jones.
  40077. *
  40078. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40079. * of this software and associated documentation files (the "Software"), to deal
  40080. * in the Software without restriction, including without limitation the rights
  40081. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40082. * copies of the Software, and to permit persons to whom the Software is
  40083. * furnished to do so, subject to the following conditions:
  40084. *
  40085. * The above copyright notice and this permission notice shall be included in
  40086. * all copies or substantial portions of the Software.
  40087. *
  40088. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40089. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40090. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40091. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40092. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40093. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40094. * THE SOFTWARE.
  40095. */
  40096. /**
  40097. * @license
  40098. * nosleep.js
  40099. * Copyright (c) 2017, Rich Tibbett
  40100. *
  40101. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40102. * of this software and associated documentation files (the "Software"), to deal
  40103. * in the Software without restriction, including without limitation the rights
  40104. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40105. * copies of the Software, and to permit persons to whom the Software is
  40106. * furnished to do so, subject to the following conditions:
  40107. *
  40108. * The above copyright notice and this permission notice shall be included in
  40109. * all copies or substantial portions of the Software.
  40110. *
  40111. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40112. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40113. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40114. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40115. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40116. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40117. * THE SOFTWARE.
  40118. */
  40119. (function (global, factory) {
  40120. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  40121. typeof define === 'function' && define.amd ? define(factory) :
  40122. (global.WebVRPolyfill = factory());
  40123. }(this, (function () { 'use strict';
  40124. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  40125. function unwrapExports (x) {
  40126. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  40127. }
  40128. function createCommonjsModule(fn, module) {
  40129. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40130. }
  40131. var isMobile = function isMobile() {
  40132. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  40133. );
  40134. };
  40135. var copyArray = function copyArray(source, dest) {
  40136. for (var i = 0, n = source.length; i < n; i++) {
  40137. dest[i] = source[i];
  40138. }
  40139. };
  40140. var extend = function extend(dest, src) {
  40141. for (var key in src) {
  40142. if (src.hasOwnProperty(key)) {
  40143. dest[key] = src[key];
  40144. }
  40145. }
  40146. return dest;
  40147. };
  40148. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  40149. /**
  40150. * @license
  40151. * cardboard-vr-display
  40152. * Copyright (c) 2015-2017 Google
  40153. * Licensed under the Apache License, Version 2.0 (the "License");
  40154. * you may not use this file except in compliance with the License.
  40155. * You may obtain a copy of the License at
  40156. *
  40157. * http://www.apache.org/licenses/LICENSE-2.0
  40158. *
  40159. * Unless required by applicable law or agreed to in writing, software
  40160. * distributed under the License is distributed on an "AS IS" BASIS,
  40161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40162. * See the License for the specific language governing permissions and
  40163. * limitations under the License.
  40164. */
  40165. /**
  40166. * @license
  40167. * gl-preserve-state
  40168. * Copyright (c) 2016, Brandon Jones.
  40169. *
  40170. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40171. * of this software and associated documentation files (the "Software"), to deal
  40172. * in the Software without restriction, including without limitation the rights
  40173. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40174. * copies of the Software, and to permit persons to whom the Software is
  40175. * furnished to do so, subject to the following conditions:
  40176. *
  40177. * The above copyright notice and this permission notice shall be included in
  40178. * all copies or substantial portions of the Software.
  40179. *
  40180. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40181. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40182. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40183. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40184. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40185. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40186. * THE SOFTWARE.
  40187. */
  40188. /**
  40189. * @license
  40190. * webvr-polyfill-dpdb
  40191. * Copyright (c) 2015-2017 Google
  40192. * Licensed under the Apache License, Version 2.0 (the "License");
  40193. * you may not use this file except in compliance with the License.
  40194. * You may obtain a copy of the License at
  40195. *
  40196. * http://www.apache.org/licenses/LICENSE-2.0
  40197. *
  40198. * Unless required by applicable law or agreed to in writing, software
  40199. * distributed under the License is distributed on an "AS IS" BASIS,
  40200. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40201. * See the License for the specific language governing permissions and
  40202. * limitations under the License.
  40203. */
  40204. /**
  40205. * @license
  40206. * nosleep.js
  40207. * Copyright (c) 2017, Rich Tibbett
  40208. *
  40209. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40210. * of this software and associated documentation files (the "Software"), to deal
  40211. * in the Software without restriction, including without limitation the rights
  40212. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40213. * copies of the Software, and to permit persons to whom the Software is
  40214. * furnished to do so, subject to the following conditions:
  40215. *
  40216. * The above copyright notice and this permission notice shall be included in
  40217. * all copies or substantial portions of the Software.
  40218. *
  40219. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40220. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40221. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40222. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40223. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40224. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40225. * THE SOFTWARE.
  40226. */
  40227. (function (global, factory) {
  40228. module.exports = factory();
  40229. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  40230. if (!(instance instanceof Constructor)) {
  40231. throw new TypeError("Cannot call a class as a function");
  40232. }
  40233. };
  40234. var createClass = function () {
  40235. function defineProperties(target, props) {
  40236. for (var i = 0; i < props.length; i++) {
  40237. var descriptor = props[i];
  40238. descriptor.enumerable = descriptor.enumerable || false;
  40239. descriptor.configurable = true;
  40240. if ("value" in descriptor) descriptor.writable = true;
  40241. Object.defineProperty(target, descriptor.key, descriptor);
  40242. }
  40243. }
  40244. return function (Constructor, protoProps, staticProps) {
  40245. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  40246. if (staticProps) defineProperties(Constructor, staticProps);
  40247. return Constructor;
  40248. };
  40249. }();
  40250. var slicedToArray = function () {
  40251. function sliceIterator(arr, i) {
  40252. var _arr = [];
  40253. var _n = true;
  40254. var _d = false;
  40255. var _e = undefined;
  40256. try {
  40257. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  40258. _arr.push(_s.value);
  40259. if (i && _arr.length === i) break;
  40260. }
  40261. } catch (err) {
  40262. _d = true;
  40263. _e = err;
  40264. } finally {
  40265. try {
  40266. if (!_n && _i["return"]) _i["return"]();
  40267. } finally {
  40268. if (_d) throw _e;
  40269. }
  40270. }
  40271. return _arr;
  40272. }
  40273. return function (arr, i) {
  40274. if (Array.isArray(arr)) {
  40275. return arr;
  40276. } else if (Symbol.iterator in Object(arr)) {
  40277. return sliceIterator(arr, i);
  40278. } else {
  40279. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  40280. }
  40281. };
  40282. }();
  40283. var MIN_TIMESTEP = 0.001;
  40284. var MAX_TIMESTEP = 1;
  40285. var dataUri = function dataUri(mimeType, svg) {
  40286. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  40287. };
  40288. var lerp = function lerp(a, b, t) {
  40289. return a + (b - a) * t;
  40290. };
  40291. var isIOS = function () {
  40292. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  40293. return function () {
  40294. return isIOS;
  40295. };
  40296. }();
  40297. var isWebViewAndroid = function () {
  40298. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  40299. return function () {
  40300. return isWebViewAndroid;
  40301. };
  40302. }();
  40303. var isSafari = function () {
  40304. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  40305. return function () {
  40306. return isSafari;
  40307. };
  40308. }();
  40309. var isFirefoxAndroid = function () {
  40310. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  40311. return function () {
  40312. return isFirefoxAndroid;
  40313. };
  40314. }();
  40315. var getChromeVersion = function () {
  40316. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  40317. var value = match ? parseInt(match[1], 10) : null;
  40318. return function () {
  40319. return value;
  40320. };
  40321. }();
  40322. var isSafariWithoutDeviceMotion = function () {
  40323. var value = false;
  40324. value = isIOS() && isSafari() && navigator.userAgent.indexOf('13_4') !== -1;
  40325. return function () {
  40326. return value;
  40327. };
  40328. }();
  40329. var isChromeWithoutDeviceMotion = function () {
  40330. var value = false;
  40331. if (getChromeVersion() === 65) {
  40332. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  40333. if (match) {
  40334. var _match$1$split = match[1].split('.'),
  40335. _match$1$split2 = slicedToArray(_match$1$split, 4),
  40336. major = _match$1$split2[0],
  40337. minor = _match$1$split2[1],
  40338. branch = _match$1$split2[2],
  40339. build = _match$1$split2[3];
  40340. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  40341. }
  40342. }
  40343. return function () {
  40344. return value;
  40345. };
  40346. }();
  40347. var isR7 = function () {
  40348. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  40349. return function () {
  40350. return isR7;
  40351. };
  40352. }();
  40353. var isLandscapeMode = function isLandscapeMode() {
  40354. var rtn = window.orientation == 90 || window.orientation == -90;
  40355. return isR7() ? !rtn : rtn;
  40356. };
  40357. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  40358. if (isNaN(timestampDeltaS)) {
  40359. return false;
  40360. }
  40361. if (timestampDeltaS <= MIN_TIMESTEP) {
  40362. return false;
  40363. }
  40364. if (timestampDeltaS > MAX_TIMESTEP) {
  40365. return false;
  40366. }
  40367. return true;
  40368. };
  40369. var getScreenWidth = function getScreenWidth() {
  40370. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40371. };
  40372. var getScreenHeight = function getScreenHeight() {
  40373. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40374. };
  40375. var requestFullscreen = function requestFullscreen(element) {
  40376. if (isWebViewAndroid()) {
  40377. return false;
  40378. }
  40379. if (element.requestFullscreen) {
  40380. element.requestFullscreen();
  40381. } else if (element.webkitRequestFullscreen) {
  40382. element.webkitRequestFullscreen();
  40383. } else if (element.mozRequestFullScreen) {
  40384. element.mozRequestFullScreen();
  40385. } else if (element.msRequestFullscreen) {
  40386. element.msRequestFullscreen();
  40387. } else {
  40388. return false;
  40389. }
  40390. return true;
  40391. };
  40392. var exitFullscreen = function exitFullscreen() {
  40393. if (document.exitFullscreen) {
  40394. document.exitFullscreen();
  40395. } else if (document.webkitExitFullscreen) {
  40396. document.webkitExitFullscreen();
  40397. } else if (document.mozCancelFullScreen) {
  40398. document.mozCancelFullScreen();
  40399. } else if (document.msExitFullscreen) {
  40400. document.msExitFullscreen();
  40401. } else {
  40402. return false;
  40403. }
  40404. return true;
  40405. };
  40406. var getFullscreenElement = function getFullscreenElement() {
  40407. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  40408. };
  40409. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  40410. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  40411. gl.shaderSource(vertexShader, vertexSource);
  40412. gl.compileShader(vertexShader);
  40413. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  40414. gl.shaderSource(fragmentShader, fragmentSource);
  40415. gl.compileShader(fragmentShader);
  40416. var program = gl.createProgram();
  40417. gl.attachShader(program, vertexShader);
  40418. gl.attachShader(program, fragmentShader);
  40419. for (var attribName in attribLocationMap) {
  40420. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  40421. }gl.linkProgram(program);
  40422. gl.deleteShader(vertexShader);
  40423. gl.deleteShader(fragmentShader);
  40424. return program;
  40425. };
  40426. var getProgramUniforms = function getProgramUniforms(gl, program) {
  40427. var uniforms = {};
  40428. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  40429. var uniformName = '';
  40430. for (var i = 0; i < uniformCount; i++) {
  40431. var uniformInfo = gl.getActiveUniform(program, i);
  40432. uniformName = uniformInfo.name.replace('[0]', '');
  40433. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  40434. }
  40435. return uniforms;
  40436. };
  40437. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  40438. var lr = 1 / (left - right),
  40439. bt = 1 / (bottom - top),
  40440. nf = 1 / (near - far);
  40441. out[0] = -2 * lr;
  40442. out[1] = 0;
  40443. out[2] = 0;
  40444. out[3] = 0;
  40445. out[4] = 0;
  40446. out[5] = -2 * bt;
  40447. out[6] = 0;
  40448. out[7] = 0;
  40449. out[8] = 0;
  40450. out[9] = 0;
  40451. out[10] = 2 * nf;
  40452. out[11] = 0;
  40453. out[12] = (left + right) * lr;
  40454. out[13] = (top + bottom) * bt;
  40455. out[14] = (far + near) * nf;
  40456. out[15] = 1;
  40457. return out;
  40458. };
  40459. var isMobile = function isMobile() {
  40460. var check = false;
  40461. (function (a) {
  40462. 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;
  40463. })(navigator.userAgent || navigator.vendor || window.opera);
  40464. return check;
  40465. };
  40466. var extend = function extend(dest, src) {
  40467. for (var key in src) {
  40468. if (src.hasOwnProperty(key)) {
  40469. dest[key] = src[key];
  40470. }
  40471. }
  40472. return dest;
  40473. };
  40474. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  40475. if (isIOS()) {
  40476. var width = canvas.style.width;
  40477. var height = canvas.style.height;
  40478. canvas.style.width = parseInt(width) + 1 + 'px';
  40479. canvas.style.height = parseInt(height) + 'px';
  40480. setTimeout(function () {
  40481. canvas.style.width = width;
  40482. canvas.style.height = height;
  40483. }, 100);
  40484. }
  40485. window.canvas = canvas;
  40486. };
  40487. var frameDataFromPose = function () {
  40488. var piOver180 = Math.PI / 180.0;
  40489. var rad45 = Math.PI * 0.25;
  40490. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  40491. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  40492. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  40493. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  40494. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  40495. xScale = 2.0 / (leftTan + rightTan),
  40496. yScale = 2.0 / (upTan + downTan);
  40497. out[0] = xScale;
  40498. out[1] = 0.0;
  40499. out[2] = 0.0;
  40500. out[3] = 0.0;
  40501. out[4] = 0.0;
  40502. out[5] = yScale;
  40503. out[6] = 0.0;
  40504. out[7] = 0.0;
  40505. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  40506. out[9] = (upTan - downTan) * yScale * 0.5;
  40507. out[10] = far / (near - far);
  40508. out[11] = -1.0;
  40509. out[12] = 0.0;
  40510. out[13] = 0.0;
  40511. out[14] = far * near / (near - far);
  40512. out[15] = 0.0;
  40513. return out;
  40514. }
  40515. function mat4_fromRotationTranslation(out, q, v) {
  40516. var x = q[0],
  40517. y = q[1],
  40518. z = q[2],
  40519. w = q[3],
  40520. x2 = x + x,
  40521. y2 = y + y,
  40522. z2 = z + z,
  40523. xx = x * x2,
  40524. xy = x * y2,
  40525. xz = x * z2,
  40526. yy = y * y2,
  40527. yz = y * z2,
  40528. zz = z * z2,
  40529. wx = w * x2,
  40530. wy = w * y2,
  40531. wz = w * z2;
  40532. out[0] = 1 - (yy + zz);
  40533. out[1] = xy + wz;
  40534. out[2] = xz - wy;
  40535. out[3] = 0;
  40536. out[4] = xy - wz;
  40537. out[5] = 1 - (xx + zz);
  40538. out[6] = yz + wx;
  40539. out[7] = 0;
  40540. out[8] = xz + wy;
  40541. out[9] = yz - wx;
  40542. out[10] = 1 - (xx + yy);
  40543. out[11] = 0;
  40544. out[12] = v[0];
  40545. out[13] = v[1];
  40546. out[14] = v[2];
  40547. out[15] = 1;
  40548. return out;
  40549. }
  40550. function mat4_translate(out, a, v) {
  40551. var x = v[0],
  40552. y = v[1],
  40553. z = v[2],
  40554. a00,
  40555. a01,
  40556. a02,
  40557. a03,
  40558. a10,
  40559. a11,
  40560. a12,
  40561. a13,
  40562. a20,
  40563. a21,
  40564. a22,
  40565. a23;
  40566. if (a === out) {
  40567. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  40568. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  40569. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  40570. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  40571. } else {
  40572. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  40573. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  40574. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  40575. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  40576. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  40577. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  40578. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  40579. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  40580. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  40581. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  40582. }
  40583. return out;
  40584. }
  40585. function mat4_invert(out, a) {
  40586. var a00 = a[0],
  40587. a01 = a[1],
  40588. a02 = a[2],
  40589. a03 = a[3],
  40590. a10 = a[4],
  40591. a11 = a[5],
  40592. a12 = a[6],
  40593. a13 = a[7],
  40594. a20 = a[8],
  40595. a21 = a[9],
  40596. a22 = a[10],
  40597. a23 = a[11],
  40598. a30 = a[12],
  40599. a31 = a[13],
  40600. a32 = a[14],
  40601. a33 = a[15],
  40602. b00 = a00 * a11 - a01 * a10,
  40603. b01 = a00 * a12 - a02 * a10,
  40604. b02 = a00 * a13 - a03 * a10,
  40605. b03 = a01 * a12 - a02 * a11,
  40606. b04 = a01 * a13 - a03 * a11,
  40607. b05 = a02 * a13 - a03 * a12,
  40608. b06 = a20 * a31 - a21 * a30,
  40609. b07 = a20 * a32 - a22 * a30,
  40610. b08 = a20 * a33 - a23 * a30,
  40611. b09 = a21 * a32 - a22 * a31,
  40612. b10 = a21 * a33 - a23 * a31,
  40613. b11 = a22 * a33 - a23 * a32,
  40614. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  40615. if (!det) {
  40616. return null;
  40617. }
  40618. det = 1.0 / det;
  40619. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  40620. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  40621. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  40622. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  40623. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  40624. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  40625. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  40626. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  40627. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  40628. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  40629. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  40630. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  40631. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  40632. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  40633. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  40634. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  40635. return out;
  40636. }
  40637. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  40638. var defaultPosition = new Float32Array([0, 0, 0]);
  40639. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  40640. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  40641. var orientation = pose.orientation || defaultOrientation;
  40642. var position = pose.position || defaultPosition;
  40643. mat4_fromRotationTranslation(view, orientation, position);
  40644. if (offset) mat4_translate(view, view, offset);
  40645. mat4_invert(view, view);
  40646. }
  40647. return function (frameData, pose, vrDisplay) {
  40648. if (!frameData || !pose) return false;
  40649. frameData.pose = pose;
  40650. frameData.timestamp = pose.timestamp;
  40651. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  40652. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  40653. return true;
  40654. };
  40655. }();
  40656. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  40657. var isFramed = window.self !== window.top;
  40658. var refOrigin = getOriginFromUrl(document.referrer);
  40659. var thisOrigin = getOriginFromUrl(window.location.href);
  40660. return isFramed && refOrigin !== thisOrigin;
  40661. };
  40662. var getOriginFromUrl = function getOriginFromUrl(url) {
  40663. var domainIdx;
  40664. var protoSepIdx = url.indexOf("://");
  40665. if (protoSepIdx !== -1) {
  40666. domainIdx = protoSepIdx + 3;
  40667. } else {
  40668. domainIdx = 0;
  40669. }
  40670. var domainEndIdx = url.indexOf('/', domainIdx);
  40671. if (domainEndIdx === -1) {
  40672. domainEndIdx = url.length;
  40673. }
  40674. return url.substring(0, domainEndIdx);
  40675. };
  40676. var getQuaternionAngle = function getQuaternionAngle(quat) {
  40677. if (quat.w > 1) {
  40678. console.warn('getQuaternionAngle: w > 1');
  40679. return 0;
  40680. }
  40681. var angle = 2 * Math.acos(quat.w);
  40682. return angle;
  40683. };
  40684. var warnOnce = function () {
  40685. var observedWarnings = {};
  40686. return function (key, message) {
  40687. if (observedWarnings[key] === undefined) {
  40688. console.warn('webvr-polyfill: ' + message);
  40689. observedWarnings[key] = true;
  40690. }
  40691. };
  40692. }();
  40693. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  40694. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  40695. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  40696. };
  40697. function WGLUPreserveGLState(gl, bindings, callback) {
  40698. if (!bindings) {
  40699. callback(gl);
  40700. return;
  40701. }
  40702. var boundValues = [];
  40703. var activeTexture = null;
  40704. for (var i = 0; i < bindings.length; ++i) {
  40705. var binding = bindings[i];
  40706. switch (binding) {
  40707. case gl.TEXTURE_BINDING_2D:
  40708. case gl.TEXTURE_BINDING_CUBE_MAP:
  40709. var textureUnit = bindings[++i];
  40710. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  40711. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  40712. boundValues.push(null, null);
  40713. break;
  40714. }
  40715. if (!activeTexture) {
  40716. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40717. }
  40718. gl.activeTexture(textureUnit);
  40719. boundValues.push(gl.getParameter(binding), null);
  40720. break;
  40721. case gl.ACTIVE_TEXTURE:
  40722. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40723. boundValues.push(null);
  40724. break;
  40725. default:
  40726. boundValues.push(gl.getParameter(binding));
  40727. break;
  40728. }
  40729. }
  40730. callback(gl);
  40731. for (var i = 0; i < bindings.length; ++i) {
  40732. var binding = bindings[i];
  40733. var boundValue = boundValues[i];
  40734. switch (binding) {
  40735. case gl.ACTIVE_TEXTURE:
  40736. break;
  40737. case gl.ARRAY_BUFFER_BINDING:
  40738. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  40739. break;
  40740. case gl.COLOR_CLEAR_VALUE:
  40741. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40742. break;
  40743. case gl.COLOR_WRITEMASK:
  40744. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40745. break;
  40746. case gl.CURRENT_PROGRAM:
  40747. gl.useProgram(boundValue);
  40748. break;
  40749. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  40750. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  40751. break;
  40752. case gl.FRAMEBUFFER_BINDING:
  40753. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  40754. break;
  40755. case gl.RENDERBUFFER_BINDING:
  40756. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  40757. break;
  40758. case gl.TEXTURE_BINDING_2D:
  40759. var textureUnit = bindings[++i];
  40760. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40761. break;
  40762. gl.activeTexture(textureUnit);
  40763. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  40764. break;
  40765. case gl.TEXTURE_BINDING_CUBE_MAP:
  40766. var textureUnit = bindings[++i];
  40767. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40768. break;
  40769. gl.activeTexture(textureUnit);
  40770. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  40771. break;
  40772. case gl.VIEWPORT:
  40773. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40774. break;
  40775. case gl.BLEND:
  40776. case gl.CULL_FACE:
  40777. case gl.DEPTH_TEST:
  40778. case gl.SCISSOR_TEST:
  40779. case gl.STENCIL_TEST:
  40780. if (boundValue) {
  40781. gl.enable(binding);
  40782. } else {
  40783. gl.disable(binding);
  40784. }
  40785. break;
  40786. default:
  40787. console.log("No GL restore behavior for 0x" + binding.toString(16));
  40788. break;
  40789. }
  40790. if (activeTexture) {
  40791. gl.activeTexture(activeTexture);
  40792. }
  40793. }
  40794. }
  40795. var glPreserveState = WGLUPreserveGLState;
  40796. 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');
  40797. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  40798. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  40799. this.gl = gl;
  40800. this.cardboardUI = cardboardUI;
  40801. this.bufferScale = bufferScale;
  40802. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  40803. this.ctxAttribs = gl.getContextAttributes();
  40804. this.instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  40805. this.meshWidth = 20;
  40806. this.meshHeight = 20;
  40807. this.bufferWidth = gl.drawingBufferWidth;
  40808. this.bufferHeight = gl.drawingBufferHeight;
  40809. this.realBindFramebuffer = gl.bindFramebuffer;
  40810. this.realEnable = gl.enable;
  40811. this.realDisable = gl.disable;
  40812. this.realColorMask = gl.colorMask;
  40813. this.realClearColor = gl.clearColor;
  40814. this.realViewport = gl.viewport;
  40815. if (!isIOS()) {
  40816. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  40817. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  40818. }
  40819. this.isPatched = false;
  40820. this.lastBoundFramebuffer = null;
  40821. this.cullFace = false;
  40822. this.depthTest = false;
  40823. this.blend = false;
  40824. this.scissorTest = false;
  40825. this.stencilTest = false;
  40826. this.viewport = [0, 0, 0, 0];
  40827. this.colorMask = [true, true, true, true];
  40828. this.clearColor = [0, 0, 0, 0];
  40829. this.attribs = {
  40830. position: 0,
  40831. texCoord: 1
  40832. };
  40833. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  40834. this.uniforms = getProgramUniforms(gl, this.program);
  40835. this.viewportOffsetScale = new Float32Array(8);
  40836. this.setTextureBounds();
  40837. this.vertexBuffer = gl.createBuffer();
  40838. this.indexBuffer = gl.createBuffer();
  40839. this.indexCount = 0;
  40840. this.renderTarget = gl.createTexture();
  40841. this.framebuffer = gl.createFramebuffer();
  40842. this.depthStencilBuffer = null;
  40843. this.depthBuffer = null;
  40844. this.stencilBuffer = null;
  40845. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  40846. this.depthStencilBuffer = gl.createRenderbuffer();
  40847. } else if (this.ctxAttribs.depth) {
  40848. this.depthBuffer = gl.createRenderbuffer();
  40849. } else if (this.ctxAttribs.stencil) {
  40850. this.stencilBuffer = gl.createRenderbuffer();
  40851. }
  40852. this.patch();
  40853. this.onResize();
  40854. }
  40855. CardboardDistorter.prototype.destroy = function () {
  40856. var gl = this.gl;
  40857. this.unpatch();
  40858. gl.deleteProgram(this.program);
  40859. gl.deleteBuffer(this.vertexBuffer);
  40860. gl.deleteBuffer(this.indexBuffer);
  40861. gl.deleteTexture(this.renderTarget);
  40862. gl.deleteFramebuffer(this.framebuffer);
  40863. if (this.depthStencilBuffer) {
  40864. gl.deleteRenderbuffer(this.depthStencilBuffer);
  40865. }
  40866. if (this.depthBuffer) {
  40867. gl.deleteRenderbuffer(this.depthBuffer);
  40868. }
  40869. if (this.stencilBuffer) {
  40870. gl.deleteRenderbuffer(this.stencilBuffer);
  40871. }
  40872. if (this.cardboardUI) {
  40873. this.cardboardUI.destroy();
  40874. }
  40875. };
  40876. CardboardDistorter.prototype.onResize = function () {
  40877. var gl = this.gl;
  40878. var self = this;
  40879. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  40880. glPreserveState(gl, glState, function (gl) {
  40881. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  40882. if (self.scissorTest) {
  40883. self.realDisable.call(gl, gl.SCISSOR_TEST);
  40884. }
  40885. self.realColorMask.call(gl, true, true, true, true);
  40886. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  40887. self.realClearColor.call(gl, 0, 0, 0, 1);
  40888. gl.clear(gl.COLOR_BUFFER_BIT);
  40889. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  40890. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  40891. 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);
  40892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  40893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  40894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  40895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  40896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  40897. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  40898. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  40899. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  40900. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  40901. } else if (self.ctxAttribs.depth) {
  40902. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  40903. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  40904. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  40905. } else if (self.ctxAttribs.stencil) {
  40906. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  40907. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  40908. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  40909. }
  40910. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  40911. console.error('Framebuffer incomplete!');
  40912. }
  40913. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  40914. if (self.scissorTest) {
  40915. self.realEnable.call(gl, gl.SCISSOR_TEST);
  40916. }
  40917. self.realColorMask.apply(gl, self.colorMask);
  40918. self.realViewport.apply(gl, self.viewport);
  40919. self.realClearColor.apply(gl, self.clearColor);
  40920. });
  40921. if (this.cardboardUI) {
  40922. this.cardboardUI.onResize();
  40923. }
  40924. };
  40925. CardboardDistorter.prototype.patch = function () {
  40926. if (this.isPatched) {
  40927. return;
  40928. }
  40929. var self = this;
  40930. var canvas = this.gl.canvas;
  40931. var gl = this.gl;
  40932. if (!isIOS()) {
  40933. canvas.width = getScreenWidth() * this.bufferScale;
  40934. canvas.height = getScreenHeight() * this.bufferScale;
  40935. Object.defineProperty(canvas, 'width', {
  40936. configurable: true,
  40937. enumerable: true,
  40938. get: function get() {
  40939. return self.bufferWidth;
  40940. },
  40941. set: function set(value) {
  40942. self.bufferWidth = value;
  40943. self.realCanvasWidth.set.call(canvas, value);
  40944. self.onResize();
  40945. }
  40946. });
  40947. Object.defineProperty(canvas, 'height', {
  40948. configurable: true,
  40949. enumerable: true,
  40950. get: function get() {
  40951. return self.bufferHeight;
  40952. },
  40953. set: function set(value) {
  40954. self.bufferHeight = value;
  40955. self.realCanvasHeight.set.call(canvas, value);
  40956. self.onResize();
  40957. }
  40958. });
  40959. }
  40960. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  40961. if (this.lastBoundFramebuffer == null) {
  40962. this.lastBoundFramebuffer = this.framebuffer;
  40963. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  40964. }
  40965. this.gl.bindFramebuffer = function (target, framebuffer) {
  40966. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  40967. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  40968. };
  40969. this.cullFace = gl.getParameter(gl.CULL_FACE);
  40970. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  40971. this.blend = gl.getParameter(gl.BLEND);
  40972. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  40973. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  40974. gl.enable = function (pname) {
  40975. switch (pname) {
  40976. case gl.CULL_FACE:
  40977. self.cullFace = true;break;
  40978. case gl.DEPTH_TEST:
  40979. self.depthTest = true;break;
  40980. case gl.BLEND:
  40981. self.blend = true;break;
  40982. case gl.SCISSOR_TEST:
  40983. self.scissorTest = true;break;
  40984. case gl.STENCIL_TEST:
  40985. self.stencilTest = true;break;
  40986. }
  40987. self.realEnable.call(gl, pname);
  40988. };
  40989. gl.disable = function (pname) {
  40990. switch (pname) {
  40991. case gl.CULL_FACE:
  40992. self.cullFace = false;break;
  40993. case gl.DEPTH_TEST:
  40994. self.depthTest = false;break;
  40995. case gl.BLEND:
  40996. self.blend = false;break;
  40997. case gl.SCISSOR_TEST:
  40998. self.scissorTest = false;break;
  40999. case gl.STENCIL_TEST:
  41000. self.stencilTest = false;break;
  41001. }
  41002. self.realDisable.call(gl, pname);
  41003. };
  41004. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  41005. gl.colorMask = function (r, g, b, a) {
  41006. self.colorMask[0] = r;
  41007. self.colorMask[1] = g;
  41008. self.colorMask[2] = b;
  41009. self.colorMask[3] = a;
  41010. self.realColorMask.call(gl, r, g, b, a);
  41011. };
  41012. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  41013. gl.clearColor = function (r, g, b, a) {
  41014. self.clearColor[0] = r;
  41015. self.clearColor[1] = g;
  41016. self.clearColor[2] = b;
  41017. self.clearColor[3] = a;
  41018. self.realClearColor.call(gl, r, g, b, a);
  41019. };
  41020. this.viewport = gl.getParameter(gl.VIEWPORT);
  41021. gl.viewport = function (x, y, w, h) {
  41022. self.viewport[0] = x;
  41023. self.viewport[1] = y;
  41024. self.viewport[2] = w;
  41025. self.viewport[3] = h;
  41026. self.realViewport.call(gl, x, y, w, h);
  41027. };
  41028. this.isPatched = true;
  41029. safariCssSizeWorkaround(canvas);
  41030. };
  41031. CardboardDistorter.prototype.unpatch = function () {
  41032. if (!this.isPatched) {
  41033. return;
  41034. }
  41035. var gl = this.gl;
  41036. var canvas = this.gl.canvas;
  41037. if (!isIOS()) {
  41038. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  41039. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  41040. }
  41041. canvas.width = this.bufferWidth;
  41042. canvas.height = this.bufferHeight;
  41043. gl.bindFramebuffer = this.realBindFramebuffer;
  41044. gl.enable = this.realEnable;
  41045. gl.disable = this.realDisable;
  41046. gl.colorMask = this.realColorMask;
  41047. gl.clearColor = this.realClearColor;
  41048. gl.viewport = this.realViewport;
  41049. if (this.lastBoundFramebuffer == this.framebuffer) {
  41050. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  41051. }
  41052. this.isPatched = false;
  41053. setTimeout(function () {
  41054. safariCssSizeWorkaround(canvas);
  41055. }, 1);
  41056. };
  41057. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  41058. if (!leftBounds) {
  41059. leftBounds = [0, 0, 0.5, 1];
  41060. }
  41061. if (!rightBounds) {
  41062. rightBounds = [0.5, 0, 0.5, 1];
  41063. }
  41064. this.viewportOffsetScale[0] = leftBounds[0];
  41065. this.viewportOffsetScale[1] = leftBounds[1];
  41066. this.viewportOffsetScale[2] = leftBounds[2];
  41067. this.viewportOffsetScale[3] = leftBounds[3];
  41068. this.viewportOffsetScale[4] = rightBounds[0];
  41069. this.viewportOffsetScale[5] = rightBounds[1];
  41070. this.viewportOffsetScale[6] = rightBounds[2];
  41071. this.viewportOffsetScale[7] = rightBounds[3];
  41072. };
  41073. CardboardDistorter.prototype.submitFrame = function () {
  41074. var gl = this.gl;
  41075. var self = this;
  41076. var glState = [];
  41077. if (!this.dirtySubmitFrameBindings) {
  41078. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  41079. }
  41080. glPreserveState(gl, glState, function (gl) {
  41081. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  41082. var positionDivisor = 0;
  41083. var texCoordDivisor = 0;
  41084. if (self.instanceExt) {
  41085. positionDivisor = gl.getVertexAttrib(self.attribs.position, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  41086. texCoordDivisor = gl.getVertexAttrib(self.attribs.texCoord, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  41087. }
  41088. if (self.cullFace) {
  41089. self.realDisable.call(gl, gl.CULL_FACE);
  41090. }
  41091. if (self.depthTest) {
  41092. self.realDisable.call(gl, gl.DEPTH_TEST);
  41093. }
  41094. if (self.blend) {
  41095. self.realDisable.call(gl, gl.BLEND);
  41096. }
  41097. if (self.scissorTest) {
  41098. self.realDisable.call(gl, gl.SCISSOR_TEST);
  41099. }
  41100. if (self.stencilTest) {
  41101. self.realDisable.call(gl, gl.STENCIL_TEST);
  41102. }
  41103. self.realColorMask.call(gl, true, true, true, true);
  41104. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41105. if (self.ctxAttribs.alpha || isIOS()) {
  41106. self.realClearColor.call(gl, 0, 0, 0, 1);
  41107. gl.clear(gl.COLOR_BUFFER_BIT);
  41108. }
  41109. gl.useProgram(self.program);
  41110. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41111. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41112. gl.enableVertexAttribArray(self.attribs.position);
  41113. gl.enableVertexAttribArray(self.attribs.texCoord);
  41114. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  41115. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  41116. if (self.instanceExt) {
  41117. if (positionDivisor != 0) {
  41118. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, 0);
  41119. }
  41120. if (texCoordDivisor != 0) {
  41121. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, 0);
  41122. }
  41123. }
  41124. gl.activeTexture(gl.TEXTURE0);
  41125. gl.uniform1i(self.uniforms.diffuse, 0);
  41126. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  41127. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  41128. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  41129. if (self.cardboardUI) {
  41130. self.cardboardUI.renderNoState();
  41131. }
  41132. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  41133. if (!self.ctxAttribs.preserveDrawingBuffer) {
  41134. self.realClearColor.call(gl, 0, 0, 0, 0);
  41135. gl.clear(gl.COLOR_BUFFER_BIT);
  41136. }
  41137. if (!self.dirtySubmitFrameBindings) {
  41138. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  41139. }
  41140. if (self.cullFace) {
  41141. self.realEnable.call(gl, gl.CULL_FACE);
  41142. }
  41143. if (self.depthTest) {
  41144. self.realEnable.call(gl, gl.DEPTH_TEST);
  41145. }
  41146. if (self.blend) {
  41147. self.realEnable.call(gl, gl.BLEND);
  41148. }
  41149. if (self.scissorTest) {
  41150. self.realEnable.call(gl, gl.SCISSOR_TEST);
  41151. }
  41152. if (self.stencilTest) {
  41153. self.realEnable.call(gl, gl.STENCIL_TEST);
  41154. }
  41155. self.realColorMask.apply(gl, self.colorMask);
  41156. self.realViewport.apply(gl, self.viewport);
  41157. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  41158. self.realClearColor.apply(gl, self.clearColor);
  41159. }
  41160. if (self.instanceExt) {
  41161. if (positionDivisor != 0) {
  41162. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, positionDivisor);
  41163. }
  41164. if (texCoordDivisor != 0) {
  41165. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, texCoordDivisor);
  41166. }
  41167. }
  41168. });
  41169. if (isIOS()) {
  41170. var canvas = gl.canvas;
  41171. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  41172. self.bufferWidth = canvas.width;
  41173. self.bufferHeight = canvas.height;
  41174. self.onResize();
  41175. }
  41176. }
  41177. };
  41178. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  41179. var gl = this.gl;
  41180. var self = this;
  41181. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  41182. glPreserveState(gl, glState, function (gl) {
  41183. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  41184. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41185. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  41186. if (!self.indexCount) {
  41187. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  41188. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41189. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  41190. self.indexCount = indices.length;
  41191. }
  41192. });
  41193. };
  41194. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  41195. var vertices = new Float32Array(2 * width * height * 5);
  41196. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  41197. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  41198. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  41199. var vidx = 0;
  41200. for (var e = 0; e < 2; e++) {
  41201. for (var j = 0; j < height; j++) {
  41202. for (var i = 0; i < width; i++, vidx++) {
  41203. var u = i / (width - 1);
  41204. var v = j / (height - 1);
  41205. var s = u;
  41206. var t = v;
  41207. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  41208. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  41209. var d = Math.sqrt(x * x + y * y);
  41210. var r = deviceInfo.distortion.distortInverse(d);
  41211. var p = x * r / d;
  41212. var q = y * r / d;
  41213. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  41214. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  41215. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  41216. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  41217. vertices[vidx * 5 + 0] = u;
  41218. vertices[vidx * 5 + 1] = v;
  41219. vertices[vidx * 5 + 2] = s;
  41220. vertices[vidx * 5 + 3] = t;
  41221. vertices[vidx * 5 + 4] = e;
  41222. }
  41223. }
  41224. var w = lensFrustum[2] - lensFrustum[0];
  41225. lensFrustum[0] = -(w + lensFrustum[0]);
  41226. lensFrustum[2] = w - lensFrustum[2];
  41227. w = noLensFrustum[2] - noLensFrustum[0];
  41228. noLensFrustum[0] = -(w + noLensFrustum[0]);
  41229. noLensFrustum[2] = w - noLensFrustum[2];
  41230. viewport.x = 1 - (viewport.x + viewport.width);
  41231. }
  41232. return vertices;
  41233. };
  41234. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  41235. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  41236. var halfwidth = width / 2;
  41237. var halfheight = height / 2;
  41238. var vidx = 0;
  41239. var iidx = 0;
  41240. for (var e = 0; e < 2; e++) {
  41241. for (var j = 0; j < height; j++) {
  41242. for (var i = 0; i < width; i++, vidx++) {
  41243. if (i == 0 || j == 0) continue;
  41244. if (i <= halfwidth == j <= halfheight) {
  41245. indices[iidx++] = vidx;
  41246. indices[iidx++] = vidx - width - 1;
  41247. indices[iidx++] = vidx - width;
  41248. indices[iidx++] = vidx - width - 1;
  41249. indices[iidx++] = vidx;
  41250. indices[iidx++] = vidx - 1;
  41251. } else {
  41252. indices[iidx++] = vidx - 1;
  41253. indices[iidx++] = vidx - width;
  41254. indices[iidx++] = vidx;
  41255. indices[iidx++] = vidx - width;
  41256. indices[iidx++] = vidx - 1;
  41257. indices[iidx++] = vidx - width - 1;
  41258. }
  41259. }
  41260. }
  41261. }
  41262. return indices;
  41263. };
  41264. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  41265. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  41266. if (descriptor.get === undefined || descriptor.set === undefined) {
  41267. descriptor.configurable = true;
  41268. descriptor.enumerable = true;
  41269. descriptor.get = function () {
  41270. return this.getAttribute(attrName);
  41271. };
  41272. descriptor.set = function (val) {
  41273. this.setAttribute(attrName, val);
  41274. };
  41275. }
  41276. return descriptor;
  41277. };
  41278. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  41279. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  41280. var DEG2RAD = Math.PI / 180.0;
  41281. var kAnglePerGearSection = 60;
  41282. var kOuterRimEndAngle = 12;
  41283. var kInnerRimBeginAngle = 20;
  41284. var kOuterRadius = 1;
  41285. var kMiddleRadius = 0.75;
  41286. var kInnerRadius = 0.3125;
  41287. var kCenterLineThicknessDp = 4;
  41288. var kButtonWidthDp = 28;
  41289. var kTouchSlopFactor = 1.5;
  41290. function CardboardUI(gl) {
  41291. this.gl = gl;
  41292. this.attribs = {
  41293. position: 0
  41294. };
  41295. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  41296. this.uniforms = getProgramUniforms(gl, this.program);
  41297. this.vertexBuffer = gl.createBuffer();
  41298. this.gearOffset = 0;
  41299. this.gearVertexCount = 0;
  41300. this.arrowOffset = 0;
  41301. this.arrowVertexCount = 0;
  41302. this.projMat = new Float32Array(16);
  41303. this.listener = null;
  41304. this.onResize();
  41305. }
  41306. CardboardUI.prototype.destroy = function () {
  41307. var gl = this.gl;
  41308. if (this.listener) {
  41309. gl.canvas.removeEventListener('click', this.listener, false);
  41310. }
  41311. gl.deleteProgram(this.program);
  41312. gl.deleteBuffer(this.vertexBuffer);
  41313. };
  41314. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  41315. var canvas = this.gl.canvas;
  41316. this.listener = function (event) {
  41317. var midline = canvas.clientWidth / 2;
  41318. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  41319. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  41320. optionsCallback(event);
  41321. }
  41322. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  41323. backCallback(event);
  41324. }
  41325. };
  41326. canvas.addEventListener('click', this.listener, false);
  41327. };
  41328. CardboardUI.prototype.onResize = function () {
  41329. var gl = this.gl;
  41330. var self = this;
  41331. var glState = [gl.ARRAY_BUFFER_BINDING];
  41332. glPreserveState(gl, glState, function (gl) {
  41333. var vertices = [];
  41334. var midline = gl.drawingBufferWidth / 2;
  41335. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  41336. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  41337. var dps = scalingRatio * window.devicePixelRatio;
  41338. var lineWidth = kCenterLineThicknessDp * dps / 2;
  41339. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  41340. var buttonScale = kButtonWidthDp * dps / 2;
  41341. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  41342. vertices.push(midline - lineWidth, buttonSize);
  41343. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  41344. vertices.push(midline + lineWidth, buttonSize);
  41345. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  41346. self.gearOffset = vertices.length / 2;
  41347. function addGearSegment(theta, r) {
  41348. var angle = (90 - theta) * DEG2RAD;
  41349. var x = Math.cos(angle);
  41350. var y = Math.sin(angle);
  41351. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  41352. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  41353. }
  41354. for (var i = 0; i <= 6; i++) {
  41355. var segmentTheta = i * kAnglePerGearSection;
  41356. addGearSegment(segmentTheta, kOuterRadius);
  41357. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  41358. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  41359. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  41360. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  41361. }
  41362. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  41363. self.arrowOffset = vertices.length / 2;
  41364. function addArrowVertex(x, y) {
  41365. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  41366. }
  41367. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  41368. addArrowVertex(0, buttonScale);
  41369. addArrowVertex(buttonScale, 0);
  41370. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  41371. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  41372. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41373. addArrowVertex(0, buttonScale);
  41374. addArrowVertex(buttonScale, buttonScale * 2);
  41375. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  41376. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41377. addArrowVertex(0, buttonScale);
  41378. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  41379. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  41380. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  41381. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  41382. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  41383. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41384. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  41385. });
  41386. };
  41387. CardboardUI.prototype.render = function () {
  41388. var gl = this.gl;
  41389. var self = this;
  41390. 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];
  41391. glPreserveState(gl, glState, function (gl) {
  41392. gl.disable(gl.CULL_FACE);
  41393. gl.disable(gl.DEPTH_TEST);
  41394. gl.disable(gl.BLEND);
  41395. gl.disable(gl.SCISSOR_TEST);
  41396. gl.disable(gl.STENCIL_TEST);
  41397. gl.colorMask(true, true, true, true);
  41398. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41399. self.renderNoState();
  41400. });
  41401. };
  41402. CardboardUI.prototype.renderNoState = function () {
  41403. var gl = this.gl;
  41404. gl.useProgram(this.program);
  41405. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  41406. gl.enableVertexAttribArray(this.attribs.position);
  41407. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  41408. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  41409. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  41410. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  41411. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  41412. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  41413. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  41414. };
  41415. function Distortion(coefficients) {
  41416. this.coefficients = coefficients;
  41417. }
  41418. Distortion.prototype.distortInverse = function (radius) {
  41419. var r0 = 0;
  41420. var r1 = 1;
  41421. var dr0 = radius - this.distort(r0);
  41422. while (Math.abs(r1 - r0) > 0.0001 ) {
  41423. var dr1 = radius - this.distort(r1);
  41424. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  41425. r0 = r1;
  41426. r1 = r2;
  41427. dr0 = dr1;
  41428. }
  41429. return r1;
  41430. };
  41431. Distortion.prototype.distort = function (radius) {
  41432. var r2 = radius * radius;
  41433. var ret = 0;
  41434. for (var i = 0; i < this.coefficients.length; i++) {
  41435. ret = r2 * (ret + this.coefficients[i]);
  41436. }
  41437. return (ret + 1) * radius;
  41438. };
  41439. var degToRad = Math.PI / 180;
  41440. var radToDeg = 180 / Math.PI;
  41441. var Vector3 = function Vector3(x, y, z) {
  41442. this.x = x || 0;
  41443. this.y = y || 0;
  41444. this.z = z || 0;
  41445. };
  41446. Vector3.prototype = {
  41447. constructor: Vector3,
  41448. set: function set(x, y, z) {
  41449. this.x = x;
  41450. this.y = y;
  41451. this.z = z;
  41452. return this;
  41453. },
  41454. copy: function copy(v) {
  41455. this.x = v.x;
  41456. this.y = v.y;
  41457. this.z = v.z;
  41458. return this;
  41459. },
  41460. length: function length() {
  41461. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  41462. },
  41463. normalize: function normalize() {
  41464. var scalar = this.length();
  41465. if (scalar !== 0) {
  41466. var invScalar = 1 / scalar;
  41467. this.multiplyScalar(invScalar);
  41468. } else {
  41469. this.x = 0;
  41470. this.y = 0;
  41471. this.z = 0;
  41472. }
  41473. return this;
  41474. },
  41475. multiplyScalar: function multiplyScalar(scalar) {
  41476. this.x *= scalar;
  41477. this.y *= scalar;
  41478. this.z *= scalar;
  41479. },
  41480. applyQuaternion: function applyQuaternion(q) {
  41481. var x = this.x;
  41482. var y = this.y;
  41483. var z = this.z;
  41484. var qx = q.x;
  41485. var qy = q.y;
  41486. var qz = q.z;
  41487. var qw = q.w;
  41488. var ix = qw * x + qy * z - qz * y;
  41489. var iy = qw * y + qz * x - qx * z;
  41490. var iz = qw * z + qx * y - qy * x;
  41491. var iw = -qx * x - qy * y - qz * z;
  41492. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  41493. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  41494. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  41495. return this;
  41496. },
  41497. dot: function dot(v) {
  41498. return this.x * v.x + this.y * v.y + this.z * v.z;
  41499. },
  41500. crossVectors: function crossVectors(a, b) {
  41501. var ax = a.x,
  41502. ay = a.y,
  41503. az = a.z;
  41504. var bx = b.x,
  41505. by = b.y,
  41506. bz = b.z;
  41507. this.x = ay * bz - az * by;
  41508. this.y = az * bx - ax * bz;
  41509. this.z = ax * by - ay * bx;
  41510. return this;
  41511. }
  41512. };
  41513. var Quaternion = function Quaternion(x, y, z, w) {
  41514. this.x = x || 0;
  41515. this.y = y || 0;
  41516. this.z = z || 0;
  41517. this.w = w !== undefined ? w : 1;
  41518. };
  41519. Quaternion.prototype = {
  41520. constructor: Quaternion,
  41521. set: function set(x, y, z, w) {
  41522. this.x = x;
  41523. this.y = y;
  41524. this.z = z;
  41525. this.w = w;
  41526. return this;
  41527. },
  41528. copy: function copy(quaternion) {
  41529. this.x = quaternion.x;
  41530. this.y = quaternion.y;
  41531. this.z = quaternion.z;
  41532. this.w = quaternion.w;
  41533. return this;
  41534. },
  41535. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  41536. var c1 = Math.cos(x / 2);
  41537. var c2 = Math.cos(y / 2);
  41538. var c3 = Math.cos(z / 2);
  41539. var s1 = Math.sin(x / 2);
  41540. var s2 = Math.sin(y / 2);
  41541. var s3 = Math.sin(z / 2);
  41542. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41543. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41544. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  41545. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  41546. return this;
  41547. },
  41548. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  41549. var c1 = Math.cos(x / 2);
  41550. var c2 = Math.cos(y / 2);
  41551. var c3 = Math.cos(z / 2);
  41552. var s1 = Math.sin(x / 2);
  41553. var s2 = Math.sin(y / 2);
  41554. var s3 = Math.sin(z / 2);
  41555. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41556. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41557. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  41558. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  41559. return this;
  41560. },
  41561. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  41562. var halfAngle = angle / 2,
  41563. s = Math.sin(halfAngle);
  41564. this.x = axis.x * s;
  41565. this.y = axis.y * s;
  41566. this.z = axis.z * s;
  41567. this.w = Math.cos(halfAngle);
  41568. return this;
  41569. },
  41570. multiply: function multiply(q) {
  41571. return this.multiplyQuaternions(this, q);
  41572. },
  41573. multiplyQuaternions: function multiplyQuaternions(a, b) {
  41574. var qax = a.x,
  41575. qay = a.y,
  41576. qaz = a.z,
  41577. qaw = a.w;
  41578. var qbx = b.x,
  41579. qby = b.y,
  41580. qbz = b.z,
  41581. qbw = b.w;
  41582. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  41583. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  41584. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  41585. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  41586. return this;
  41587. },
  41588. inverse: function inverse() {
  41589. this.x *= -1;
  41590. this.y *= -1;
  41591. this.z *= -1;
  41592. this.normalize();
  41593. return this;
  41594. },
  41595. normalize: function normalize() {
  41596. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  41597. if (l === 0) {
  41598. this.x = 0;
  41599. this.y = 0;
  41600. this.z = 0;
  41601. this.w = 1;
  41602. } else {
  41603. l = 1 / l;
  41604. this.x = this.x * l;
  41605. this.y = this.y * l;
  41606. this.z = this.z * l;
  41607. this.w = this.w * l;
  41608. }
  41609. return this;
  41610. },
  41611. slerp: function slerp(qb, t) {
  41612. if (t === 0) return this;
  41613. if (t === 1) return this.copy(qb);
  41614. var x = this.x,
  41615. y = this.y,
  41616. z = this.z,
  41617. w = this.w;
  41618. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  41619. if (cosHalfTheta < 0) {
  41620. this.w = -qb.w;
  41621. this.x = -qb.x;
  41622. this.y = -qb.y;
  41623. this.z = -qb.z;
  41624. cosHalfTheta = -cosHalfTheta;
  41625. } else {
  41626. this.copy(qb);
  41627. }
  41628. if (cosHalfTheta >= 1.0) {
  41629. this.w = w;
  41630. this.x = x;
  41631. this.y = y;
  41632. this.z = z;
  41633. return this;
  41634. }
  41635. var halfTheta = Math.acos(cosHalfTheta);
  41636. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  41637. if (Math.abs(sinHalfTheta) < 0.001) {
  41638. this.w = 0.5 * (w + this.w);
  41639. this.x = 0.5 * (x + this.x);
  41640. this.y = 0.5 * (y + this.y);
  41641. this.z = 0.5 * (z + this.z);
  41642. return this;
  41643. }
  41644. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  41645. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  41646. this.w = w * ratioA + this.w * ratioB;
  41647. this.x = x * ratioA + this.x * ratioB;
  41648. this.y = y * ratioA + this.y * ratioB;
  41649. this.z = z * ratioA + this.z * ratioB;
  41650. return this;
  41651. },
  41652. setFromUnitVectors: function () {
  41653. var v1, r;
  41654. var EPS = 0.000001;
  41655. return function (vFrom, vTo) {
  41656. if (v1 === undefined) v1 = new Vector3();
  41657. r = vFrom.dot(vTo) + 1;
  41658. if (r < EPS) {
  41659. r = 0;
  41660. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  41661. v1.set(-vFrom.y, vFrom.x, 0);
  41662. } else {
  41663. v1.set(0, -vFrom.z, vFrom.y);
  41664. }
  41665. } else {
  41666. v1.crossVectors(vFrom, vTo);
  41667. }
  41668. this.x = v1.x;
  41669. this.y = v1.y;
  41670. this.z = v1.z;
  41671. this.w = r;
  41672. this.normalize();
  41673. return this;
  41674. };
  41675. }()
  41676. };
  41677. function Device(params) {
  41678. this.width = params.width || getScreenWidth();
  41679. this.height = params.height || getScreenHeight();
  41680. this.widthMeters = params.widthMeters;
  41681. this.heightMeters = params.heightMeters;
  41682. this.bevelMeters = params.bevelMeters;
  41683. }
  41684. var DEFAULT_ANDROID = new Device({
  41685. widthMeters: 0.110,
  41686. heightMeters: 0.062,
  41687. bevelMeters: 0.004
  41688. });
  41689. var DEFAULT_IOS = new Device({
  41690. widthMeters: 0.1038,
  41691. heightMeters: 0.0584,
  41692. bevelMeters: 0.004
  41693. });
  41694. var Viewers = {
  41695. CardboardV1: new CardboardViewer({
  41696. id: 'CardboardV1',
  41697. label: 'Cardboard I/O 2014',
  41698. fov: 40,
  41699. interLensDistance: 0.060,
  41700. baselineLensDistance: 0.035,
  41701. screenLensDistance: 0.042,
  41702. distortionCoefficients: [0.441, 0.156],
  41703. 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]
  41704. }),
  41705. CardboardV2: new CardboardViewer({
  41706. id: 'CardboardV2',
  41707. label: 'Cardboard I/O 2015',
  41708. fov: 60,
  41709. interLensDistance: 0.064,
  41710. baselineLensDistance: 0.035,
  41711. screenLensDistance: 0.039,
  41712. distortionCoefficients: [0.34, 0.55],
  41713. 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]
  41714. })
  41715. };
  41716. function DeviceInfo(deviceParams, additionalViewers) {
  41717. this.viewer = Viewers.CardboardV2;
  41718. this.updateDeviceParams(deviceParams);
  41719. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41720. for (var i = 0; i < additionalViewers.length; i++) {
  41721. var viewer = additionalViewers[i];
  41722. Viewers[viewer.id] = new CardboardViewer(viewer);
  41723. }
  41724. }
  41725. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  41726. this.device = this.determineDevice_(deviceParams) || this.device;
  41727. };
  41728. DeviceInfo.prototype.getDevice = function () {
  41729. return this.device;
  41730. };
  41731. DeviceInfo.prototype.setViewer = function (viewer) {
  41732. this.viewer = viewer;
  41733. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41734. };
  41735. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  41736. if (!deviceParams) {
  41737. if (isIOS()) {
  41738. console.warn('Using fallback iOS device measurements.');
  41739. return DEFAULT_IOS;
  41740. } else {
  41741. console.warn('Using fallback Android device measurements.');
  41742. return DEFAULT_ANDROID;
  41743. }
  41744. }
  41745. var METERS_PER_INCH = 0.0254;
  41746. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  41747. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  41748. var width = getScreenWidth();
  41749. var height = getScreenHeight();
  41750. return new Device({
  41751. widthMeters: metersPerPixelX * width,
  41752. heightMeters: metersPerPixelY * height,
  41753. bevelMeters: deviceParams.bevelMm * 0.001
  41754. });
  41755. };
  41756. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  41757. var viewer = this.viewer;
  41758. var device = this.device;
  41759. var distortion = this.distortion;
  41760. var eyeToScreenDistance = viewer.screenLensDistance;
  41761. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  41762. var innerDist = viewer.interLensDistance / 2;
  41763. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  41764. var topDist = device.heightMeters - bottomDist;
  41765. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  41766. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  41767. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  41768. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  41769. return {
  41770. leftDegrees: Math.min(outerAngle, viewer.fov),
  41771. rightDegrees: Math.min(innerAngle, viewer.fov),
  41772. downDegrees: Math.min(bottomAngle, viewer.fov),
  41773. upDegrees: Math.min(topAngle, viewer.fov)
  41774. };
  41775. };
  41776. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  41777. var viewer = this.viewer;
  41778. var device = this.device;
  41779. var distortion = this.distortion;
  41780. var fovLeft = Math.tan(-degToRad * viewer.fov);
  41781. var fovTop = Math.tan(degToRad * viewer.fov);
  41782. var fovRight = Math.tan(degToRad * viewer.fov);
  41783. var fovBottom = Math.tan(-degToRad * viewer.fov);
  41784. var halfWidth = device.widthMeters / 4;
  41785. var halfHeight = device.heightMeters / 2;
  41786. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  41787. var centerX = viewer.interLensDistance / 2 - halfWidth;
  41788. var centerY = -verticalLensOffset;
  41789. var centerZ = viewer.screenLensDistance;
  41790. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  41791. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  41792. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  41793. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  41794. var result = new Float32Array(4);
  41795. result[0] = Math.max(fovLeft, screenLeft);
  41796. result[1] = Math.min(fovTop, screenTop);
  41797. result[2] = Math.min(fovRight, screenRight);
  41798. result[3] = Math.max(fovBottom, screenBottom);
  41799. return result;
  41800. };
  41801. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  41802. var viewer = this.viewer;
  41803. var device = this.device;
  41804. var distortion = this.distortion;
  41805. var result = new Float32Array(4);
  41806. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  41807. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  41808. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  41809. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  41810. var halfWidth = device.widthMeters / 4;
  41811. var halfHeight = device.heightMeters / 2;
  41812. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  41813. var centerX = viewer.interLensDistance / 2 - halfWidth;
  41814. var centerY = -verticalLensOffset;
  41815. var centerZ = viewer.screenLensDistance;
  41816. var screenLeft = (centerX - halfWidth) / centerZ;
  41817. var screenTop = (centerY + halfHeight) / centerZ;
  41818. var screenRight = (centerX + halfWidth) / centerZ;
  41819. var screenBottom = (centerY - halfHeight) / centerZ;
  41820. result[0] = Math.max(fovLeft, screenLeft);
  41821. result[1] = Math.min(fovTop, screenTop);
  41822. result[2] = Math.min(fovRight, screenRight);
  41823. result[3] = Math.max(fovBottom, screenBottom);
  41824. return result;
  41825. };
  41826. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  41827. var viewer = this.viewer;
  41828. var device = this.device;
  41829. var dist = viewer.screenLensDistance;
  41830. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  41831. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  41832. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  41833. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  41834. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  41835. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  41836. return {
  41837. x: left,
  41838. y: bottom,
  41839. width: right - left,
  41840. height: top - bottom
  41841. };
  41842. };
  41843. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  41844. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  41845. };
  41846. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  41847. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  41848. return {
  41849. leftDegrees: fov.rightDegrees,
  41850. rightDegrees: fov.leftDegrees,
  41851. upDegrees: fov.upDegrees,
  41852. downDegrees: fov.downDegrees
  41853. };
  41854. };
  41855. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  41856. var p = this.getUndistortedParams_();
  41857. return {
  41858. leftDegrees: radToDeg * Math.atan(p.outerDist),
  41859. rightDegrees: radToDeg * Math.atan(p.innerDist),
  41860. downDegrees: radToDeg * Math.atan(p.bottomDist),
  41861. upDegrees: radToDeg * Math.atan(p.topDist)
  41862. };
  41863. };
  41864. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  41865. var p = this.getUndistortedParams_();
  41866. var viewer = this.viewer;
  41867. var device = this.device;
  41868. var eyeToScreenDistance = viewer.screenLensDistance;
  41869. var screenWidth = device.widthMeters / eyeToScreenDistance;
  41870. var screenHeight = device.heightMeters / eyeToScreenDistance;
  41871. var xPxPerTanAngle = device.width / screenWidth;
  41872. var yPxPerTanAngle = device.height / screenHeight;
  41873. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  41874. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  41875. return {
  41876. x: x,
  41877. y: y,
  41878. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  41879. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  41880. };
  41881. };
  41882. DeviceInfo.prototype.getUndistortedParams_ = function () {
  41883. var viewer = this.viewer;
  41884. var device = this.device;
  41885. var distortion = this.distortion;
  41886. var eyeToScreenDistance = viewer.screenLensDistance;
  41887. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  41888. var screenWidth = device.widthMeters / eyeToScreenDistance;
  41889. var screenHeight = device.heightMeters / eyeToScreenDistance;
  41890. var eyePosX = screenWidth / 2 - halfLensDistance;
  41891. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  41892. var maxFov = viewer.fov;
  41893. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  41894. var outerDist = Math.min(eyePosX, viewerMax);
  41895. var innerDist = Math.min(halfLensDistance, viewerMax);
  41896. var bottomDist = Math.min(eyePosY, viewerMax);
  41897. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  41898. return {
  41899. outerDist: outerDist,
  41900. innerDist: innerDist,
  41901. topDist: topDist,
  41902. bottomDist: bottomDist,
  41903. eyePosX: eyePosX,
  41904. eyePosY: eyePosY
  41905. };
  41906. };
  41907. function CardboardViewer(params) {
  41908. this.id = params.id;
  41909. this.label = params.label;
  41910. this.fov = params.fov;
  41911. this.interLensDistance = params.interLensDistance;
  41912. this.baselineLensDistance = params.baselineLensDistance;
  41913. this.screenLensDistance = params.screenLensDistance;
  41914. this.distortionCoefficients = params.distortionCoefficients;
  41915. this.inverseCoefficients = params.inverseCoefficients;
  41916. }
  41917. DeviceInfo.Viewers = Viewers;
  41918. var format = 1;
  41919. var last_updated = "2019-11-09T17:36:14Z";
  41920. 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}];
  41921. var DPDB_CACHE = {
  41922. format: format,
  41923. last_updated: last_updated,
  41924. devices: devices
  41925. };
  41926. function Dpdb(url, onDeviceParamsUpdated) {
  41927. this.dpdb = DPDB_CACHE;
  41928. this.recalculateDeviceParams_();
  41929. if (url) {
  41930. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  41931. var xhr = new XMLHttpRequest();
  41932. var obj = this;
  41933. xhr.open('GET', url, true);
  41934. xhr.addEventListener('load', function () {
  41935. obj.loading = false;
  41936. if (xhr.status >= 200 && xhr.status <= 299) {
  41937. obj.dpdb = JSON.parse(xhr.response);
  41938. obj.recalculateDeviceParams_();
  41939. } else {
  41940. console.error('Error loading online DPDB!');
  41941. }
  41942. });
  41943. xhr.send();
  41944. }
  41945. }
  41946. Dpdb.prototype.getDeviceParams = function () {
  41947. return this.deviceParams;
  41948. };
  41949. Dpdb.prototype.recalculateDeviceParams_ = function () {
  41950. var newDeviceParams = this.calcDeviceParams_();
  41951. if (newDeviceParams) {
  41952. this.deviceParams = newDeviceParams;
  41953. if (this.onDeviceParamsUpdated) {
  41954. this.onDeviceParamsUpdated(this.deviceParams);
  41955. }
  41956. } else {
  41957. console.error('Failed to recalculate device parameters.');
  41958. }
  41959. };
  41960. Dpdb.prototype.calcDeviceParams_ = function () {
  41961. var db = this.dpdb;
  41962. if (!db) {
  41963. console.error('DPDB not available.');
  41964. return null;
  41965. }
  41966. if (db.format != 1) {
  41967. console.error('DPDB has unexpected format version.');
  41968. return null;
  41969. }
  41970. if (!db.devices || !db.devices.length) {
  41971. console.error('DPDB does not have a devices section.');
  41972. return null;
  41973. }
  41974. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  41975. var width = getScreenWidth();
  41976. var height = getScreenHeight();
  41977. if (!db.devices) {
  41978. console.error('DPDB has no devices section.');
  41979. return null;
  41980. }
  41981. for (var i = 0; i < db.devices.length; i++) {
  41982. var device = db.devices[i];
  41983. if (!device.rules) {
  41984. console.warn('Device[' + i + '] has no rules section.');
  41985. continue;
  41986. }
  41987. if (device.type != 'ios' && device.type != 'android') {
  41988. console.warn('Device[' + i + '] has invalid type.');
  41989. continue;
  41990. }
  41991. if (isIOS() != (device.type == 'ios')) continue;
  41992. var matched = false;
  41993. for (var j = 0; j < device.rules.length; j++) {
  41994. var rule = device.rules[j];
  41995. if (this.ruleMatches_(rule, userAgent, width, height)) {
  41996. matched = true;
  41997. break;
  41998. }
  41999. }
  42000. if (!matched) continue;
  42001. var xdpi = device.dpi[0] || device.dpi;
  42002. var ydpi = device.dpi[1] || device.dpi;
  42003. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  42004. }
  42005. console.warn('No DPDB device match.');
  42006. return null;
  42007. };
  42008. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  42009. if (!rule.ua && !rule.res) return false;
  42010. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  42011. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  42012. if (rule.res) {
  42013. if (!rule.res[0] || !rule.res[1]) return false;
  42014. var resX = rule.res[0];
  42015. var resY = rule.res[1];
  42016. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  42017. return false;
  42018. }
  42019. }
  42020. return true;
  42021. };
  42022. function DeviceParams(params) {
  42023. this.xdpi = params.xdpi;
  42024. this.ydpi = params.ydpi;
  42025. this.bevelMm = params.bevelMm;
  42026. }
  42027. function SensorSample(sample, timestampS) {
  42028. this.set(sample, timestampS);
  42029. }
  42030. SensorSample.prototype.set = function (sample, timestampS) {
  42031. this.sample = sample;
  42032. this.timestampS = timestampS;
  42033. };
  42034. SensorSample.prototype.copy = function (sensorSample) {
  42035. this.set(sensorSample.sample, sensorSample.timestampS);
  42036. };
  42037. function ComplementaryFilter(kFilter, isDebug) {
  42038. this.kFilter = kFilter;
  42039. this.isDebug = isDebug;
  42040. this.currentAccelMeasurement = new SensorSample();
  42041. this.currentGyroMeasurement = new SensorSample();
  42042. this.previousGyroMeasurement = new SensorSample();
  42043. if (isIOS()) {
  42044. this.filterQ = new Quaternion(-1, 0, 0, 1);
  42045. } else {
  42046. this.filterQ = new Quaternion(1, 0, 0, 1);
  42047. }
  42048. this.previousFilterQ = new Quaternion();
  42049. this.previousFilterQ.copy(this.filterQ);
  42050. this.accelQ = new Quaternion();
  42051. this.isOrientationInitialized = false;
  42052. this.estimatedGravity = new Vector3();
  42053. this.measuredGravity = new Vector3();
  42054. this.gyroIntegralQ = new Quaternion();
  42055. }
  42056. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  42057. this.currentAccelMeasurement.set(vector, timestampS);
  42058. };
  42059. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  42060. this.currentGyroMeasurement.set(vector, timestampS);
  42061. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  42062. if (isTimestampDeltaValid(deltaT)) {
  42063. this.run_();
  42064. }
  42065. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  42066. };
  42067. ComplementaryFilter.prototype.run_ = function () {
  42068. if (!this.isOrientationInitialized) {
  42069. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  42070. this.previousFilterQ.copy(this.accelQ);
  42071. this.isOrientationInitialized = true;
  42072. return;
  42073. }
  42074. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  42075. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  42076. this.gyroIntegralQ.multiply(gyroDeltaQ);
  42077. this.filterQ.copy(this.previousFilterQ);
  42078. this.filterQ.multiply(gyroDeltaQ);
  42079. var invFilterQ = new Quaternion();
  42080. invFilterQ.copy(this.filterQ);
  42081. invFilterQ.inverse();
  42082. this.estimatedGravity.set(0, 0, -1);
  42083. this.estimatedGravity.applyQuaternion(invFilterQ);
  42084. this.estimatedGravity.normalize();
  42085. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  42086. this.measuredGravity.normalize();
  42087. var deltaQ = new Quaternion();
  42088. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  42089. deltaQ.inverse();
  42090. if (this.isDebug) {
  42091. 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));
  42092. }
  42093. var targetQ = new Quaternion();
  42094. targetQ.copy(this.filterQ);
  42095. targetQ.multiply(deltaQ);
  42096. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  42097. this.previousFilterQ.copy(this.filterQ);
  42098. };
  42099. ComplementaryFilter.prototype.getOrientation = function () {
  42100. return this.filterQ;
  42101. };
  42102. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  42103. var normAccel = new Vector3();
  42104. normAccel.copy(accel);
  42105. normAccel.normalize();
  42106. var quat = new Quaternion();
  42107. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  42108. quat.inverse();
  42109. return quat;
  42110. };
  42111. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  42112. var quat = new Quaternion();
  42113. var axis = new Vector3();
  42114. axis.copy(gyro);
  42115. axis.normalize();
  42116. quat.setFromAxisAngle(axis, gyro.length() * dt);
  42117. return quat;
  42118. };
  42119. function PosePredictor(predictionTimeS, isDebug) {
  42120. this.predictionTimeS = predictionTimeS;
  42121. this.isDebug = isDebug;
  42122. this.previousQ = new Quaternion();
  42123. this.previousTimestampS = null;
  42124. this.deltaQ = new Quaternion();
  42125. this.outQ = new Quaternion();
  42126. }
  42127. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  42128. if (!this.previousTimestampS) {
  42129. this.previousQ.copy(currentQ);
  42130. this.previousTimestampS = timestampS;
  42131. return currentQ;
  42132. }
  42133. var axis = new Vector3();
  42134. axis.copy(gyro);
  42135. axis.normalize();
  42136. var angularSpeed = gyro.length();
  42137. if (angularSpeed < degToRad * 20) {
  42138. if (this.isDebug) {
  42139. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  42140. }
  42141. this.outQ.copy(currentQ);
  42142. this.previousQ.copy(currentQ);
  42143. return this.outQ;
  42144. }
  42145. var predictAngle = angularSpeed * this.predictionTimeS;
  42146. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  42147. this.outQ.copy(this.previousQ);
  42148. this.outQ.multiply(this.deltaQ);
  42149. this.previousQ.copy(currentQ);
  42150. this.previousTimestampS = timestampS;
  42151. return this.outQ;
  42152. };
  42153. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  42154. this.yawOnly = yawOnly;
  42155. this.accelerometer = new Vector3();
  42156. this.gyroscope = new Vector3();
  42157. this.filter = new ComplementaryFilter(kFilter, isDebug);
  42158. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  42159. this.isFirefoxAndroid = isFirefoxAndroid();
  42160. this.isIOS = isIOS();
  42161. var chromeVersion = getChromeVersion();
  42162. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  42163. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion() || isSafariWithoutDeviceMotion();
  42164. this.filterToWorldQ = new Quaternion();
  42165. if (isIOS()) {
  42166. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  42167. } else {
  42168. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42169. }
  42170. this.inverseWorldToScreenQ = new Quaternion();
  42171. this.worldToScreenQ = new Quaternion();
  42172. this.originalPoseAdjustQ = new Quaternion();
  42173. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  42174. this.setScreenTransform_();
  42175. if (isLandscapeMode()) {
  42176. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  42177. }
  42178. this.resetQ = new Quaternion();
  42179. this.orientationOut_ = new Float32Array(4);
  42180. this.start();
  42181. }
  42182. FusionPoseSensor.prototype.getPosition = function () {
  42183. return null;
  42184. };
  42185. FusionPoseSensor.prototype.getOrientation = function () {
  42186. var orientation = void 0;
  42187. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  42188. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  42189. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  42190. var y = new Quaternion();
  42191. if (window.orientation === -90) {
  42192. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  42193. } else {
  42194. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  42195. }
  42196. return z.multiply(y);
  42197. }();
  42198. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  42199. var q = new Quaternion();
  42200. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42201. return q;
  42202. }();
  42203. orientation = this._deviceOrientationQ;
  42204. var out = new Quaternion();
  42205. out.copy(orientation);
  42206. out.multiply(this.deviceOrientationFilterToWorldQ);
  42207. out.multiply(this.resetQ);
  42208. out.multiply(this.worldToScreenQ);
  42209. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  42210. if (this.yawOnly) {
  42211. out.x = 0;
  42212. out.z = 0;
  42213. out.normalize();
  42214. }
  42215. this.orientationOut_[0] = out.x;
  42216. this.orientationOut_[1] = out.y;
  42217. this.orientationOut_[2] = out.z;
  42218. this.orientationOut_[3] = out.w;
  42219. return this.orientationOut_;
  42220. } else {
  42221. var filterOrientation = this.filter.getOrientation();
  42222. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  42223. }
  42224. var out = new Quaternion();
  42225. out.copy(this.filterToWorldQ);
  42226. out.multiply(this.resetQ);
  42227. out.multiply(orientation);
  42228. out.multiply(this.worldToScreenQ);
  42229. if (this.yawOnly) {
  42230. out.x = 0;
  42231. out.z = 0;
  42232. out.normalize();
  42233. }
  42234. this.orientationOut_[0] = out.x;
  42235. this.orientationOut_[1] = out.y;
  42236. this.orientationOut_[2] = out.z;
  42237. this.orientationOut_[3] = out.w;
  42238. return this.orientationOut_;
  42239. };
  42240. FusionPoseSensor.prototype.resetPose = function () {
  42241. this.resetQ.copy(this.filter.getOrientation());
  42242. this.resetQ.x = 0;
  42243. this.resetQ.y = 0;
  42244. this.resetQ.z *= -1;
  42245. this.resetQ.normalize();
  42246. if (isLandscapeMode()) {
  42247. this.resetQ.multiply(this.inverseWorldToScreenQ);
  42248. }
  42249. this.resetQ.multiply(this.originalPoseAdjustQ);
  42250. };
  42251. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  42252. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  42253. var alpha = e.alpha,
  42254. beta = e.beta,
  42255. gamma = e.gamma;
  42256. alpha = (alpha || 0) * Math.PI / 180;
  42257. beta = (beta || 0) * Math.PI / 180;
  42258. gamma = (gamma || 0) * Math.PI / 180;
  42259. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  42260. };
  42261. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  42262. this.updateDeviceMotion_(deviceMotion);
  42263. };
  42264. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  42265. var accGravity = deviceMotion.accelerationIncludingGravity;
  42266. var rotRate = deviceMotion.rotationRate;
  42267. var timestampS = deviceMotion.timeStamp / 1000;
  42268. var deltaS = timestampS - this.previousTimestampS;
  42269. if (deltaS < 0) {
  42270. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  42271. this.previousTimestampS = timestampS;
  42272. return;
  42273. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  42274. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  42275. this.previousTimestampS = timestampS;
  42276. return;
  42277. }
  42278. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  42279. if (rotRate) {
  42280. if (isR7()) {
  42281. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  42282. } else {
  42283. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  42284. }
  42285. if (!this.isDeviceMotionInRadians) {
  42286. this.gyroscope.multiplyScalar(Math.PI / 180);
  42287. }
  42288. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  42289. }
  42290. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  42291. this.previousTimestampS = timestampS;
  42292. };
  42293. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  42294. this.setScreenTransform_();
  42295. };
  42296. FusionPoseSensor.prototype.onMessage_ = function (event) {
  42297. var message = event.data;
  42298. if (!message || !message.type) {
  42299. return;
  42300. }
  42301. var type = message.type.toLowerCase();
  42302. if (type !== 'devicemotion') {
  42303. return;
  42304. }
  42305. this.updateDeviceMotion_(message.deviceMotionEvent);
  42306. };
  42307. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  42308. this.worldToScreenQ.set(0, 0, 0, 1);
  42309. switch (window.orientation) {
  42310. case 0:
  42311. break;
  42312. case 90:
  42313. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  42314. break;
  42315. case -90:
  42316. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  42317. break;
  42318. case 180:
  42319. break;
  42320. }
  42321. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  42322. this.inverseWorldToScreenQ.inverse();
  42323. };
  42324. FusionPoseSensor.prototype.start = function () {
  42325. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  42326. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  42327. this.onMessageCallback_ = this.onMessage_.bind(this);
  42328. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  42329. if (isIOS() && isInsideCrossOriginIFrame()) {
  42330. window.addEventListener('message', this.onMessageCallback_);
  42331. }
  42332. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  42333. if (this.isWithoutDeviceMotion) {
  42334. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42335. } else {
  42336. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  42337. }
  42338. };
  42339. FusionPoseSensor.prototype.stop = function () {
  42340. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  42341. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42342. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  42343. window.removeEventListener('message', this.onMessageCallback_);
  42344. };
  42345. var SENSOR_FREQUENCY = 60;
  42346. var X_AXIS = new Vector3(1, 0, 0);
  42347. var Z_AXIS = new Vector3(0, 0, 1);
  42348. var SENSOR_TO_VR = new Quaternion();
  42349. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  42350. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  42351. var PoseSensor = function () {
  42352. function PoseSensor(config) {
  42353. classCallCheck(this, PoseSensor);
  42354. this.config = config;
  42355. this.sensor = null;
  42356. this.fusionSensor = null;
  42357. this._out = new Float32Array(4);
  42358. this.api = null;
  42359. this.errors = [];
  42360. this._sensorQ = new Quaternion();
  42361. this._outQ = new Quaternion();
  42362. this._onSensorRead = this._onSensorRead.bind(this);
  42363. this._onSensorError = this._onSensorError.bind(this);
  42364. this.init();
  42365. }
  42366. createClass(PoseSensor, [{
  42367. key: 'init',
  42368. value: function init() {
  42369. var sensor = null;
  42370. try {
  42371. sensor = new RelativeOrientationSensor({
  42372. frequency: SENSOR_FREQUENCY,
  42373. referenceFrame: 'screen'
  42374. });
  42375. sensor.addEventListener('error', this._onSensorError);
  42376. } catch (error) {
  42377. this.errors.push(error);
  42378. if (error.name === 'SecurityError') {
  42379. console.error('Cannot construct sensors due to the Feature Policy');
  42380. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  42381. this.useDeviceMotion();
  42382. } else if (error.name === 'ReferenceError') {
  42383. this.useDeviceMotion();
  42384. } else {
  42385. console.error(error);
  42386. }
  42387. }
  42388. if (sensor) {
  42389. this.api = 'sensor';
  42390. this.sensor = sensor;
  42391. this.sensor.addEventListener('reading', this._onSensorRead);
  42392. this.sensor.start();
  42393. }
  42394. }
  42395. }, {
  42396. key: 'useDeviceMotion',
  42397. value: function useDeviceMotion() {
  42398. this.api = 'devicemotion';
  42399. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  42400. if (this.sensor) {
  42401. this.sensor.removeEventListener('reading', this._onSensorRead);
  42402. this.sensor.removeEventListener('error', this._onSensorError);
  42403. this.sensor = null;
  42404. }
  42405. }
  42406. }, {
  42407. key: 'getOrientation',
  42408. value: function getOrientation() {
  42409. if (this.fusionSensor) {
  42410. return this.fusionSensor.getOrientation();
  42411. }
  42412. if (!this.sensor || !this.sensor.quaternion) {
  42413. this._out[0] = this._out[1] = this._out[2] = 0;
  42414. this._out[3] = 1;
  42415. return this._out;
  42416. }
  42417. var q = this.sensor.quaternion;
  42418. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  42419. var out = this._outQ;
  42420. out.copy(SENSOR_TO_VR);
  42421. out.multiply(this._sensorQ);
  42422. if (this.config.YAW_ONLY) {
  42423. out.x = out.z = 0;
  42424. out.normalize();
  42425. }
  42426. this._out[0] = out.x;
  42427. this._out[1] = out.y;
  42428. this._out[2] = out.z;
  42429. this._out[3] = out.w;
  42430. return this._out;
  42431. }
  42432. }, {
  42433. key: '_onSensorError',
  42434. value: function _onSensorError(event) {
  42435. this.errors.push(event.error);
  42436. if (event.error.name === 'NotAllowedError') {
  42437. console.error('Permission to access sensor was denied');
  42438. } else if (event.error.name === 'NotReadableError') {
  42439. console.error('Sensor could not be read');
  42440. } else {
  42441. console.error(event.error);
  42442. }
  42443. this.useDeviceMotion();
  42444. }
  42445. }, {
  42446. key: '_onSensorRead',
  42447. value: function _onSensorRead() {}
  42448. }]);
  42449. return PoseSensor;
  42450. }();
  42451. 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>";
  42452. function RotateInstructions() {
  42453. this.loadIcon_();
  42454. var overlay = document.createElement('div');
  42455. var s = overlay.style;
  42456. s.position = 'fixed';
  42457. s.top = 0;
  42458. s.right = 0;
  42459. s.bottom = 0;
  42460. s.left = 0;
  42461. s.backgroundColor = 'gray';
  42462. s.fontFamily = 'sans-serif';
  42463. s.zIndex = 1000000;
  42464. var img = document.createElement('img');
  42465. img.src = this.icon;
  42466. var s = img.style;
  42467. s.marginLeft = '25%';
  42468. s.marginTop = '25%';
  42469. s.width = '50%';
  42470. overlay.appendChild(img);
  42471. var text = document.createElement('div');
  42472. var s = text.style;
  42473. s.textAlign = 'center';
  42474. s.fontSize = '16px';
  42475. s.lineHeight = '24px';
  42476. s.margin = '24px 25%';
  42477. s.width = '50%';
  42478. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  42479. overlay.appendChild(text);
  42480. var snackbar = document.createElement('div');
  42481. var s = snackbar.style;
  42482. s.backgroundColor = '#CFD8DC';
  42483. s.position = 'fixed';
  42484. s.bottom = 0;
  42485. s.width = '100%';
  42486. s.height = '48px';
  42487. s.padding = '14px 24px';
  42488. s.boxSizing = 'border-box';
  42489. s.color = '#656A6B';
  42490. overlay.appendChild(snackbar);
  42491. var snackbarText = document.createElement('div');
  42492. snackbarText.style.float = 'left';
  42493. snackbarText.innerHTML = 'No Cardboard viewer?';
  42494. var snackbarButton = document.createElement('a');
  42495. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  42496. snackbarButton.innerHTML = 'get one';
  42497. snackbarButton.target = '_blank';
  42498. var s = snackbarButton.style;
  42499. s.float = 'right';
  42500. s.fontWeight = 600;
  42501. s.textTransform = 'uppercase';
  42502. s.borderLeft = '1px solid gray';
  42503. s.paddingLeft = '24px';
  42504. s.textDecoration = 'none';
  42505. s.color = '#656A6B';
  42506. snackbar.appendChild(snackbarText);
  42507. snackbar.appendChild(snackbarButton);
  42508. this.overlay = overlay;
  42509. this.text = text;
  42510. this.hide();
  42511. }
  42512. RotateInstructions.prototype.show = function (parent) {
  42513. if (!parent && !this.overlay.parentElement) {
  42514. document.body.appendChild(this.overlay);
  42515. } else if (parent) {
  42516. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  42517. parent.appendChild(this.overlay);
  42518. }
  42519. this.overlay.style.display = 'block';
  42520. var img = this.overlay.querySelector('img');
  42521. var s = img.style;
  42522. if (isLandscapeMode()) {
  42523. s.width = '20%';
  42524. s.marginLeft = '40%';
  42525. s.marginTop = '3%';
  42526. } else {
  42527. s.width = '50%';
  42528. s.marginLeft = '25%';
  42529. s.marginTop = '25%';
  42530. }
  42531. };
  42532. RotateInstructions.prototype.hide = function () {
  42533. this.overlay.style.display = 'none';
  42534. };
  42535. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  42536. this.show(parent);
  42537. this.timer = setTimeout(this.hide.bind(this), ms);
  42538. };
  42539. RotateInstructions.prototype.disableShowTemporarily = function () {
  42540. clearTimeout(this.timer);
  42541. };
  42542. RotateInstructions.prototype.update = function () {
  42543. this.disableShowTemporarily();
  42544. if (!isLandscapeMode() && isMobile()) {
  42545. this.show();
  42546. } else {
  42547. this.hide();
  42548. }
  42549. };
  42550. RotateInstructions.prototype.loadIcon_ = function () {
  42551. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  42552. };
  42553. var DEFAULT_VIEWER = 'CardboardV1';
  42554. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  42555. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  42556. function ViewerSelector(defaultViewer) {
  42557. try {
  42558. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  42559. } catch (error) {
  42560. console.error('Failed to load viewer profile: %s', error);
  42561. }
  42562. if (!this.selectedKey) {
  42563. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  42564. }
  42565. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  42566. this.root = null;
  42567. this.onChangeCallbacks_ = [];
  42568. }
  42569. ViewerSelector.prototype.show = function (root) {
  42570. this.root = root;
  42571. root.appendChild(this.dialog);
  42572. var selected = this.dialog.querySelector('#' + this.selectedKey);
  42573. selected.checked = true;
  42574. this.dialog.style.display = 'block';
  42575. };
  42576. ViewerSelector.prototype.hide = function () {
  42577. if (this.root && this.root.contains(this.dialog)) {
  42578. this.root.removeChild(this.dialog);
  42579. }
  42580. this.dialog.style.display = 'none';
  42581. };
  42582. ViewerSelector.prototype.getCurrentViewer = function () {
  42583. return DeviceInfo.Viewers[this.selectedKey];
  42584. };
  42585. ViewerSelector.prototype.getSelectedKey_ = function () {
  42586. var input = this.dialog.querySelector('input[name=field]:checked');
  42587. if (input) {
  42588. return input.id;
  42589. }
  42590. return null;
  42591. };
  42592. ViewerSelector.prototype.onChange = function (cb) {
  42593. this.onChangeCallbacks_.push(cb);
  42594. };
  42595. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  42596. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  42597. this.onChangeCallbacks_[i](viewer);
  42598. }
  42599. };
  42600. ViewerSelector.prototype.onSave_ = function () {
  42601. this.selectedKey = this.getSelectedKey_();
  42602. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42603. console.error('ViewerSelector.onSave_: this should never happen!');
  42604. return;
  42605. }
  42606. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  42607. try {
  42608. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42609. } catch (error) {
  42610. console.error('Failed to save viewer profile: %s', error);
  42611. }
  42612. this.hide();
  42613. };
  42614. ViewerSelector.prototype.createDialog_ = function (options) {
  42615. var container = document.createElement('div');
  42616. container.classList.add(CLASS_NAME);
  42617. container.style.display = 'none';
  42618. var overlay = document.createElement('div');
  42619. var s = overlay.style;
  42620. s.position = 'fixed';
  42621. s.left = 0;
  42622. s.top = 0;
  42623. s.width = '100%';
  42624. s.height = '100%';
  42625. s.background = 'rgba(0, 0, 0, 0.3)';
  42626. overlay.addEventListener('click', this.hide.bind(this));
  42627. var width = 280;
  42628. var dialog = document.createElement('div');
  42629. var s = dialog.style;
  42630. s.boxSizing = 'border-box';
  42631. s.position = 'fixed';
  42632. s.top = '24px';
  42633. s.left = '50%';
  42634. s.marginLeft = -width / 2 + 'px';
  42635. s.width = width + 'px';
  42636. s.padding = '24px';
  42637. s.overflow = 'hidden';
  42638. s.background = '#fafafa';
  42639. s.fontFamily = "'Roboto', sans-serif";
  42640. s.boxShadow = '0px 5px 20px #666';
  42641. dialog.appendChild(this.createH1_('Select your viewer'));
  42642. for (var id in options) {
  42643. dialog.appendChild(this.createChoice_(id, options[id].label));
  42644. }
  42645. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42646. container.appendChild(overlay);
  42647. container.appendChild(dialog);
  42648. return container;
  42649. };
  42650. ViewerSelector.prototype.createH1_ = function (name) {
  42651. var h1 = document.createElement('h1');
  42652. var s = h1.style;
  42653. s.color = 'black';
  42654. s.fontSize = '20px';
  42655. s.fontWeight = 'bold';
  42656. s.marginTop = 0;
  42657. s.marginBottom = '24px';
  42658. h1.innerHTML = name;
  42659. return h1;
  42660. };
  42661. ViewerSelector.prototype.createChoice_ = function (id, name) {
  42662. var div = document.createElement('div');
  42663. div.style.marginTop = '8px';
  42664. div.style.color = 'black';
  42665. var input = document.createElement('input');
  42666. input.style.fontSize = '30px';
  42667. input.setAttribute('id', id);
  42668. input.setAttribute('type', 'radio');
  42669. input.setAttribute('value', id);
  42670. input.setAttribute('name', 'field');
  42671. var label = document.createElement('label');
  42672. label.style.marginLeft = '4px';
  42673. label.setAttribute('for', id);
  42674. label.innerHTML = name;
  42675. div.appendChild(input);
  42676. div.appendChild(label);
  42677. return div;
  42678. };
  42679. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  42680. var button = document.createElement('button');
  42681. button.innerHTML = label;
  42682. var s = button.style;
  42683. s.float = 'right';
  42684. s.textTransform = 'uppercase';
  42685. s.color = '#1094f7';
  42686. s.fontSize = '14px';
  42687. s.letterSpacing = 0;
  42688. s.border = 0;
  42689. s.background = 'none';
  42690. s.marginTop = '16px';
  42691. button.addEventListener('click', onclick);
  42692. return button;
  42693. };
  42694. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  42695. function unwrapExports$$1 (x) {
  42696. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  42697. }
  42698. function createCommonjsModule$$1(fn, module) {
  42699. return module = { exports: {} }, fn(module, module.exports), module.exports;
  42700. }
  42701. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  42702. (function webpackUniversalModuleDefinition(root, factory) {
  42703. module.exports = factory();
  42704. })(commonjsGlobal$$1, function() {
  42705. return (function(modules) {
  42706. var installedModules = {};
  42707. function __webpack_require__(moduleId) {
  42708. if(installedModules[moduleId]) {
  42709. return installedModules[moduleId].exports;
  42710. }
  42711. var module = installedModules[moduleId] = {
  42712. i: moduleId,
  42713. l: false,
  42714. exports: {}
  42715. };
  42716. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  42717. module.l = true;
  42718. return module.exports;
  42719. }
  42720. __webpack_require__.m = modules;
  42721. __webpack_require__.c = installedModules;
  42722. __webpack_require__.d = function(exports, name, getter) {
  42723. if(!__webpack_require__.o(exports, name)) {
  42724. Object.defineProperty(exports, name, {
  42725. configurable: false,
  42726. enumerable: true,
  42727. get: getter
  42728. });
  42729. }
  42730. };
  42731. __webpack_require__.n = function(module) {
  42732. var getter = module && module.__esModule ?
  42733. function getDefault() { return module['default']; } :
  42734. function getModuleExports() { return module; };
  42735. __webpack_require__.d(getter, 'a', getter);
  42736. return getter;
  42737. };
  42738. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  42739. __webpack_require__.p = "";
  42740. return __webpack_require__(__webpack_require__.s = 0);
  42741. })
  42742. ([
  42743. (function(module, exports, __webpack_require__) {
  42744. 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; }; }();
  42745. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  42746. var mediaFile = __webpack_require__(1);
  42747. 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;
  42748. var NoSleep = function () {
  42749. function NoSleep() {
  42750. _classCallCheck(this, NoSleep);
  42751. if (oldIOS) {
  42752. this.noSleepTimer = null;
  42753. } else {
  42754. this.noSleepVideo = document.createElement('video');
  42755. this.noSleepVideo.setAttribute('playsinline', '');
  42756. this.noSleepVideo.setAttribute('src', mediaFile);
  42757. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  42758. if (this.noSleepVideo.currentTime > 0.5) {
  42759. this.noSleepVideo.currentTime = Math.random();
  42760. }
  42761. }.bind(this));
  42762. }
  42763. }
  42764. _createClass(NoSleep, [{
  42765. key: 'enable',
  42766. value: function enable() {
  42767. if (oldIOS) {
  42768. this.disable();
  42769. this.noSleepTimer = window.setInterval(function () {
  42770. window.location.href = '/';
  42771. window.setTimeout(window.stop, 0);
  42772. }, 15000);
  42773. } else {
  42774. this.noSleepVideo.play();
  42775. }
  42776. }
  42777. }, {
  42778. key: 'disable',
  42779. value: function disable() {
  42780. if (oldIOS) {
  42781. if (this.noSleepTimer) {
  42782. window.clearInterval(this.noSleepTimer);
  42783. this.noSleepTimer = null;
  42784. }
  42785. } else {
  42786. this.noSleepVideo.pause();
  42787. }
  42788. }
  42789. }]);
  42790. return NoSleep;
  42791. }();
  42792. module.exports = NoSleep;
  42793. }),
  42794. (function(module, exports, __webpack_require__) {
  42795. 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=';
  42796. })
  42797. ]);
  42798. });
  42799. });
  42800. var NoSleep$1 = unwrapExports$$1(NoSleep);
  42801. var nextDisplayId = 1000;
  42802. var defaultLeftBounds = [0, 0, 0.5, 1];
  42803. var defaultRightBounds = [0.5, 0, 0.5, 1];
  42804. var raf = window.requestAnimationFrame;
  42805. var caf = window.cancelAnimationFrame;
  42806. function VRFrameData() {
  42807. this.leftProjectionMatrix = new Float32Array(16);
  42808. this.leftViewMatrix = new Float32Array(16);
  42809. this.rightProjectionMatrix = new Float32Array(16);
  42810. this.rightViewMatrix = new Float32Array(16);
  42811. this.pose = null;
  42812. }
  42813. function VRDisplayCapabilities(config) {
  42814. Object.defineProperties(this, {
  42815. hasPosition: {
  42816. writable: false, enumerable: true, value: config.hasPosition
  42817. },
  42818. hasExternalDisplay: {
  42819. writable: false, enumerable: true, value: config.hasExternalDisplay
  42820. },
  42821. canPresent: {
  42822. writable: false, enumerable: true, value: config.canPresent
  42823. },
  42824. maxLayers: {
  42825. writable: false, enumerable: true, value: config.maxLayers
  42826. },
  42827. hasOrientation: {
  42828. enumerable: true, get: function get() {
  42829. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  42830. return config.hasOrientation;
  42831. }
  42832. }
  42833. });
  42834. }
  42835. function VRDisplay(config) {
  42836. config = config || {};
  42837. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  42838. this.isPolyfilled = true;
  42839. this.displayId = nextDisplayId++;
  42840. this.displayName = '';
  42841. this.depthNear = 0.01;
  42842. this.depthFar = 10000.0;
  42843. this.isPresenting = false;
  42844. Object.defineProperty(this, 'isConnected', {
  42845. get: function get() {
  42846. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  42847. return false;
  42848. }
  42849. });
  42850. this.capabilities = new VRDisplayCapabilities({
  42851. hasPosition: false,
  42852. hasOrientation: false,
  42853. hasExternalDisplay: false,
  42854. canPresent: false,
  42855. maxLayers: 1
  42856. });
  42857. this.stageParameters = null;
  42858. this.waitingForPresent_ = false;
  42859. this.layer_ = null;
  42860. this.originalParent_ = null;
  42861. this.fullscreenElement_ = null;
  42862. this.fullscreenWrapper_ = null;
  42863. this.fullscreenElementCachedStyle_ = null;
  42864. this.fullscreenEventTarget_ = null;
  42865. this.fullscreenChangeHandler_ = null;
  42866. this.fullscreenErrorHandler_ = null;
  42867. if (USE_WAKELOCK && isMobile()) {
  42868. this.wakelock_ = new NoSleep$1();
  42869. }
  42870. }
  42871. VRDisplay.prototype.getFrameData = function (frameData) {
  42872. return frameDataFromPose(frameData, this._getPose(), this);
  42873. };
  42874. VRDisplay.prototype.getPose = function () {
  42875. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  42876. return this._getPose();
  42877. };
  42878. VRDisplay.prototype.resetPose = function () {
  42879. deprecateWarning('VRDisplay.prototype.resetPose');
  42880. return this._resetPose();
  42881. };
  42882. VRDisplay.prototype.getImmediatePose = function () {
  42883. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  42884. return this._getPose();
  42885. };
  42886. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  42887. return raf(callback);
  42888. };
  42889. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  42890. return caf(id);
  42891. };
  42892. VRDisplay.prototype.wrapForFullscreen = function (element) {
  42893. if (isIOS()) {
  42894. return element;
  42895. }
  42896. if (!this.fullscreenWrapper_) {
  42897. this.fullscreenWrapper_ = document.createElement('div');
  42898. 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'];
  42899. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  42900. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  42901. }
  42902. if (this.fullscreenElement_ == element) {
  42903. return this.fullscreenWrapper_;
  42904. }
  42905. if (this.fullscreenElement_) {
  42906. if (this.originalParent_) {
  42907. this.originalParent_.appendChild(this.fullscreenElement_);
  42908. } else {
  42909. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  42910. }
  42911. }
  42912. this.fullscreenElement_ = element;
  42913. this.originalParent_ = element.parentElement;
  42914. if (!this.originalParent_) {
  42915. document.body.appendChild(element);
  42916. }
  42917. if (!this.fullscreenWrapper_.parentElement) {
  42918. var parent = this.fullscreenElement_.parentElement;
  42919. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  42920. parent.removeChild(this.fullscreenElement_);
  42921. }
  42922. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  42923. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  42924. var self = this;
  42925. function applyFullscreenElementStyle() {
  42926. if (!self.fullscreenElement_) {
  42927. return;
  42928. }
  42929. 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'];
  42930. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  42931. }
  42932. applyFullscreenElementStyle();
  42933. return this.fullscreenWrapper_;
  42934. };
  42935. VRDisplay.prototype.removeFullscreenWrapper = function () {
  42936. if (!this.fullscreenElement_) {
  42937. return;
  42938. }
  42939. var element = this.fullscreenElement_;
  42940. if (this.fullscreenElementCachedStyle_) {
  42941. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  42942. } else {
  42943. element.removeAttribute('style');
  42944. }
  42945. this.fullscreenElement_ = null;
  42946. this.fullscreenElementCachedStyle_ = null;
  42947. var parent = this.fullscreenWrapper_.parentElement;
  42948. this.fullscreenWrapper_.removeChild(element);
  42949. if (this.originalParent_ === parent) {
  42950. parent.insertBefore(element, this.fullscreenWrapper_);
  42951. }
  42952. else if (this.originalParent_) {
  42953. this.originalParent_.appendChild(element);
  42954. }
  42955. parent.removeChild(this.fullscreenWrapper_);
  42956. return element;
  42957. };
  42958. VRDisplay.prototype.requestPresent = function (layers) {
  42959. var wasPresenting = this.isPresenting;
  42960. var self = this;
  42961. if (!(layers instanceof Array)) {
  42962. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  42963. layers = [layers];
  42964. }
  42965. return new Promise(function (resolve, reject) {
  42966. if (!self.capabilities.canPresent) {
  42967. reject(new Error('VRDisplay is not capable of presenting.'));
  42968. return;
  42969. }
  42970. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  42971. reject(new Error('Invalid number of layers.'));
  42972. return;
  42973. }
  42974. var incomingLayer = layers[0];
  42975. if (!incomingLayer.source) {
  42976. resolve();
  42977. return;
  42978. }
  42979. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  42980. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  42981. if (wasPresenting) {
  42982. var layer = self.layer_;
  42983. if (layer.source !== incomingLayer.source) {
  42984. layer.source = incomingLayer.source;
  42985. }
  42986. for (var i = 0; i < 4; i++) {
  42987. layer.leftBounds[i] = leftBounds[i];
  42988. layer.rightBounds[i] = rightBounds[i];
  42989. }
  42990. self.wrapForFullscreen(self.layer_.source);
  42991. self.updatePresent_();
  42992. resolve();
  42993. return;
  42994. }
  42995. self.layer_ = {
  42996. predistorted: incomingLayer.predistorted,
  42997. source: incomingLayer.source,
  42998. leftBounds: leftBounds.slice(0),
  42999. rightBounds: rightBounds.slice(0)
  43000. };
  43001. self.waitingForPresent_ = false;
  43002. if (self.layer_ && self.layer_.source) {
  43003. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  43004. var onFullscreenChange = function onFullscreenChange() {
  43005. var actualFullscreenElement = getFullscreenElement();
  43006. self.isPresenting = fullscreenElement === actualFullscreenElement;
  43007. if (self.isPresenting) {
  43008. if (screen.orientation && screen.orientation.lock) {
  43009. screen.orientation.lock('landscape-primary').catch(function (error) {
  43010. console.error('screen.orientation.lock() failed due to', error.message);
  43011. });
  43012. }
  43013. self.waitingForPresent_ = false;
  43014. self.beginPresent_();
  43015. resolve();
  43016. } else {
  43017. if (screen.orientation && screen.orientation.unlock) {
  43018. screen.orientation.unlock();
  43019. }
  43020. self.removeFullscreenWrapper();
  43021. self.disableWakeLock();
  43022. self.endPresent_();
  43023. self.removeFullscreenListeners_();
  43024. }
  43025. self.fireVRDisplayPresentChange_();
  43026. };
  43027. var onFullscreenError = function onFullscreenError() {
  43028. if (!self.waitingForPresent_) {
  43029. return;
  43030. }
  43031. self.removeFullscreenWrapper();
  43032. self.removeFullscreenListeners_();
  43033. self.disableWakeLock();
  43034. self.waitingForPresent_ = false;
  43035. self.isPresenting = false;
  43036. reject(new Error('Unable to present.'));
  43037. };
  43038. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  43039. if (requestFullscreen(fullscreenElement)) {
  43040. self.enableWakeLock();
  43041. self.waitingForPresent_ = true;
  43042. } else if (isIOS() || isWebViewAndroid()) {
  43043. self.enableWakeLock();
  43044. self.isPresenting = true;
  43045. self.beginPresent_();
  43046. self.fireVRDisplayPresentChange_();
  43047. resolve();
  43048. }
  43049. }
  43050. if (!self.waitingForPresent_ && !isIOS()) {
  43051. exitFullscreen();
  43052. reject(new Error('Unable to present.'));
  43053. }
  43054. });
  43055. };
  43056. VRDisplay.prototype.exitPresent = function () {
  43057. var wasPresenting = this.isPresenting;
  43058. var self = this;
  43059. this.isPresenting = false;
  43060. this.layer_ = null;
  43061. this.disableWakeLock();
  43062. return new Promise(function (resolve, reject) {
  43063. if (wasPresenting) {
  43064. if (!exitFullscreen() && isIOS()) {
  43065. self.endPresent_();
  43066. self.fireVRDisplayPresentChange_();
  43067. }
  43068. if (isWebViewAndroid()) {
  43069. self.removeFullscreenWrapper();
  43070. self.removeFullscreenListeners_();
  43071. self.endPresent_();
  43072. self.fireVRDisplayPresentChange_();
  43073. }
  43074. resolve();
  43075. } else {
  43076. reject(new Error('Was not presenting to VRDisplay.'));
  43077. }
  43078. });
  43079. };
  43080. VRDisplay.prototype.getLayers = function () {
  43081. if (this.layer_) {
  43082. return [this.layer_];
  43083. }
  43084. return [];
  43085. };
  43086. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  43087. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  43088. window.dispatchEvent(event);
  43089. };
  43090. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  43091. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  43092. window.dispatchEvent(event);
  43093. };
  43094. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  43095. this.removeFullscreenListeners_();
  43096. this.fullscreenEventTarget_ = element;
  43097. this.fullscreenChangeHandler_ = changeHandler;
  43098. this.fullscreenErrorHandler_ = errorHandler;
  43099. if (changeHandler) {
  43100. if (document.fullscreenEnabled) {
  43101. element.addEventListener('fullscreenchange', changeHandler, false);
  43102. } else if (document.webkitFullscreenEnabled) {
  43103. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  43104. } else if (document.mozFullScreenEnabled) {
  43105. document.addEventListener('mozfullscreenchange', changeHandler, false);
  43106. } else if (document.msFullscreenEnabled) {
  43107. element.addEventListener('msfullscreenchange', changeHandler, false);
  43108. }
  43109. }
  43110. if (errorHandler) {
  43111. if (document.fullscreenEnabled) {
  43112. element.addEventListener('fullscreenerror', errorHandler, false);
  43113. } else if (document.webkitFullscreenEnabled) {
  43114. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  43115. } else if (document.mozFullScreenEnabled) {
  43116. document.addEventListener('mozfullscreenerror', errorHandler, false);
  43117. } else if (document.msFullscreenEnabled) {
  43118. element.addEventListener('msfullscreenerror', errorHandler, false);
  43119. }
  43120. }
  43121. };
  43122. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  43123. if (!this.fullscreenEventTarget_) return;
  43124. var element = this.fullscreenEventTarget_;
  43125. if (this.fullscreenChangeHandler_) {
  43126. var changeHandler = this.fullscreenChangeHandler_;
  43127. element.removeEventListener('fullscreenchange', changeHandler, false);
  43128. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  43129. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  43130. element.removeEventListener('msfullscreenchange', changeHandler, false);
  43131. }
  43132. if (this.fullscreenErrorHandler_) {
  43133. var errorHandler = this.fullscreenErrorHandler_;
  43134. element.removeEventListener('fullscreenerror', errorHandler, false);
  43135. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  43136. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  43137. element.removeEventListener('msfullscreenerror', errorHandler, false);
  43138. }
  43139. this.fullscreenEventTarget_ = null;
  43140. this.fullscreenChangeHandler_ = null;
  43141. this.fullscreenErrorHandler_ = null;
  43142. };
  43143. VRDisplay.prototype.enableWakeLock = function () {
  43144. if (this.wakelock_) {
  43145. this.wakelock_.enable();
  43146. }
  43147. };
  43148. VRDisplay.prototype.disableWakeLock = function () {
  43149. if (this.wakelock_) {
  43150. this.wakelock_.disable();
  43151. }
  43152. };
  43153. VRDisplay.prototype.beginPresent_ = function () {
  43154. };
  43155. VRDisplay.prototype.endPresent_ = function () {
  43156. };
  43157. VRDisplay.prototype.submitFrame = function (pose) {
  43158. };
  43159. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  43160. return null;
  43161. };
  43162. var config = {
  43163. ADDITIONAL_VIEWERS: [],
  43164. DEFAULT_VIEWER: '',
  43165. MOBILE_WAKE_LOCK: true,
  43166. DEBUG: false,
  43167. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43168. K_FILTER: 0.98,
  43169. PREDICTION_TIME_S: 0.040,
  43170. CARDBOARD_UI_DISABLED: false,
  43171. ROTATE_INSTRUCTIONS_DISABLED: false,
  43172. YAW_ONLY: false,
  43173. BUFFER_SCALE: 0.5,
  43174. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43175. };
  43176. var Eye = {
  43177. LEFT: 'left',
  43178. RIGHT: 'right'
  43179. };
  43180. function CardboardVRDisplay(config$$1) {
  43181. var defaults = extend({}, config);
  43182. config$$1 = extend(defaults, config$$1 || {});
  43183. VRDisplay.call(this, {
  43184. wakelock: config$$1.MOBILE_WAKE_LOCK
  43185. });
  43186. this.config = config$$1;
  43187. this.displayName = 'Cardboard VRDisplay';
  43188. this.capabilities = new VRDisplayCapabilities({
  43189. hasPosition: false,
  43190. hasOrientation: true,
  43191. hasExternalDisplay: false,
  43192. canPresent: true,
  43193. maxLayers: 1
  43194. });
  43195. this.stageParameters = null;
  43196. this.bufferScale_ = this.config.BUFFER_SCALE;
  43197. this.poseSensor_ = new PoseSensor(this.config);
  43198. this.distorter_ = null;
  43199. this.cardboardUI_ = null;
  43200. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  43201. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  43202. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  43203. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  43204. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  43205. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  43206. this.rotateInstructions_ = new RotateInstructions();
  43207. }
  43208. if (isIOS()) {
  43209. window.addEventListener('resize', this.onResize_.bind(this));
  43210. }
  43211. }
  43212. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  43213. CardboardVRDisplay.prototype._getPose = function () {
  43214. return {
  43215. position: null,
  43216. orientation: this.poseSensor_.getOrientation(),
  43217. linearVelocity: null,
  43218. linearAcceleration: null,
  43219. angularVelocity: null,
  43220. angularAcceleration: null
  43221. };
  43222. };
  43223. CardboardVRDisplay.prototype._resetPose = function () {
  43224. if (this.poseSensor_.resetPose) {
  43225. this.poseSensor_.resetPose();
  43226. }
  43227. };
  43228. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  43229. var fieldOfView;
  43230. if (whichEye == Eye.LEFT) {
  43231. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  43232. } else if (whichEye == Eye.RIGHT) {
  43233. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  43234. } else {
  43235. console.error('Invalid eye provided: %s', whichEye);
  43236. return null;
  43237. }
  43238. return fieldOfView;
  43239. };
  43240. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  43241. var offset;
  43242. if (whichEye == Eye.LEFT) {
  43243. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43244. } else if (whichEye == Eye.RIGHT) {
  43245. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43246. } else {
  43247. console.error('Invalid eye provided: %s', whichEye);
  43248. return null;
  43249. }
  43250. return offset;
  43251. };
  43252. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  43253. var offset = this._getEyeOffset(whichEye);
  43254. var fieldOfView = this._getFieldOfView(whichEye);
  43255. var eyeParams = {
  43256. offset: offset,
  43257. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  43258. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  43259. };
  43260. Object.defineProperty(eyeParams, 'fieldOfView', {
  43261. enumerable: true,
  43262. get: function get() {
  43263. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  43264. return fieldOfView;
  43265. }
  43266. });
  43267. return eyeParams;
  43268. };
  43269. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  43270. if (this.config.DEBUG) {
  43271. console.log('DPDB reported that device params were updated.');
  43272. }
  43273. this.deviceInfo_.updateDeviceParams(newParams);
  43274. if (this.distorter_) {
  43275. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43276. }
  43277. };
  43278. CardboardVRDisplay.prototype.updateBounds_ = function () {
  43279. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  43280. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  43281. }
  43282. };
  43283. CardboardVRDisplay.prototype.beginPresent_ = function () {
  43284. var gl = this.layer_.source.getContext('webgl');
  43285. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43286. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43287. if (!gl) return;
  43288. if (this.layer_.predistorted) {
  43289. if (!this.config.CARDBOARD_UI_DISABLED) {
  43290. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  43291. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  43292. this.cardboardUI_ = new CardboardUI(gl);
  43293. }
  43294. } else {
  43295. if (!this.config.CARDBOARD_UI_DISABLED) {
  43296. this.cardboardUI_ = new CardboardUI(gl);
  43297. }
  43298. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  43299. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43300. }
  43301. if (this.cardboardUI_) {
  43302. this.cardboardUI_.listen(function (e) {
  43303. this.viewerSelector_.show(this.layer_.source.parentElement);
  43304. e.stopPropagation();
  43305. e.preventDefault();
  43306. }.bind(this), function (e) {
  43307. this.exitPresent();
  43308. e.stopPropagation();
  43309. e.preventDefault();
  43310. }.bind(this));
  43311. }
  43312. if (this.rotateInstructions_) {
  43313. if (isLandscapeMode() && isMobile()) {
  43314. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  43315. } else {
  43316. this.rotateInstructions_.update();
  43317. }
  43318. }
  43319. this.orientationHandler = this.onOrientationChange_.bind(this);
  43320. window.addEventListener('orientationchange', this.orientationHandler);
  43321. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  43322. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43323. this.fireVRDisplayDeviceParamsChange_();
  43324. };
  43325. CardboardVRDisplay.prototype.endPresent_ = function () {
  43326. if (this.distorter_) {
  43327. this.distorter_.destroy();
  43328. this.distorter_ = null;
  43329. }
  43330. if (this.cardboardUI_) {
  43331. this.cardboardUI_.destroy();
  43332. this.cardboardUI_ = null;
  43333. }
  43334. if (this.rotateInstructions_) {
  43335. this.rotateInstructions_.hide();
  43336. }
  43337. this.viewerSelector_.hide();
  43338. window.removeEventListener('orientationchange', this.orientationHandler);
  43339. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43340. };
  43341. CardboardVRDisplay.prototype.updatePresent_ = function () {
  43342. this.endPresent_();
  43343. this.beginPresent_();
  43344. };
  43345. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  43346. if (this.distorter_) {
  43347. this.updateBounds_();
  43348. this.distorter_.submitFrame();
  43349. } else if (this.cardboardUI_ && this.layer_) {
  43350. var gl = this.layer_.source.getContext('webgl');
  43351. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43352. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43353. var canvas = gl.canvas;
  43354. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  43355. this.cardboardUI_.onResize();
  43356. }
  43357. this.lastWidth = canvas.width;
  43358. this.lastHeight = canvas.height;
  43359. this.cardboardUI_.render();
  43360. }
  43361. };
  43362. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  43363. this.viewerSelector_.hide();
  43364. if (this.rotateInstructions_) {
  43365. this.rotateInstructions_.update();
  43366. }
  43367. this.onResize_();
  43368. };
  43369. CardboardVRDisplay.prototype.onResize_ = function (e) {
  43370. if (this.layer_) {
  43371. var gl = this.layer_.source.getContext('webgl');
  43372. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43373. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43374. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  43375. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  43376. 'padding: 0px', 'box-sizing: content-box'];
  43377. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  43378. safariCssSizeWorkaround(gl.canvas);
  43379. }
  43380. };
  43381. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  43382. this.deviceInfo_.setViewer(viewer);
  43383. if (this.distorter_) {
  43384. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43385. }
  43386. this.fireVRDisplayDeviceParamsChange_();
  43387. };
  43388. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  43389. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  43390. detail: {
  43391. vrdisplay: this,
  43392. deviceInfo: this.deviceInfo_
  43393. }
  43394. });
  43395. window.dispatchEvent(event);
  43396. };
  43397. CardboardVRDisplay.VRFrameData = VRFrameData;
  43398. CardboardVRDisplay.VRDisplay = VRDisplay;
  43399. return CardboardVRDisplay;
  43400. })));
  43401. });
  43402. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  43403. var version = "0.10.12";
  43404. var DefaultConfig = {
  43405. ADDITIONAL_VIEWERS: [],
  43406. DEFAULT_VIEWER: '',
  43407. PROVIDE_MOBILE_VRDISPLAY: true,
  43408. MOBILE_WAKE_LOCK: true,
  43409. DEBUG: false,
  43410. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43411. K_FILTER: 0.98,
  43412. PREDICTION_TIME_S: 0.040,
  43413. CARDBOARD_UI_DISABLED: false,
  43414. ROTATE_INSTRUCTIONS_DISABLED: false,
  43415. YAW_ONLY: false,
  43416. BUFFER_SCALE: 0.5,
  43417. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43418. };
  43419. function WebVRPolyfill(config) {
  43420. this.config = extend(extend({}, DefaultConfig), config);
  43421. this.polyfillDisplays = [];
  43422. this.enabled = false;
  43423. this.hasNative = 'getVRDisplays' in navigator;
  43424. this.native = {};
  43425. this.native.getVRDisplays = navigator.getVRDisplays;
  43426. this.native.VRFrameData = window.VRFrameData;
  43427. this.native.VRDisplay = window.VRDisplay;
  43428. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  43429. this.enable();
  43430. this.getVRDisplays().then(function (displays) {
  43431. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  43432. displays[0].fireVRDisplayConnect_();
  43433. }
  43434. });
  43435. }
  43436. }
  43437. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  43438. if (this._polyfillDisplaysPopulated) {
  43439. return this.polyfillDisplays;
  43440. }
  43441. if (isMobile()) {
  43442. var vrDisplay = new CardboardVRDisplay({
  43443. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  43444. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  43445. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  43446. DEBUG: this.config.DEBUG,
  43447. DPDB_URL: this.config.DPDB_URL,
  43448. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  43449. K_FILTER: this.config.K_FILTER,
  43450. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  43451. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  43452. YAW_ONLY: this.config.YAW_ONLY,
  43453. BUFFER_SCALE: this.config.BUFFER_SCALE,
  43454. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  43455. });
  43456. this.polyfillDisplays.push(vrDisplay);
  43457. }
  43458. this._polyfillDisplaysPopulated = true;
  43459. return this.polyfillDisplays;
  43460. };
  43461. WebVRPolyfill.prototype.enable = function () {
  43462. this.enabled = true;
  43463. if (this.hasNative && this.native.VRFrameData) {
  43464. var NativeVRFrameData = this.native.VRFrameData;
  43465. var nativeFrameData = new this.native.VRFrameData();
  43466. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  43467. window.VRDisplay.prototype.getFrameData = function (frameData) {
  43468. if (frameData instanceof NativeVRFrameData) {
  43469. nativeGetFrameData.call(this, frameData);
  43470. return;
  43471. }
  43472. nativeGetFrameData.call(this, nativeFrameData);
  43473. frameData.pose = nativeFrameData.pose;
  43474. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  43475. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  43476. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  43477. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  43478. };
  43479. }
  43480. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  43481. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  43482. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  43483. };
  43484. WebVRPolyfill.prototype.getVRDisplays = function () {
  43485. var _this = this;
  43486. var config = this.config;
  43487. if (!this.hasNative) {
  43488. return Promise.resolve(this.getPolyfillDisplays());
  43489. }
  43490. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  43491. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  43492. });
  43493. };
  43494. WebVRPolyfill.version = version;
  43495. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  43496. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  43497. var webvrPolyfill = Object.freeze({
  43498. default: WebVRPolyfill
  43499. });
  43500. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  43501. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  43502. if (!commonjsGlobal.document) {
  43503. commonjsGlobal.document = commonjsGlobal.window.document;
  43504. }
  43505. if (!commonjsGlobal.navigator) {
  43506. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  43507. }
  43508. }
  43509. var src = require$$0;
  43510. return src;
  43511. })));
  43512. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43513. },{}],70:[function(require,module,exports){
  43514. var newline = /\n/
  43515. var newlineChar = '\n'
  43516. var whitespace = /\s/
  43517. module.exports = function(text, opt) {
  43518. var lines = module.exports.lines(text, opt)
  43519. return lines.map(function(line) {
  43520. return text.substring(line.start, line.end)
  43521. }).join('\n')
  43522. }
  43523. module.exports.lines = function wordwrap(text, opt) {
  43524. opt = opt||{}
  43525. //zero width results in nothing visible
  43526. if (opt.width === 0 && opt.mode !== 'nowrap')
  43527. return []
  43528. text = text||''
  43529. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  43530. var start = Math.max(0, opt.start||0)
  43531. var end = typeof opt.end === 'number' ? opt.end : text.length
  43532. var mode = opt.mode
  43533. var measure = opt.measure || monospace
  43534. if (mode === 'pre')
  43535. return pre(measure, text, start, end, width)
  43536. else
  43537. return greedy(measure, text, start, end, width, mode)
  43538. }
  43539. function idxOf(text, chr, start, end) {
  43540. var idx = text.indexOf(chr, start)
  43541. if (idx === -1 || idx > end)
  43542. return end
  43543. return idx
  43544. }
  43545. function isWhitespace(chr) {
  43546. return whitespace.test(chr)
  43547. }
  43548. function pre(measure, text, start, end, width) {
  43549. var lines = []
  43550. var lineStart = start
  43551. for (var i=start; i<end && i<text.length; i++) {
  43552. var chr = text.charAt(i)
  43553. var isNewline = newline.test(chr)
  43554. //If we've reached a newline, then step down a line
  43555. //Or if we've reached the EOF
  43556. if (isNewline || i===end-1) {
  43557. var lineEnd = isNewline ? i : i+1
  43558. var measured = measure(text, lineStart, lineEnd, width)
  43559. lines.push(measured)
  43560. lineStart = i+1
  43561. }
  43562. }
  43563. return lines
  43564. }
  43565. function greedy(measure, text, start, end, width, mode) {
  43566. //A greedy word wrapper based on LibGDX algorithm
  43567. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  43568. var lines = []
  43569. var testWidth = width
  43570. //if 'nowrap' is specified, we only wrap on newline chars
  43571. if (mode === 'nowrap')
  43572. testWidth = Number.MAX_VALUE
  43573. while (start < end && start < text.length) {
  43574. //get next newline position
  43575. var newLine = idxOf(text, newlineChar, start, end)
  43576. //eat whitespace at start of line
  43577. while (start < newLine) {
  43578. if (!isWhitespace( text.charAt(start) ))
  43579. break
  43580. start++
  43581. }
  43582. //determine visible # of glyphs for the available width
  43583. var measured = measure(text, start, newLine, testWidth)
  43584. var lineEnd = start + (measured.end-measured.start)
  43585. var nextStart = lineEnd + newlineChar.length
  43586. //if we had to cut the line before the next newline...
  43587. if (lineEnd < newLine) {
  43588. //find char to break on
  43589. while (lineEnd > start) {
  43590. if (isWhitespace(text.charAt(lineEnd)))
  43591. break
  43592. lineEnd--
  43593. }
  43594. if (lineEnd === start) {
  43595. if (nextStart > start + newlineChar.length) nextStart--
  43596. lineEnd = nextStart // If no characters to break, show all.
  43597. } else {
  43598. nextStart = lineEnd
  43599. //eat whitespace at end of line
  43600. while (lineEnd > start) {
  43601. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  43602. break
  43603. lineEnd--
  43604. }
  43605. }
  43606. }
  43607. if (lineEnd >= start) {
  43608. var result = measure(text, start, lineEnd, testWidth)
  43609. lines.push(result)
  43610. }
  43611. start = nextStart
  43612. }
  43613. return lines
  43614. }
  43615. //determines the visible number of glyphs within a given width
  43616. function monospace(text, start, end, width) {
  43617. var glyphs = Math.min(width, end-start)
  43618. return {
  43619. start: start,
  43620. end: start+glyphs
  43621. }
  43622. }
  43623. },{}],71:[function(require,module,exports){
  43624. "use strict";
  43625. var window = require("global/window")
  43626. var isFunction = require("is-function")
  43627. var parseHeaders = require("parse-headers")
  43628. var xtend = require("xtend")
  43629. module.exports = createXHR
  43630. // Allow use of default import syntax in TypeScript
  43631. module.exports.default = createXHR;
  43632. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  43633. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  43634. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  43635. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  43636. options = initParams(uri, options, callback)
  43637. options.method = method.toUpperCase()
  43638. return _createXHR(options)
  43639. }
  43640. })
  43641. function forEachArray(array, iterator) {
  43642. for (var i = 0; i < array.length; i++) {
  43643. iterator(array[i])
  43644. }
  43645. }
  43646. function isEmpty(obj){
  43647. for(var i in obj){
  43648. if(obj.hasOwnProperty(i)) return false
  43649. }
  43650. return true
  43651. }
  43652. function initParams(uri, options, callback) {
  43653. var params = uri
  43654. if (isFunction(options)) {
  43655. callback = options
  43656. if (typeof uri === "string") {
  43657. params = {uri:uri}
  43658. }
  43659. } else {
  43660. params = xtend(options, {uri: uri})
  43661. }
  43662. params.callback = callback
  43663. return params
  43664. }
  43665. function createXHR(uri, options, callback) {
  43666. options = initParams(uri, options, callback)
  43667. return _createXHR(options)
  43668. }
  43669. function _createXHR(options) {
  43670. if(typeof options.callback === "undefined"){
  43671. throw new Error("callback argument missing")
  43672. }
  43673. var called = false
  43674. var callback = function cbOnce(err, response, body){
  43675. if(!called){
  43676. called = true
  43677. options.callback(err, response, body)
  43678. }
  43679. }
  43680. function readystatechange() {
  43681. if (xhr.readyState === 4) {
  43682. setTimeout(loadFunc, 0)
  43683. }
  43684. }
  43685. function getBody() {
  43686. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  43687. var body = undefined
  43688. if (xhr.response) {
  43689. body = xhr.response
  43690. } else {
  43691. body = xhr.responseText || getXml(xhr)
  43692. }
  43693. if (isJson) {
  43694. try {
  43695. body = JSON.parse(body)
  43696. } catch (e) {}
  43697. }
  43698. return body
  43699. }
  43700. function errorFunc(evt) {
  43701. clearTimeout(timeoutTimer)
  43702. if(!(evt instanceof Error)){
  43703. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  43704. }
  43705. evt.statusCode = 0
  43706. return callback(evt, failureResponse)
  43707. }
  43708. // will load the data & process the response in a special response object
  43709. function loadFunc() {
  43710. if (aborted) return
  43711. var status
  43712. clearTimeout(timeoutTimer)
  43713. if(options.useXDR && xhr.status===undefined) {
  43714. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  43715. status = 200
  43716. } else {
  43717. status = (xhr.status === 1223 ? 204 : xhr.status)
  43718. }
  43719. var response = failureResponse
  43720. var err = null
  43721. if (status !== 0){
  43722. response = {
  43723. body: getBody(),
  43724. statusCode: status,
  43725. method: method,
  43726. headers: {},
  43727. url: uri,
  43728. rawRequest: xhr
  43729. }
  43730. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  43731. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  43732. }
  43733. } else {
  43734. err = new Error("Internal XMLHttpRequest Error")
  43735. }
  43736. return callback(err, response, response.body)
  43737. }
  43738. var xhr = options.xhr || null
  43739. if (!xhr) {
  43740. if (options.cors || options.useXDR) {
  43741. xhr = new createXHR.XDomainRequest()
  43742. }else{
  43743. xhr = new createXHR.XMLHttpRequest()
  43744. }
  43745. }
  43746. var key
  43747. var aborted
  43748. var uri = xhr.url = options.uri || options.url
  43749. var method = xhr.method = options.method || "GET"
  43750. var body = options.body || options.data
  43751. var headers = xhr.headers = options.headers || {}
  43752. var sync = !!options.sync
  43753. var isJson = false
  43754. var timeoutTimer
  43755. var failureResponse = {
  43756. body: undefined,
  43757. headers: {},
  43758. statusCode: 0,
  43759. method: method,
  43760. url: uri,
  43761. rawRequest: xhr
  43762. }
  43763. if ("json" in options && options.json !== false) {
  43764. isJson = true
  43765. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  43766. if (method !== "GET" && method !== "HEAD") {
  43767. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  43768. body = JSON.stringify(options.json === true ? body : options.json)
  43769. }
  43770. }
  43771. xhr.onreadystatechange = readystatechange
  43772. xhr.onload = loadFunc
  43773. xhr.onerror = errorFunc
  43774. // IE9 must have onprogress be set to a unique function.
  43775. xhr.onprogress = function () {
  43776. // IE must die
  43777. }
  43778. xhr.onabort = function(){
  43779. aborted = true;
  43780. }
  43781. xhr.ontimeout = errorFunc
  43782. xhr.open(method, uri, !sync, options.username, options.password)
  43783. //has to be after open
  43784. if(!sync) {
  43785. xhr.withCredentials = !!options.withCredentials
  43786. }
  43787. // Cannot set timeout with sync request
  43788. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  43789. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  43790. if (!sync && options.timeout > 0 ) {
  43791. timeoutTimer = setTimeout(function(){
  43792. if (aborted) return
  43793. aborted = true//IE9 may still call readystatechange
  43794. xhr.abort("timeout")
  43795. var e = new Error("XMLHttpRequest timeout")
  43796. e.code = "ETIMEDOUT"
  43797. errorFunc(e)
  43798. }, options.timeout )
  43799. }
  43800. if (xhr.setRequestHeader) {
  43801. for(key in headers){
  43802. if(headers.hasOwnProperty(key)){
  43803. xhr.setRequestHeader(key, headers[key])
  43804. }
  43805. }
  43806. } else if (options.headers && !isEmpty(options.headers)) {
  43807. throw new Error("Headers cannot be set on an XDomainRequest object")
  43808. }
  43809. if ("responseType" in options) {
  43810. xhr.responseType = options.responseType
  43811. }
  43812. if ("beforeSend" in options &&
  43813. typeof options.beforeSend === "function"
  43814. ) {
  43815. options.beforeSend(xhr)
  43816. }
  43817. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  43818. // XMLHttpRequest spec says to pass null as body to indicate no body
  43819. // See https://github.com/naugtur/xhr/issues/100.
  43820. xhr.send(body || null)
  43821. return xhr
  43822. }
  43823. function getXml(xhr) {
  43824. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  43825. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  43826. try {
  43827. if (xhr.responseType === "document") {
  43828. return xhr.responseXML
  43829. }
  43830. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  43831. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  43832. return xhr.responseXML
  43833. }
  43834. } catch (e) {}
  43835. return null
  43836. }
  43837. function noop() {}
  43838. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":73}],72:[function(require,module,exports){
  43839. module.exports = (function xmlparser() {
  43840. //common browsers
  43841. if (typeof self.DOMParser !== 'undefined') {
  43842. return function(str) {
  43843. var parser = new self.DOMParser()
  43844. return parser.parseFromString(str, 'application/xml')
  43845. }
  43846. }
  43847. //IE8 fallback
  43848. if (typeof self.ActiveXObject !== 'undefined'
  43849. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  43850. return function(str) {
  43851. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  43852. xmlDoc.async = "false"
  43853. xmlDoc.loadXML(str)
  43854. return xmlDoc
  43855. }
  43856. }
  43857. //last resort fallback
  43858. return function(str) {
  43859. var div = document.createElement('div')
  43860. div.innerHTML = str
  43861. return div
  43862. }
  43863. })()
  43864. },{}],73:[function(require,module,exports){
  43865. module.exports = extend
  43866. var hasOwnProperty = Object.prototype.hasOwnProperty;
  43867. function extend() {
  43868. var target = {}
  43869. for (var i = 0; i < arguments.length; i++) {
  43870. var source = arguments[i]
  43871. for (var key in source) {
  43872. if (hasOwnProperty.call(source, key)) {
  43873. target[key] = source[key]
  43874. }
  43875. }
  43876. }
  43877. return target
  43878. }
  43879. },{}],74:[function(require,module,exports){
  43880. module.exports={
  43881. "name": "aframe",
  43882. "version": "1.2.0",
  43883. "description": "A web framework for building virtual reality experiences.",
  43884. "homepage": "https://aframe.io/",
  43885. "main": "dist/aframe-master.js",
  43886. "scripts": {
  43887. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  43888. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  43889. "codecov": "codecov",
  43890. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  43891. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  43892. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  43893. "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",
  43894. "docs": "markserv --dir docs --port 9001",
  43895. "preghpages": "node ./scripts/preghpages.js",
  43896. "ghpages": "ghpages -p gh-pages/",
  43897. "lint": "semistandard -v | snazzy",
  43898. "lint:fix": "semistandard --fix",
  43899. "precommit": "npm run lint",
  43900. "prepush": "node scripts/testOnlyCheck.js",
  43901. "prerelease": "node scripts/release.js 1.1.0 1.2.0",
  43902. "start": "npm run dev",
  43903. "start:https": "cross-env SSL=true npm run dev",
  43904. "test": "karma start ./tests/karma.conf.js",
  43905. "test:docs": "node scripts/docsLint.js",
  43906. "test:firefox": "npm test -- --browsers Firefox",
  43907. "test:chrome": "npm test -- --browsers Chrome",
  43908. "test:nobrowser": "NO_BROWSER=true npm test",
  43909. "test:node": "mocha --ui tdd tests/node"
  43910. },
  43911. "repository": "aframevr/aframe",
  43912. "license": "MIT",
  43913. "files": [
  43914. "dist/*",
  43915. "docs/**/*",
  43916. "src/**/*",
  43917. "vendor/**/*"
  43918. ],
  43919. "dependencies": {
  43920. "custom-event-polyfill": "^1.0.6",
  43921. "debug": "ngokevin/debug#noTimestamp",
  43922. "deep-assign": "^2.0.0",
  43923. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  43924. "load-bmfont": "^1.2.3",
  43925. "object-assign": "^4.0.1",
  43926. "present": "0.0.6",
  43927. "promise-polyfill": "^3.1.0",
  43928. "super-animejs": "^3.1.0",
  43929. "super-three": "^0.133.5",
  43930. "three-bmfont-text": "dmarcos/three-bmfont-text#21d017046216e318362c48abd1a48bddfb6e0733",
  43931. "webvr-polyfill": "^0.10.12"
  43932. },
  43933. "devDependencies": {
  43934. "browserify": "^13.1.0",
  43935. "browserify-css": "^0.8.4",
  43936. "browserify-derequire": "^0.9.4",
  43937. "browserify-istanbul": "^2.0.0",
  43938. "budo": "^9.2.0",
  43939. "chai": "^3.5.0",
  43940. "chai-shallow-deep-equal": "^1.4.0",
  43941. "chalk": "^1.1.3",
  43942. "codecov": "^1.0.1",
  43943. "cross-env": "^5.0.1",
  43944. "envify": "^3.4.1",
  43945. "exorcist": "^0.4.0",
  43946. "ghpages": "0.0.8",
  43947. "git-rev": "^0.2.1",
  43948. "glob": "^7.1.1",
  43949. "husky": "^0.11.7",
  43950. "istanbul": "^0.4.5",
  43951. "jsdom": "^9.11.0",
  43952. "karma": "1.4.1",
  43953. "karma-browserify": "^5.1.0",
  43954. "karma-chai-shallow-deep-equal": "0.0.4",
  43955. "karma-chrome-launcher": "^2.0.0",
  43956. "karma-coverage": "^1.1.1",
  43957. "karma-env-preprocessor": "^0.1.1",
  43958. "karma-firefox-launcher": "^1.2.0",
  43959. "karma-mocha": "^1.1.1",
  43960. "karma-mocha-reporter": "^2.1.0",
  43961. "karma-sinon-chai": "1.2.4",
  43962. "lolex": "^1.5.1",
  43963. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  43964. "minifyify": "^7.3.3",
  43965. "mocha": "^3.0.2",
  43966. "mozilla-download": "^1.1.1",
  43967. "replace-in-file": "^2.5.3",
  43968. "semistandard": "^9.0.0",
  43969. "shelljs": "^0.7.7",
  43970. "shx": "^0.2.2",
  43971. "sinon": "^1.17.5",
  43972. "sinon-chai": "2.8.0",
  43973. "snazzy": "^5.0.0",
  43974. "too-wordy": "ngokevin/too-wordy",
  43975. "uglifyjs": "^2.4.10",
  43976. "write-good": "^0.9.1"
  43977. },
  43978. "link": true,
  43979. "browserify": {
  43980. "transform": [
  43981. "browserify-css",
  43982. "envify"
  43983. ]
  43984. },
  43985. "semistandard": {
  43986. "ignore": [
  43987. "build/**",
  43988. "dist/**",
  43989. "examples/**/shaders/*.js",
  43990. "**/vendor/**"
  43991. ]
  43992. },
  43993. "keywords": [
  43994. "3d",
  43995. "aframe",
  43996. "cardboard",
  43997. "components",
  43998. "oculus",
  43999. "three",
  44000. "three.js",
  44001. "rift",
  44002. "vive",
  44003. "vr",
  44004. "web-components",
  44005. "webvr"
  44006. ],
  44007. "browserify-css": {
  44008. "minify": true
  44009. },
  44010. "engines": {
  44011. "node": ">= 4.6.0",
  44012. "npm": "^2.15.9"
  44013. }
  44014. }
  44015. },{}],75:[function(require,module,exports){
  44016. var anime = require('super-animejs');
  44017. var components = require('../core/component').components;
  44018. var registerComponent = require('../core/component').registerComponent;
  44019. var THREE = require('../lib/three');
  44020. var utils = require('../utils');
  44021. var colorHelperFrom = new THREE.Color();
  44022. var colorHelperTo = new THREE.Color();
  44023. var getComponentProperty = utils.entity.getComponentProperty;
  44024. var setComponentProperty = utils.entity.setComponentProperty;
  44025. var splitCache = {};
  44026. var TYPE_COLOR = 'color';
  44027. var PROP_POSITION = 'position';
  44028. var PROP_ROTATION = 'rotation';
  44029. var PROP_SCALE = 'scale';
  44030. var STRING_COMPONENTS = 'components';
  44031. var STRING_OBJECT3D = 'object3D';
  44032. /**
  44033. * Animation component for A-Frame using anime.js.
  44034. *
  44035. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  44036. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  44037. * boolean * flag * `isAnimationPlaying`.
  44038. *
  44039. * anime.js animation config for tweenining Javascript objects and values works as:
  44040. *
  44041. * config = {
  44042. * targets: {foo: 0.0, bar: '#000'},
  44043. * foo: 1.0,
  44044. * bar: '#FFF'
  44045. * }
  44046. *
  44047. * The above will tween each property in `targets`. The `to` values are set in the root of
  44048. * the config.
  44049. *
  44050. * @member {object} animation - anime.js instance.
  44051. * @member {boolean} animationIsPlaying - Control if animation is playing.
  44052. */
  44053. module.exports.Component = registerComponent('animation', {
  44054. schema: {
  44055. autoplay: {default: true},
  44056. delay: {default: 0},
  44057. dir: {default: ''},
  44058. dur: {default: 1000},
  44059. easing: {default: 'easeInQuad'},
  44060. elasticity: {default: 400},
  44061. enabled: {default: true},
  44062. from: {default: ''},
  44063. loop: {
  44064. default: 0,
  44065. parse: function (value) {
  44066. // Boolean or integer.
  44067. if (value === true || value === 'true') { return true; }
  44068. if (value === false || value === 'false') { return false; }
  44069. return parseInt(value, 10);
  44070. }
  44071. },
  44072. property: {default: ''},
  44073. startEvents: {type: 'array'},
  44074. pauseEvents: {type: 'array'},
  44075. resumeEvents: {type: 'array'},
  44076. round: {default: false},
  44077. to: {default: ''},
  44078. type: {default: ''},
  44079. isRawProperty: {default: false}
  44080. },
  44081. multiple: true,
  44082. init: function () {
  44083. var self = this;
  44084. this.eventDetail = {name: this.attrName};
  44085. this.time = 0;
  44086. this.animation = null;
  44087. this.animationIsPlaying = false;
  44088. this.onStartEvent = this.onStartEvent.bind(this);
  44089. this.beginAnimation = this.beginAnimation.bind(this);
  44090. this.pauseAnimation = this.pauseAnimation.bind(this);
  44091. this.resumeAnimation = this.resumeAnimation.bind(this);
  44092. this.fromColor = {};
  44093. this.toColor = {};
  44094. this.targets = {};
  44095. this.targetsArray = [];
  44096. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  44097. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  44098. this.config = {
  44099. complete: function () {
  44100. self.animationIsPlaying = false;
  44101. self.el.emit('animationcomplete', self.eventDetail, false);
  44102. if (self.id) {
  44103. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  44104. }
  44105. }
  44106. };
  44107. },
  44108. update: function (oldData) {
  44109. var config = this.config;
  44110. var data = this.data;
  44111. this.animationIsPlaying = false;
  44112. if (!this.data.enabled) { return; }
  44113. if (!data.property) { return; }
  44114. // Base config.
  44115. config.autoplay = false;
  44116. config.direction = data.dir;
  44117. config.duration = data.dur;
  44118. config.easing = data.easing;
  44119. config.elasticity = data.elasticity;
  44120. config.loop = data.loop;
  44121. config.round = data.round;
  44122. // Start new animation.
  44123. this.createAndStartAnimation();
  44124. },
  44125. tick: function (t, dt) {
  44126. if (!this.animationIsPlaying) { return; }
  44127. this.time += dt;
  44128. this.animation.tick(this.time);
  44129. },
  44130. remove: function () {
  44131. this.pauseAnimation();
  44132. this.removeEventListeners();
  44133. },
  44134. pause: function () {
  44135. this.paused = true;
  44136. this.pausedWasPlaying = this.animationIsPlaying;
  44137. this.pauseAnimation();
  44138. this.removeEventListeners();
  44139. },
  44140. /**
  44141. * `play` handler only for resuming scene.
  44142. */
  44143. play: function () {
  44144. if (!this.paused) { return; }
  44145. this.paused = false;
  44146. this.addEventListeners();
  44147. if (this.pausedWasPlaying) {
  44148. this.resumeAnimation();
  44149. this.pausedWasPlaying = false;
  44150. }
  44151. },
  44152. /**
  44153. * Start animation from scratch.
  44154. */
  44155. createAndStartAnimation: function () {
  44156. var data = this.data;
  44157. this.updateConfig();
  44158. this.animationIsPlaying = false;
  44159. this.animation = anime(this.config);
  44160. this.animation.began = true;
  44161. this.removeEventListeners();
  44162. this.addEventListeners();
  44163. // Wait for start events for animation.
  44164. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  44165. // Delay animation.
  44166. if (data.delay) {
  44167. setTimeout(this.beginAnimation, data.delay);
  44168. return;
  44169. }
  44170. // Play animation.
  44171. this.beginAnimation();
  44172. },
  44173. /**
  44174. * This is before animation start (including from startEvents).
  44175. * Set to initial state (config.from, time = 0, seekTime = 0).
  44176. */
  44177. beginAnimation: function () {
  44178. this.updateConfig();
  44179. this.animation.began = true;
  44180. this.time = 0;
  44181. this.animationIsPlaying = true;
  44182. this.stopRelatedAnimations();
  44183. this.el.emit('animationbegin', this.eventDetail, false);
  44184. },
  44185. pauseAnimation: function () {
  44186. this.animationIsPlaying = false;
  44187. },
  44188. resumeAnimation: function () {
  44189. this.animationIsPlaying = true;
  44190. },
  44191. /**
  44192. * startEvents callback.
  44193. */
  44194. onStartEvent: function () {
  44195. if (!this.data.enabled) { return; }
  44196. this.updateConfig();
  44197. if (this.animation) {
  44198. this.animation.pause();
  44199. }
  44200. this.animation = anime(this.config);
  44201. // Include the delay before each start event.
  44202. if (this.data.delay) {
  44203. setTimeout(this.beginAnimation, this.data.delay);
  44204. return;
  44205. }
  44206. this.beginAnimation();
  44207. },
  44208. /**
  44209. * rawProperty: true and type: color;
  44210. */
  44211. updateConfigForRawColor: function () {
  44212. var config = this.config;
  44213. var data = this.data;
  44214. var el = this.el;
  44215. var from;
  44216. var key;
  44217. var to;
  44218. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  44219. return;
  44220. }
  44221. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  44222. to = data.to;
  44223. // Use r/g/b vector for color type.
  44224. this.setColorConfig(from, to);
  44225. from = this.fromColor;
  44226. to = this.toColor;
  44227. this.targetsArray.length = 0;
  44228. this.targetsArray.push(from);
  44229. config.targets = this.targetsArray;
  44230. for (key in to) { config[key] = to[key]; }
  44231. config.update = (function () {
  44232. var lastValue = {};
  44233. return function (anim) {
  44234. var value;
  44235. value = anim.animatables[0].target;
  44236. // For animation timeline.
  44237. if (value.r === lastValue.r &&
  44238. value.g === lastValue.g &&
  44239. value.b === lastValue.b) { return; }
  44240. setRawProperty(el, data.property, value, data.type);
  44241. };
  44242. })();
  44243. },
  44244. /**
  44245. * Stuff property into generic `property` key.
  44246. */
  44247. updateConfigForDefault: function () {
  44248. var config = this.config;
  44249. var data = this.data;
  44250. var el = this.el;
  44251. var from;
  44252. var isBoolean;
  44253. var isNumber;
  44254. var to;
  44255. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  44256. return;
  44257. }
  44258. if (data.from === '') {
  44259. // Infer from.
  44260. from = isRawProperty(data)
  44261. ? getRawProperty(el, data.property)
  44262. : getComponentProperty(el, data.property);
  44263. } else {
  44264. // Explicit from.
  44265. from = data.from;
  44266. }
  44267. to = data.to;
  44268. isNumber = !isNaN(from || to);
  44269. if (isNumber) {
  44270. from = parseFloat(from);
  44271. to = parseFloat(to);
  44272. } else {
  44273. from = from ? from.toString() : from;
  44274. to = to ? to.toString() : to;
  44275. }
  44276. // Convert booleans to integer to allow boolean flipping.
  44277. isBoolean = data.to === 'true' || data.to === 'false' ||
  44278. data.to === true || data.to === false;
  44279. if (isBoolean) {
  44280. from = data.from === 'true' || data.from === true ? 1 : 0;
  44281. to = data.to === 'true' || data.to === true ? 1 : 0;
  44282. }
  44283. this.targets.aframeProperty = from;
  44284. config.targets = this.targets;
  44285. config.aframeProperty = to;
  44286. config.update = (function () {
  44287. var lastValue;
  44288. return function (anim) {
  44289. var value;
  44290. value = anim.animatables[0].target.aframeProperty;
  44291. // Need to do a last value check for animation timeline since all the tweening
  44292. // begins simultaenously even if the value has not changed. Also better for perf
  44293. // anyways.
  44294. if (value === lastValue) { return; }
  44295. lastValue = value;
  44296. if (isBoolean) { value = value >= 1; }
  44297. if (isRawProperty(data)) {
  44298. setRawProperty(el, data.property, value, data.type);
  44299. } else {
  44300. setComponentProperty(el, data.property, value);
  44301. }
  44302. };
  44303. })();
  44304. },
  44305. /**
  44306. * Extend x/y/z/w onto the config.
  44307. * Update vector by modifying object3D.
  44308. */
  44309. updateConfigForVector: function () {
  44310. var config = this.config;
  44311. var data = this.data;
  44312. var el = this.el;
  44313. var key;
  44314. var from;
  44315. var to;
  44316. // Parse coordinates.
  44317. from = data.from !== ''
  44318. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  44319. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  44320. to = utils.coordinates.parse(data.to);
  44321. if (data.property === PROP_ROTATION) {
  44322. toRadians(from);
  44323. toRadians(to);
  44324. }
  44325. // Set to and from.
  44326. this.targetsArray.length = 0;
  44327. this.targetsArray.push(from);
  44328. config.targets = this.targetsArray;
  44329. for (key in to) { config[key] = to[key]; }
  44330. // If animating object3D transformation, run more optimized updater.
  44331. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  44332. data.property === PROP_SCALE) {
  44333. config.update = (function () {
  44334. var lastValue = {};
  44335. return function (anim) {
  44336. var value = anim.animatables[0].target;
  44337. if (data.property === PROP_SCALE) {
  44338. value.x = Math.max(0.0001, value.x);
  44339. value.y = Math.max(0.0001, value.y);
  44340. value.z = Math.max(0.0001, value.z);
  44341. }
  44342. // For animation timeline.
  44343. if (value.x === lastValue.x &&
  44344. value.y === lastValue.y &&
  44345. value.z === lastValue.z) { return; }
  44346. lastValue.x = value.x;
  44347. lastValue.y = value.y;
  44348. lastValue.z = value.z;
  44349. el.object3D[data.property].set(value.x, value.y, value.z);
  44350. };
  44351. })();
  44352. return;
  44353. }
  44354. // Animating some vector.
  44355. config.update = (function () {
  44356. var lastValue = {};
  44357. return function (anim) {
  44358. var value = anim.animatables[0].target;
  44359. // Animate rotation through radians.
  44360. // For animation timeline.
  44361. if (value.x === lastValue.x &&
  44362. value.y === lastValue.y &&
  44363. value.z === lastValue.z) { return; }
  44364. lastValue.x = value.x;
  44365. lastValue.y = value.y;
  44366. lastValue.z = value.z;
  44367. setComponentProperty(el, data.property, value);
  44368. };
  44369. })();
  44370. },
  44371. /**
  44372. * Update the config before each run.
  44373. */
  44374. updateConfig: function () {
  44375. var propType;
  44376. // Route config type.
  44377. propType = getPropertyType(this.el, this.data.property);
  44378. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  44379. this.updateConfigForRawColor();
  44380. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  44381. this.updateConfigForVector();
  44382. } else {
  44383. this.updateConfigForDefault();
  44384. }
  44385. },
  44386. /**
  44387. * Wait for component to initialize.
  44388. */
  44389. waitComponentInitRawProperty: function (cb) {
  44390. var componentName;
  44391. var data = this.data;
  44392. var el = this.el;
  44393. var self = this;
  44394. if (data.from !== '') { return false; }
  44395. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  44396. componentName = splitDot(data.property)[1];
  44397. if (el.components[componentName]) { return false; }
  44398. el.addEventListener('componentinitialized', function wait (evt) {
  44399. if (evt.detail.name !== componentName) { return; }
  44400. cb();
  44401. // Since the config was created async, create the animation now since we missed it
  44402. // earlier.
  44403. self.animation = anime(self.config);
  44404. el.removeEventListener('componentinitialized', wait);
  44405. });
  44406. return true;
  44407. },
  44408. /**
  44409. * Make sure two animations on the same property don't fight each other.
  44410. * e.g., animation__mouseenter="property: material.opacity"
  44411. * animation__mouseleave="property: material.opacity"
  44412. */
  44413. stopRelatedAnimations: function () {
  44414. var component;
  44415. var componentName;
  44416. for (componentName in this.el.components) {
  44417. component = this.el.components[componentName];
  44418. if (componentName === this.attrName) { continue; }
  44419. if (component.name !== 'animation') { continue; }
  44420. if (!component.animationIsPlaying) { continue; }
  44421. if (component.data.property !== this.data.property) { continue; }
  44422. component.animationIsPlaying = false;
  44423. }
  44424. },
  44425. addEventListeners: function () {
  44426. var data = this.data;
  44427. var el = this.el;
  44428. addEventListeners(el, data.startEvents, this.onStartEvent);
  44429. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44430. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44431. },
  44432. removeEventListeners: function () {
  44433. var data = this.data;
  44434. var el = this.el;
  44435. removeEventListeners(el, data.startEvents, this.onStartEvent);
  44436. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44437. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44438. },
  44439. setColorConfig: function (from, to) {
  44440. colorHelperFrom.set(from);
  44441. colorHelperTo.set(to);
  44442. from = this.fromColor;
  44443. to = this.toColor;
  44444. from.r = colorHelperFrom.r;
  44445. from.g = colorHelperFrom.g;
  44446. from.b = colorHelperFrom.b;
  44447. to.r = colorHelperTo.r;
  44448. to.g = colorHelperTo.g;
  44449. to.b = colorHelperTo.b;
  44450. }
  44451. });
  44452. /**
  44453. * Given property name, check schema to see what type we are animating.
  44454. * We just care whether the property is a vector.
  44455. */
  44456. function getPropertyType (el, property) {
  44457. var component;
  44458. var componentName;
  44459. var split;
  44460. var propertyName;
  44461. split = property.split('.');
  44462. componentName = split[0];
  44463. propertyName = split[1];
  44464. component = el.components[componentName] || components[componentName];
  44465. // Primitives.
  44466. if (!component) { return null; }
  44467. // Dynamic schema. We only care about vectors anyways.
  44468. if (propertyName && !component.schema[propertyName]) { return null; }
  44469. // Multi-prop.
  44470. if (propertyName) { return component.schema[propertyName].type; }
  44471. // Single-prop.
  44472. return component.schema.type;
  44473. }
  44474. /**
  44475. * Convert object to radians.
  44476. */
  44477. function toRadians (obj) {
  44478. obj.x = THREE.Math.degToRad(obj.x);
  44479. obj.y = THREE.Math.degToRad(obj.y);
  44480. obj.z = THREE.Math.degToRad(obj.z);
  44481. }
  44482. function addEventListeners (el, eventNames, handler) {
  44483. var i;
  44484. for (i = 0; i < eventNames.length; i++) {
  44485. el.addEventListener(eventNames[i], handler);
  44486. }
  44487. }
  44488. function removeEventListeners (el, eventNames, handler) {
  44489. var i;
  44490. for (i = 0; i < eventNames.length; i++) {
  44491. el.removeEventListener(eventNames[i], handler);
  44492. }
  44493. }
  44494. function getRawProperty (el, path) {
  44495. var i;
  44496. var split;
  44497. var value;
  44498. split = splitDot(path);
  44499. value = el;
  44500. for (i = 0; i < split.length; i++) {
  44501. value = value[split[i]];
  44502. }
  44503. if (value === undefined) {
  44504. console.log(el);
  44505. throw new Error('[animation] property (' + path + ') could not be found');
  44506. }
  44507. return value;
  44508. }
  44509. function setRawProperty (el, path, value, type) {
  44510. var i;
  44511. var split;
  44512. var propertyName;
  44513. var targetValue;
  44514. if (path.startsWith('object3D.rotation')) {
  44515. value = THREE.Math.degToRad(value);
  44516. }
  44517. // Walk.
  44518. split = splitDot(path);
  44519. targetValue = el;
  44520. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  44521. propertyName = split[split.length - 1];
  44522. // Raw color.
  44523. if (type === TYPE_COLOR) {
  44524. if ('r' in targetValue[propertyName]) {
  44525. targetValue[propertyName].r = value.r;
  44526. targetValue[propertyName].g = value.g;
  44527. targetValue[propertyName].b = value.b;
  44528. } else {
  44529. targetValue[propertyName].x = value.r;
  44530. targetValue[propertyName].y = value.g;
  44531. targetValue[propertyName].z = value.b;
  44532. }
  44533. return;
  44534. }
  44535. targetValue[propertyName] = value;
  44536. }
  44537. function splitDot (path) {
  44538. if (path in splitCache) { return splitCache[path]; }
  44539. splitCache[path] = path.split('.');
  44540. return splitCache[path];
  44541. }
  44542. function isRawProperty (data) {
  44543. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  44544. data.property.startsWith(STRING_OBJECT3D);
  44545. }
  44546. },{"../core/component":135,"../lib/three":183,"../utils":210,"super-animejs":56}],76:[function(require,module,exports){
  44547. var registerComponent = require('../core/component').registerComponent;
  44548. var THREE = require('../lib/three');
  44549. /**
  44550. * Camera component.
  44551. * Pairs along with camera system to handle tracking the active camera.
  44552. */
  44553. module.exports.Component = registerComponent('camera', {
  44554. schema: {
  44555. active: {default: true},
  44556. far: {default: 10000},
  44557. fov: {default: 80, min: 0},
  44558. near: {default: 0.005, min: 0},
  44559. spectator: {default: false},
  44560. zoom: {default: 1, min: 0}
  44561. },
  44562. /**
  44563. * Initialize three.js camera and add it to the entity.
  44564. * Add reference from scene to this entity as the camera.
  44565. */
  44566. init: function () {
  44567. var camera;
  44568. var el = this.el;
  44569. // Create camera.
  44570. camera = this.camera = new THREE.PerspectiveCamera();
  44571. el.setObject3D('camera', camera);
  44572. },
  44573. /**
  44574. * Update three.js camera.
  44575. */
  44576. update: function (oldData) {
  44577. var data = this.data;
  44578. var camera = this.camera;
  44579. // Update properties.
  44580. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  44581. camera.far = data.far;
  44582. camera.fov = data.fov;
  44583. camera.near = data.near;
  44584. camera.zoom = data.zoom;
  44585. camera.updateProjectionMatrix();
  44586. this.updateActiveCamera(oldData);
  44587. this.updateSpectatorCamera(oldData);
  44588. },
  44589. updateActiveCamera: function (oldData) {
  44590. var data = this.data;
  44591. var el = this.el;
  44592. var system = this.system;
  44593. // Active property did not change.
  44594. if (oldData && oldData.active === data.active || data.spectator) { return; }
  44595. // If `active` property changes, or first update, handle active camera with system.
  44596. if (data.active && system.activeCameraEl !== el) {
  44597. // Camera enabled. Set camera to this camera.
  44598. system.setActiveCamera(el);
  44599. } else if (!data.active && system.activeCameraEl === el) {
  44600. // Camera disabled. Set camera to another camera.
  44601. system.disableActiveCamera();
  44602. }
  44603. },
  44604. updateSpectatorCamera: function (oldData) {
  44605. var data = this.data;
  44606. var el = this.el;
  44607. var system = this.system;
  44608. // spectator property did not change.
  44609. if (oldData && oldData.spectator === data.spectator) { return; }
  44610. // If `spectator` property changes, or first update, handle spectator camera with system.
  44611. if (data.spectator && system.spectatorCameraEl !== el) {
  44612. // Camera enabled. Set camera to this camera.
  44613. system.setSpectatorCamera(el);
  44614. } else if (!data.spectator && system.spectatorCameraEl === el) {
  44615. // Camera disabled. Set camera to another camera.
  44616. system.disableSpectatorCamera();
  44617. }
  44618. },
  44619. /**
  44620. * Remove camera on remove (callback).
  44621. */
  44622. remove: function () {
  44623. this.el.removeObject3D('camera');
  44624. }
  44625. });
  44626. },{"../core/component":135,"../lib/three":183}],77:[function(require,module,exports){
  44627. /* global THREE */
  44628. var registerComponent = require('../core/component').registerComponent;
  44629. var utils = require('../utils/');
  44630. var bind = utils.bind;
  44631. var EVENTS = {
  44632. CLICK: 'click',
  44633. FUSING: 'fusing',
  44634. MOUSEENTER: 'mouseenter',
  44635. MOUSEDOWN: 'mousedown',
  44636. MOUSELEAVE: 'mouseleave',
  44637. MOUSEUP: 'mouseup'
  44638. };
  44639. var STATES = {
  44640. FUSING: 'cursor-fusing',
  44641. HOVERING: 'cursor-hovering',
  44642. HOVERED: 'cursor-hovered'
  44643. };
  44644. var CANVAS_EVENTS = {
  44645. DOWN: ['mousedown', 'touchstart'],
  44646. UP: ['mouseup', 'touchend']
  44647. };
  44648. var WEBXR_EVENTS = {
  44649. DOWN: ['selectstart'],
  44650. UP: ['selectend']
  44651. };
  44652. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  44653. /**
  44654. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  44655. * from the camera and pointing from camera's facing direction, and then only returning the
  44656. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  44657. *
  44658. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  44659. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  44660. * @member {object} intersection - Attributes of the current intersection event, including
  44661. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  44662. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  44663. * emit events when unintersecting.
  44664. */
  44665. module.exports.Component = registerComponent('cursor', {
  44666. dependencies: ['raycaster'],
  44667. schema: {
  44668. downEvents: {default: []},
  44669. fuse: {default: utils.device.isMobile()},
  44670. fuseTimeout: {default: 1500, min: 0},
  44671. mouseCursorStylesEnabled: {default: true},
  44672. upEvents: {default: []},
  44673. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  44674. },
  44675. init: function () {
  44676. var self = this;
  44677. this.fuseTimeout = undefined;
  44678. this.cursorDownEl = null;
  44679. this.intersectedEl = null;
  44680. this.canvasBounds = document.body.getBoundingClientRect();
  44681. this.isCursorDown = false;
  44682. // Debounce.
  44683. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  44684. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  44685. }, 500);
  44686. this.eventDetail = {};
  44687. this.intersectedEventDetail = {cursorEl: this.el};
  44688. // Bind methods.
  44689. this.onCursorDown = bind(this.onCursorDown, this);
  44690. this.onCursorUp = bind(this.onCursorUp, this);
  44691. this.onIntersection = bind(this.onIntersection, this);
  44692. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  44693. this.onMouseMove = bind(this.onMouseMove, this);
  44694. this.onEnterVR = bind(this.onEnterVR, this);
  44695. },
  44696. update: function (oldData) {
  44697. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  44698. this.updateMouseEventListeners();
  44699. },
  44700. play: function () {
  44701. this.addEventListeners();
  44702. },
  44703. pause: function () {
  44704. this.removeEventListeners();
  44705. },
  44706. remove: function () {
  44707. var el = this.el;
  44708. el.removeState(STATES.HOVERING);
  44709. el.removeState(STATES.FUSING);
  44710. clearTimeout(this.fuseTimeout);
  44711. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  44712. this.removeEventListeners();
  44713. },
  44714. addEventListeners: function () {
  44715. var canvas;
  44716. var data = this.data;
  44717. var el = this.el;
  44718. var self = this;
  44719. function addCanvasListeners () {
  44720. canvas = el.sceneEl.canvas;
  44721. if (data.downEvents.length || data.upEvents.length) { return; }
  44722. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44723. canvas.addEventListener(downEvent, self.onCursorDown);
  44724. });
  44725. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44726. canvas.addEventListener(upEvent, self.onCursorUp);
  44727. });
  44728. }
  44729. canvas = el.sceneEl.canvas;
  44730. if (canvas) {
  44731. addCanvasListeners();
  44732. } else {
  44733. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  44734. }
  44735. data.downEvents.forEach(function (downEvent) {
  44736. el.addEventListener(downEvent, self.onCursorDown);
  44737. });
  44738. data.upEvents.forEach(function (upEvent) {
  44739. el.addEventListener(upEvent, self.onCursorUp);
  44740. });
  44741. el.addEventListener('raycaster-intersection', this.onIntersection);
  44742. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44743. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  44744. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44745. window.addEventListener('resize', this.updateCanvasBounds);
  44746. window.addEventListener('scroll', this.updateCanvasBounds);
  44747. this.updateMouseEventListeners();
  44748. },
  44749. removeEventListeners: function () {
  44750. var canvas;
  44751. var data = this.data;
  44752. var el = this.el;
  44753. var self = this;
  44754. canvas = el.sceneEl.canvas;
  44755. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  44756. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44757. canvas.removeEventListener(downEvent, self.onCursorDown);
  44758. });
  44759. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44760. canvas.removeEventListener(upEvent, self.onCursorUp);
  44761. });
  44762. }
  44763. data.downEvents.forEach(function (downEvent) {
  44764. el.removeEventListener(downEvent, self.onCursorDown);
  44765. });
  44766. data.upEvents.forEach(function (upEvent) {
  44767. el.removeEventListener(upEvent, self.onCursorUp);
  44768. });
  44769. el.removeEventListener('raycaster-intersection', this.onIntersection);
  44770. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44771. canvas.removeEventListener('mousemove', this.onMouseMove);
  44772. canvas.removeEventListener('touchstart', this.onMouseMove);
  44773. canvas.removeEventListener('touchmove', this.onMouseMove);
  44774. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  44775. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44776. window.removeEventListener('resize', this.updateCanvasBounds);
  44777. window.removeEventListener('scroll', this.updateCanvasBounds);
  44778. },
  44779. updateMouseEventListeners: function () {
  44780. var canvas;
  44781. var el = this.el;
  44782. canvas = el.sceneEl.canvas;
  44783. canvas.removeEventListener('mousemove', this.onMouseMove);
  44784. canvas.removeEventListener('touchmove', this.onMouseMove);
  44785. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  44786. if (this.data.rayOrigin !== 'mouse') { return; }
  44787. canvas.addEventListener('mousemove', this.onMouseMove, false);
  44788. canvas.addEventListener('touchmove', this.onMouseMove, false);
  44789. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  44790. this.updateCanvasBounds();
  44791. },
  44792. onMouseMove: (function () {
  44793. var direction = new THREE.Vector3();
  44794. var mouse = new THREE.Vector2();
  44795. var origin = new THREE.Vector3();
  44796. var rayCasterConfig = {origin: origin, direction: direction};
  44797. return function (evt) {
  44798. var bounds = this.canvasBounds;
  44799. var camera = this.el.sceneEl.camera;
  44800. var left;
  44801. var point;
  44802. var top;
  44803. camera.parent.updateMatrixWorld();
  44804. // Calculate mouse position based on the canvas element
  44805. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  44806. // Track the first touch for simplicity.
  44807. point = evt.touches.item(0);
  44808. } else {
  44809. point = evt;
  44810. }
  44811. left = point.clientX - bounds.left;
  44812. top = point.clientY - bounds.top;
  44813. mouse.x = (left / bounds.width) * 2 - 1;
  44814. mouse.y = -(top / bounds.height) * 2 + 1;
  44815. if (camera && camera.isPerspectiveCamera) {
  44816. origin.setFromMatrixPosition(camera.matrixWorld);
  44817. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  44818. } else if (camera && camera.isOrthographicCamera) {
  44819. origin.set(mouse.x, mouse.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  44820. direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  44821. } else {
  44822. console.error('AFRAME.Raycaster: Unsupported camera type: ' + camera.type);
  44823. }
  44824. this.el.setAttribute('raycaster', rayCasterConfig);
  44825. if (evt.type === 'touchmove') { evt.preventDefault(); }
  44826. };
  44827. })(),
  44828. /**
  44829. * Trigger mousedown and keep track of the mousedowned entity.
  44830. */
  44831. onCursorDown: function (evt) {
  44832. this.isCursorDown = true;
  44833. // Raycast again for touch.
  44834. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  44835. this.onMouseMove(evt);
  44836. this.el.components.raycaster.checkIntersections();
  44837. evt.preventDefault();
  44838. }
  44839. this.twoWayEmit(EVENTS.MOUSEDOWN);
  44840. this.cursorDownEl = this.intersectedEl;
  44841. },
  44842. /**
  44843. * Trigger mouseup if:
  44844. * - Not fusing (mobile has no mouse).
  44845. * - Currently intersecting an entity.
  44846. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  44847. * in case user mousedowned one entity, dragged to another, and mouseupped.
  44848. */
  44849. onCursorUp: function (evt) {
  44850. if (!this.isCursorDown) { return; }
  44851. this.isCursorDown = false;
  44852. var data = this.data;
  44853. this.twoWayEmit(EVENTS.MOUSEUP);
  44854. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  44855. // previously cursorUp entity.
  44856. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  44857. this.intersectedEventDetail.intersection = null;
  44858. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  44859. }
  44860. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  44861. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  44862. this.twoWayEmit(EVENTS.CLICK);
  44863. }
  44864. this.cursorDownEl = null;
  44865. if (evt.type === 'touchend') { evt.preventDefault(); }
  44866. },
  44867. /**
  44868. * Handle intersection.
  44869. */
  44870. onIntersection: function (evt) {
  44871. var currentIntersection;
  44872. var cursorEl = this.el;
  44873. var index;
  44874. var intersectedEl;
  44875. var intersection;
  44876. // Select closest object, excluding the cursor.
  44877. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  44878. intersection = evt.detail.intersections[index];
  44879. intersectedEl = evt.detail.els[index];
  44880. // If cursor is the only intersected object, ignore the event.
  44881. if (!intersectedEl) { return; }
  44882. // Already intersecting this entity.
  44883. if (this.intersectedEl === intersectedEl) { return; }
  44884. // Ignore events further away than active intersection.
  44885. if (this.intersectedEl) {
  44886. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  44887. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  44888. }
  44889. // Unset current intersection.
  44890. this.clearCurrentIntersection(true);
  44891. this.setIntersection(intersectedEl, intersection);
  44892. },
  44893. /**
  44894. * Handle intersection cleared.
  44895. */
  44896. onIntersectionCleared: function (evt) {
  44897. var clearedEls = evt.detail.clearedEls;
  44898. // Check if the current intersection has ended
  44899. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  44900. this.clearCurrentIntersection();
  44901. },
  44902. onEnterVR: function () {
  44903. this.clearCurrentIntersection(true);
  44904. var xrSession = this.el.sceneEl.xrSession;
  44905. var self = this;
  44906. if (!xrSession) { return; }
  44907. if (this.data.rayOrigin === 'mouse') { return; }
  44908. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  44909. xrSession.addEventListener(downEvent, self.onCursorDown);
  44910. });
  44911. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  44912. xrSession.addEventListener(upEvent, self.onCursorUp);
  44913. });
  44914. },
  44915. setIntersection: function (intersectedEl, intersection) {
  44916. var cursorEl = this.el;
  44917. var data = this.data;
  44918. var self = this;
  44919. // Already intersecting.
  44920. if (this.intersectedEl === intersectedEl) { return; }
  44921. // Set new intersection.
  44922. this.intersectedEl = intersectedEl;
  44923. // Hovering.
  44924. cursorEl.addState(STATES.HOVERING);
  44925. intersectedEl.addState(STATES.HOVERED);
  44926. this.twoWayEmit(EVENTS.MOUSEENTER);
  44927. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  44928. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  44929. }
  44930. // Begin fuse if necessary.
  44931. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  44932. cursorEl.addState(STATES.FUSING);
  44933. this.twoWayEmit(EVENTS.FUSING);
  44934. this.fuseTimeout = setTimeout(function fuse () {
  44935. cursorEl.removeState(STATES.FUSING);
  44936. self.twoWayEmit(EVENTS.CLICK);
  44937. }, data.fuseTimeout);
  44938. },
  44939. clearCurrentIntersection: function (ignoreRemaining) {
  44940. var index;
  44941. var intersection;
  44942. var intersections;
  44943. var cursorEl = this.el;
  44944. // Nothing to be cleared.
  44945. if (!this.intersectedEl) { return; }
  44946. // No longer hovering (or fusing).
  44947. this.intersectedEl.removeState(STATES.HOVERED);
  44948. cursorEl.removeState(STATES.HOVERING);
  44949. cursorEl.removeState(STATES.FUSING);
  44950. this.twoWayEmit(EVENTS.MOUSELEAVE);
  44951. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  44952. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  44953. }
  44954. // Unset intersected entity (after emitting the event).
  44955. this.intersectedEl = null;
  44956. // Clear fuseTimeout.
  44957. clearTimeout(this.fuseTimeout);
  44958. // Set intersection to another raycasted element if any.
  44959. if (ignoreRemaining === true) { return; }
  44960. intersections = this.el.components.raycaster.intersections;
  44961. if (intersections.length === 0) { return; }
  44962. // Exclude the cursor.
  44963. index = intersections[0].object.el === cursorEl ? 1 : 0;
  44964. intersection = intersections[index];
  44965. if (!intersection) { return; }
  44966. this.setIntersection(intersection.object.el, intersection);
  44967. },
  44968. /**
  44969. * Helper to emit on both the cursor and the intersected entity (if exists).
  44970. */
  44971. twoWayEmit: function (evtName) {
  44972. var el = this.el;
  44973. var intersectedEl = this.intersectedEl;
  44974. var intersection;
  44975. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  44976. this.eventDetail.intersectedEl = intersectedEl;
  44977. this.eventDetail.intersection = intersection;
  44978. el.emit(evtName, this.eventDetail);
  44979. if (!intersectedEl) { return; }
  44980. this.intersectedEventDetail.intersection = intersection;
  44981. intersectedEl.emit(evtName, this.intersectedEventDetail);
  44982. }
  44983. });
  44984. },{"../core/component":135,"../utils/":210}],78:[function(require,module,exports){
  44985. var registerComponent = require('../core/component').registerComponent;
  44986. var bind = require('../utils/bind');
  44987. var trackedControlsUtils = require('../utils/tracked-controls');
  44988. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44989. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44990. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44991. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  44992. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  44993. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  44994. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  44995. var GAMEPAD_ID_WEBXR = 'google-daydream';
  44996. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  44997. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  44998. /**
  44999. * Button indices:
  45000. * 0 - trackpad
  45001. * 1 - menu (never dispatched on this layer)
  45002. * 2 - system (never dispatched on this layer)
  45003. *
  45004. * Axis:
  45005. * 0 - trackpad x
  45006. * 1 - trackpad y
  45007. */
  45008. var INPUT_MAPPING_WEBVR = {
  45009. axes: {trackpad: [0, 1]},
  45010. buttons: ['trackpad', 'menu', 'system']
  45011. };
  45012. /**
  45013. * Button indices:
  45014. * 0 - none
  45015. * 1 - none
  45016. * 2 - touchpad
  45017. *
  45018. * Axis:
  45019. * 0 - touchpad x
  45020. * 1 - touchpad y
  45021. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/google/google-daydream.json
  45022. */
  45023. var INPUT_MAPPING_WEBXR = {
  45024. axes: {touchpad: [0, 1]},
  45025. buttons: ['none', 'none', 'touchpad', 'menu', 'system']
  45026. };
  45027. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  45028. /**
  45029. * Daydream controls.
  45030. * Interface with Daydream controller and map Gamepad events to
  45031. * controller buttons: trackpad, menu, system
  45032. * Load a controller model and highlight the pressed buttons.
  45033. */
  45034. module.exports.Component = registerComponent('daydream-controls', {
  45035. schema: {
  45036. hand: {default: ''}, // This informs the degenerate arm model.
  45037. buttonColor: {type: 'color', default: '#000000'},
  45038. buttonTouchedColor: {type: 'color', default: '#777777'},
  45039. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  45040. model: {default: true},
  45041. orientationOffset: {type: 'vec3'},
  45042. armModel: {default: true}
  45043. },
  45044. mapping: INPUT_MAPPING,
  45045. bindMethods: function () {
  45046. this.onModelLoaded = bind(this.onModelLoaded, this);
  45047. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45048. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45049. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45050. this.onAxisMoved = bind(this.onAxisMoved, this);
  45051. },
  45052. init: function () {
  45053. var self = this;
  45054. this.onButtonChanged = bind(this.onButtonChanged, this);
  45055. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45056. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45057. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45058. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45059. this.controllerPresent = false;
  45060. this.lastControllerCheck = 0;
  45061. this.bindMethods();
  45062. },
  45063. addEventListeners: function () {
  45064. var el = this.el;
  45065. el.addEventListener('buttonchanged', this.onButtonChanged);
  45066. el.addEventListener('buttondown', this.onButtonDown);
  45067. el.addEventListener('buttonup', this.onButtonUp);
  45068. el.addEventListener('touchstart', this.onButtonTouchStart);
  45069. el.addEventListener('touchend', this.onButtonTouchEnd);
  45070. el.addEventListener('model-loaded', this.onModelLoaded);
  45071. el.addEventListener('axismove', this.onAxisMoved);
  45072. this.controllerEventsActive = true;
  45073. },
  45074. removeEventListeners: function () {
  45075. var el = this.el;
  45076. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45077. el.removeEventListener('buttondown', this.onButtonDown);
  45078. el.removeEventListener('buttonup', this.onButtonUp);
  45079. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45080. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45081. el.removeEventListener('model-loaded', this.onModelLoaded);
  45082. el.removeEventListener('axismove', this.onAxisMoved);
  45083. this.controllerEventsActive = false;
  45084. },
  45085. checkIfControllerPresent: function () {
  45086. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45087. this.data.hand ? {hand: this.data.hand} : {});
  45088. },
  45089. play: function () {
  45090. this.checkIfControllerPresent();
  45091. this.addControllersUpdateListener();
  45092. },
  45093. pause: function () {
  45094. this.removeEventListeners();
  45095. this.removeControllersUpdateListener();
  45096. },
  45097. injectTrackedControls: function () {
  45098. var el = this.el;
  45099. var data = this.data;
  45100. el.setAttribute('tracked-controls', {
  45101. armModel: data.armModel,
  45102. hand: data.hand,
  45103. idPrefix: GAMEPAD_ID_PREFIX,
  45104. id: GAMEPAD_ID_PREFIX,
  45105. orientationOffset: data.orientationOffset
  45106. });
  45107. if (!this.data.model) { return; }
  45108. this.el.setAttribute('obj-model', {
  45109. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  45110. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  45111. });
  45112. },
  45113. addControllersUpdateListener: function () {
  45114. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45115. },
  45116. removeControllersUpdateListener: function () {
  45117. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45118. },
  45119. onControllersUpdate: function () {
  45120. this.checkIfControllerPresent();
  45121. },
  45122. onModelLoaded: function (evt) {
  45123. var controllerObject3D = evt.detail.model;
  45124. var buttonMeshes;
  45125. if (!this.data.model) { return; }
  45126. buttonMeshes = this.buttonMeshes = {};
  45127. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  45128. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  45129. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  45130. buttonMeshes.touchpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  45131. // Offset pivot point.
  45132. controllerObject3D.position.set(0, 0, -0.04);
  45133. },
  45134. onAxisMoved: function (evt) {
  45135. emitIfAxesChanged(this, this.mapping.axes, evt);
  45136. },
  45137. onButtonChanged: function (evt) {
  45138. var button = this.mapping.buttons[evt.detail.id];
  45139. if (!button) return;
  45140. // Pass along changed event with button state, using button mapping for convenience.
  45141. this.el.emit(button + 'changed', evt.detail.state);
  45142. },
  45143. updateModel: function (buttonName, evtName) {
  45144. if (!this.data.model) { return; }
  45145. this.updateButtonModel(buttonName, evtName);
  45146. },
  45147. updateButtonModel: function (buttonName, state) {
  45148. var buttonMeshes = this.buttonMeshes;
  45149. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45150. var color;
  45151. switch (state) {
  45152. case 'down':
  45153. color = this.data.buttonHighlightColor;
  45154. break;
  45155. case 'touchstart':
  45156. color = this.data.buttonTouchedColor;
  45157. break;
  45158. default:
  45159. color = this.data.buttonColor;
  45160. }
  45161. buttonMeshes[buttonName].material.color.set(color);
  45162. }
  45163. });
  45164. },{"../core/component":135,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],79:[function(require,module,exports){
  45165. var registerComponent = require('../core/component').registerComponent;
  45166. var bind = require('../utils/bind');
  45167. var trackedControlsUtils = require('../utils/tracked-controls');
  45168. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45169. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45170. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45171. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  45172. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  45173. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  45174. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  45175. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  45176. var GAMEPAD_ID_WEBVR = 'Gear VR';
  45177. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  45178. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  45179. /**
  45180. * Button indices:
  45181. * 0 - trackpad
  45182. * 1 - trigger
  45183. *
  45184. * Axis:
  45185. * 0 - trackpad x
  45186. * 1 - trackpad y
  45187. */
  45188. var INPUT_MAPPING_WEBVR = {
  45189. axes: {trackpad: [0, 1]},
  45190. buttons: ['trackpad', 'trigger']
  45191. };
  45192. /**
  45193. * Button indices:
  45194. * 0 - trigger
  45195. * 1 - none
  45196. * 2 - touchpad
  45197. * 3 - menu
  45198. *
  45199. * Axis:
  45200. * 0 - touchpad x
  45201. * 1 - touchpad y
  45202. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/samsung/samsung-gearvr.json
  45203. */
  45204. var INPUT_MAPPING_WEBXR = {
  45205. axes: {touchpad: [0, 1]},
  45206. buttons: ['trigger', 'none', 'touchpad', 'none', 'menu']
  45207. };
  45208. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  45209. /**
  45210. * Gear VR controls.
  45211. * Interface with Gear VR controller and map Gamepad events to
  45212. * controller buttons: trackpad, trigger
  45213. * Load a controller model and highlight the pressed buttons.
  45214. */
  45215. module.exports.Component = registerComponent('gearvr-controls', {
  45216. schema: {
  45217. hand: {default: ''}, // This informs the degenerate arm model.
  45218. buttonColor: {type: 'color', default: '#000000'},
  45219. buttonTouchedColor: {type: 'color', default: '#777777'},
  45220. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  45221. model: {default: true},
  45222. orientationOffset: {type: 'vec3'},
  45223. armModel: {default: true}
  45224. },
  45225. mapping: INPUT_MAPPING,
  45226. bindMethods: function () {
  45227. this.onModelLoaded = bind(this.onModelLoaded, this);
  45228. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45229. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45230. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45231. this.onAxisMoved = bind(this.onAxisMoved, this);
  45232. },
  45233. init: function () {
  45234. var self = this;
  45235. this.onButtonChanged = bind(this.onButtonChanged, this);
  45236. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45237. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45238. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45239. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45240. this.controllerPresent = false;
  45241. this.lastControllerCheck = 0;
  45242. this.bindMethods();
  45243. },
  45244. addEventListeners: function () {
  45245. var el = this.el;
  45246. el.addEventListener('buttonchanged', this.onButtonChanged);
  45247. el.addEventListener('buttondown', this.onButtonDown);
  45248. el.addEventListener('buttonup', this.onButtonUp);
  45249. el.addEventListener('touchstart', this.onButtonTouchStart);
  45250. el.addEventListener('touchend', this.onButtonTouchEnd);
  45251. el.addEventListener('model-loaded', this.onModelLoaded);
  45252. el.addEventListener('axismove', this.onAxisMoved);
  45253. this.controllerEventsActive = true;
  45254. },
  45255. removeEventListeners: function () {
  45256. var el = this.el;
  45257. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45258. el.removeEventListener('buttondown', this.onButtonDown);
  45259. el.removeEventListener('buttonup', this.onButtonUp);
  45260. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45261. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45262. el.removeEventListener('model-loaded', this.onModelLoaded);
  45263. el.removeEventListener('axismove', this.onAxisMoved);
  45264. this.controllerEventsActive = false;
  45265. },
  45266. checkIfControllerPresent: function () {
  45267. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45268. this.data.hand ? {hand: this.data.hand} : {});
  45269. },
  45270. play: function () {
  45271. this.checkIfControllerPresent();
  45272. this.addControllersUpdateListener();
  45273. },
  45274. pause: function () {
  45275. this.removeEventListeners();
  45276. this.removeControllersUpdateListener();
  45277. },
  45278. injectTrackedControls: function () {
  45279. var el = this.el;
  45280. var data = this.data;
  45281. el.setAttribute('tracked-controls', {
  45282. armModel: data.armModel,
  45283. hand: data.hand,
  45284. idPrefix: GAMEPAD_ID_PREFIX,
  45285. id: GAMEPAD_ID_PREFIX,
  45286. orientationOffset: data.orientationOffset
  45287. });
  45288. if (!this.data.model) { return; }
  45289. this.el.setAttribute('obj-model', {
  45290. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  45291. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  45292. });
  45293. },
  45294. addControllersUpdateListener: function () {
  45295. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45296. },
  45297. removeControllersUpdateListener: function () {
  45298. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45299. },
  45300. onControllersUpdate: function () {
  45301. this.checkIfControllerPresent();
  45302. },
  45303. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  45304. onModelLoaded: function (evt) {
  45305. var controllerObject3D = evt.detail.model;
  45306. var buttonMeshes;
  45307. if (!this.data.model) { return; }
  45308. buttonMeshes = this.buttonMeshes = {};
  45309. buttonMeshes.trigger = controllerObject3D.children[2];
  45310. buttonMeshes.trackpad = controllerObject3D.children[1];
  45311. buttonMeshes.touchpad = controllerObject3D.children[1];
  45312. },
  45313. onButtonChanged: function (evt) {
  45314. var button = this.mapping.buttons[evt.detail.id];
  45315. if (!button) return;
  45316. // Pass along changed event with button state, using button mapping for convenience.
  45317. this.el.emit(button + 'changed', evt.detail.state);
  45318. },
  45319. onAxisMoved: function (evt) {
  45320. emitIfAxesChanged(this, this.mapping.axes, evt);
  45321. },
  45322. updateModel: function (buttonName, evtName) {
  45323. if (!this.data.model) { return; }
  45324. this.updateButtonModel(buttonName, evtName);
  45325. },
  45326. updateButtonModel: function (buttonName, state) {
  45327. var buttonMeshes = this.buttonMeshes;
  45328. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45329. var color;
  45330. switch (state) {
  45331. case 'down':
  45332. color = this.data.buttonHighlightColor;
  45333. break;
  45334. case 'touchstart':
  45335. color = this.data.buttonTouchedColor;
  45336. break;
  45337. default:
  45338. color = this.data.buttonColor;
  45339. }
  45340. buttonMeshes[buttonName].material.color.set(color);
  45341. }
  45342. });
  45343. },{"../core/component":135,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],80:[function(require,module,exports){
  45344. var registerComponent = require('../core/component').registerComponent;
  45345. var bind = require('../utils/bind');
  45346. var trackedControlsUtils = require('../utils/tracked-controls');
  45347. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45348. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45349. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45350. var GAMEPAD_ID_PREFIX = 'generic';
  45351. /**
  45352. * Button indices:
  45353. * 0 - trigger
  45354. * 1 - squeeze
  45355. * 2 - touchpad
  45356. * 3 - thumbstick
  45357. *
  45358. * Axis:
  45359. * 0 - touchpad
  45360. * 1 - thumbstick
  45361. *
  45362. */
  45363. var INPUT_MAPPING = {
  45364. axes: {
  45365. touchpad: [0, 1],
  45366. thumbstick: [2, 3]
  45367. },
  45368. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  45369. };
  45370. /**
  45371. * Oculus Go controls.
  45372. * Interface with Oculus Go controller and map Gamepad events to
  45373. * controller buttons: trackpad, trigger
  45374. * Load a controller model and highlight the pressed buttons.
  45375. */
  45376. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  45377. schema: {
  45378. hand: {default: ''}, // This informs the degenerate arm model.
  45379. defaultModel: {default: true},
  45380. defaultModelColor: {default: 'gray'},
  45381. orientationOffset: {type: 'vec3'},
  45382. disabled: {default: false}
  45383. },
  45384. /**
  45385. * Button IDs:
  45386. * 0 - trackpad
  45387. * 1 - trigger
  45388. */
  45389. mapping: INPUT_MAPPING,
  45390. bindMethods: function () {
  45391. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45392. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45393. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45394. this.onAxisMoved = bind(this.onAxisMoved, this);
  45395. },
  45396. init: function () {
  45397. var self = this;
  45398. this.onButtonChanged = bind(this.onButtonChanged, this);
  45399. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45400. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45401. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45402. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45403. this.controllerPresent = false;
  45404. this.wasControllerConnected = false;
  45405. this.lastControllerCheck = 0;
  45406. this.rendererSystem = this.el.sceneEl.systems.renderer;
  45407. this.bindMethods();
  45408. // generic-tracked-controller-controls has the lowest precedence.
  45409. // We must diable this component if there are more specialized controls components.
  45410. this.el.addEventListener('controllerconnected', function (evt) {
  45411. if (evt.detail.name === self.name) { return; }
  45412. self.wasControllerConnected = true;
  45413. self.removeEventListeners();
  45414. self.removeControllersUpdateListener();
  45415. });
  45416. },
  45417. addEventListeners: function () {
  45418. var el = this.el;
  45419. el.addEventListener('buttonchanged', this.onButtonChanged);
  45420. el.addEventListener('buttondown', this.onButtonDown);
  45421. el.addEventListener('buttonup', this.onButtonUp);
  45422. el.addEventListener('touchstart', this.onButtonTouchStart);
  45423. el.addEventListener('touchend', this.onButtonTouchEnd);
  45424. el.addEventListener('axismove', this.onAxisMoved);
  45425. this.controllerEventsActive = true;
  45426. },
  45427. removeEventListeners: function () {
  45428. var el = this.el;
  45429. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45430. el.removeEventListener('buttondown', this.onButtonDown);
  45431. el.removeEventListener('buttonup', this.onButtonUp);
  45432. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45433. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45434. el.removeEventListener('axismove', this.onAxisMoved);
  45435. this.controllerEventsActive = false;
  45436. },
  45437. checkIfControllerPresent: function () {
  45438. var data = this.data;
  45439. var hand = data.hand ? data.hand : undefined;
  45440. checkControllerPresentAndSetup(
  45441. this, GAMEPAD_ID_PREFIX,
  45442. {hand: hand, iterateControllerProfiles: true});
  45443. },
  45444. play: function () {
  45445. if (this.wasControllerConnected) { return; }
  45446. this.checkIfControllerPresent();
  45447. this.addControllersUpdateListener();
  45448. },
  45449. pause: function () {
  45450. this.removeEventListeners();
  45451. this.removeControllersUpdateListener();
  45452. },
  45453. injectTrackedControls: function () {
  45454. var el = this.el;
  45455. var data = this.data;
  45456. // Do nothing if tracked-controls already set.
  45457. // Generic controls have the lowest precedence.
  45458. if (this.el.components['tracked-controls']) {
  45459. this.removeEventListeners();
  45460. return;
  45461. }
  45462. el.setAttribute('tracked-controls', {
  45463. hand: data.hand,
  45464. idPrefix: GAMEPAD_ID_PREFIX,
  45465. orientationOffset: data.orientationOffset,
  45466. iterateControllerProfiles: true
  45467. });
  45468. if (!this.data.defaultModel) { return; }
  45469. this.initDefaultModel();
  45470. },
  45471. addControllersUpdateListener: function () {
  45472. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45473. },
  45474. removeControllersUpdateListener: function () {
  45475. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45476. },
  45477. onControllersUpdate: function () {
  45478. this.checkIfControllerPresent();
  45479. },
  45480. onButtonChanged: function (evt) {
  45481. var button = this.mapping.buttons[evt.detail.id];
  45482. if (!button) return;
  45483. // Pass along changed event with button state, using button mapping for convenience.
  45484. this.el.emit(button + 'changed', evt.detail.state);
  45485. },
  45486. onAxisMoved: function (evt) {
  45487. emitIfAxesChanged(this, this.mapping.axes, evt);
  45488. },
  45489. initDefaultModel: function () {
  45490. var modelEl = this.modelEl = document.createElement('a-entity');
  45491. modelEl.setAttribute('geometry', {
  45492. primitive: 'sphere',
  45493. radius: 0.03
  45494. });
  45495. modelEl.setAttribute('material', {color: this.data.color});
  45496. this.el.appendChild(modelEl);
  45497. }
  45498. });
  45499. },{"../core/component":135,"../utils/bind":204,"../utils/tracked-controls":219}],81:[function(require,module,exports){
  45500. var geometries = require('../core/geometry').geometries;
  45501. var geometryNames = require('../core/geometry').geometryNames;
  45502. var registerComponent = require('../core/component').registerComponent;
  45503. var THREE = require('../lib/three');
  45504. var dummyGeometry = new THREE.BufferGeometry();
  45505. /**
  45506. * Geometry component. Combined with material component to make a mesh in 3D object.
  45507. * Extended with registered geometries.
  45508. */
  45509. module.exports.Component = registerComponent('geometry', {
  45510. schema: {
  45511. buffer: {default: true},
  45512. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  45513. skipCache: {default: false}
  45514. },
  45515. init: function () {
  45516. this.geometry = null;
  45517. },
  45518. /**
  45519. * Talk to geometry system to get or create geometry.
  45520. */
  45521. update: function (previousData) {
  45522. var data = this.data;
  45523. var el = this.el;
  45524. var mesh;
  45525. var system = this.system;
  45526. // Dispose old geometry if we created one.
  45527. if (this.geometry) {
  45528. system.unuseGeometry(previousData);
  45529. this.geometry = null;
  45530. }
  45531. // Create new geometry.
  45532. this.geometry = system.getOrCreateGeometry(data);
  45533. // Set on mesh. If mesh does not exist, create it.
  45534. mesh = el.getObject3D('mesh');
  45535. if (mesh) {
  45536. mesh.geometry = this.geometry;
  45537. } else {
  45538. mesh = new THREE.Mesh();
  45539. mesh.geometry = this.geometry;
  45540. // Default material if not defined on the entity.
  45541. if (!this.el.getAttribute('material')) {
  45542. mesh.material = new THREE.MeshStandardMaterial({
  45543. color: Math.random() * 0xFFFFFF,
  45544. metalness: 0,
  45545. roughness: 0.5
  45546. });
  45547. }
  45548. el.setObject3D('mesh', mesh);
  45549. }
  45550. },
  45551. /**
  45552. * Tell geometry system that entity is no longer using the geometry.
  45553. * Unset the geometry on the mesh
  45554. */
  45555. remove: function () {
  45556. this.system.unuseGeometry(this.data);
  45557. this.el.getObject3D('mesh').geometry = dummyGeometry;
  45558. this.geometry = null;
  45559. },
  45560. /**
  45561. * Update geometry component schema based on geometry type.
  45562. */
  45563. updateSchema: function (data) {
  45564. var currentGeometryType = this.oldData && this.oldData.primitive;
  45565. var newGeometryType = data.primitive;
  45566. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  45567. // Geometry has no schema.
  45568. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  45569. // Nothing has changed.
  45570. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  45571. this.extendSchema(schema);
  45572. }
  45573. });
  45574. },{"../core/component":135,"../core/geometry":136,"../lib/three":183}],82:[function(require,module,exports){
  45575. var registerComponent = require('../core/component').registerComponent;
  45576. var THREE = require('../lib/three');
  45577. var utils = require('../utils/');
  45578. var warn = utils.debug('components:gltf-model:warn');
  45579. /**
  45580. * glTF model loader.
  45581. */
  45582. module.exports.Component = registerComponent('gltf-model', {
  45583. schema: {type: 'model'},
  45584. init: function () {
  45585. var self = this;
  45586. var dracoLoader = this.system.getDRACOLoader();
  45587. var meshoptDecoder = this.system.getMeshoptDecoder();
  45588. this.model = null;
  45589. this.loader = new THREE.GLTFLoader();
  45590. if (dracoLoader) {
  45591. this.loader.setDRACOLoader(dracoLoader);
  45592. }
  45593. if (meshoptDecoder) {
  45594. this.ready = meshoptDecoder.then(function (meshoptDecoder) {
  45595. self.loader.setMeshoptDecoder(meshoptDecoder);
  45596. });
  45597. } else {
  45598. this.ready = Promise.resolve();
  45599. }
  45600. },
  45601. update: function () {
  45602. var self = this;
  45603. var el = this.el;
  45604. var src = this.data;
  45605. if (!src) { return; }
  45606. this.remove();
  45607. this.ready.then(function () {
  45608. self.loader.load(src, function gltfLoaded (gltfModel) {
  45609. self.model = gltfModel.scene || gltfModel.scenes[0];
  45610. self.model.animations = gltfModel.animations;
  45611. el.setObject3D('mesh', self.model);
  45612. el.emit('model-loaded', {format: 'gltf', model: self.model});
  45613. }, undefined /* onProgress */, function gltfFailed (error) {
  45614. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  45615. warn(message);
  45616. el.emit('model-error', {format: 'gltf', src: src});
  45617. });
  45618. });
  45619. },
  45620. remove: function () {
  45621. if (!this.model) { return; }
  45622. this.el.removeObject3D('mesh');
  45623. }
  45624. });
  45625. },{"../core/component":135,"../lib/three":183,"../utils/":210}],83:[function(require,module,exports){
  45626. /* global THREE */
  45627. var registerComponent = require('../core/component').registerComponent;
  45628. // Found at https://github.com/aframevr/assets.
  45629. var MODEL_URLS = {
  45630. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  45631. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  45632. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  45633. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  45634. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  45635. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  45636. };
  45637. // Poses.
  45638. var ANIMATIONS = {
  45639. open: 'Open',
  45640. // point: grip active, trackpad surface active, trigger inactive.
  45641. point: 'Point',
  45642. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  45643. pointThumb: 'Point + Thumb',
  45644. // fist: grip active, trigger active, trackpad surface active.
  45645. fist: 'Fist',
  45646. // hold: trigger active, grip inactive.
  45647. hold: 'Hold',
  45648. // thumbUp: grip active, trigger active, trackpad surface inactive.
  45649. thumbUp: 'Thumb Up'
  45650. };
  45651. // Map animation to public events for the API.
  45652. var EVENTS = {};
  45653. EVENTS[ANIMATIONS.fist] = 'grip';
  45654. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  45655. EVENTS[ANIMATIONS.point] = 'pointing';
  45656. /**
  45657. * Hand controls component that abstracts 6DoF controls:
  45658. * oculus-touch-controls, vive-controls, windows-motion-controls.
  45659. *
  45660. * Originally meant to be a sample implementation of applications-specific controls that
  45661. * abstracts multiple types of controllers.
  45662. *
  45663. * Auto-detect appropriate controller.
  45664. * Handle common events coming from the detected vendor-specific controls.
  45665. * Translate button events to semantic hand-related event names:
  45666. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  45667. * Load hand model with gestures that are applied based on the button pressed.
  45668. *
  45669. * @property {string} Hand mapping (`left`, `right`).
  45670. */
  45671. module.exports.Component = registerComponent('hand-controls', {
  45672. schema: {
  45673. color: {default: 'white', type: 'color'},
  45674. hand: { default: 'left' },
  45675. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  45676. },
  45677. init: function () {
  45678. var self = this;
  45679. var el = this.el;
  45680. // Current pose.
  45681. this.gesture = ANIMATIONS.open;
  45682. // Active buttons populated by events provided by the attached controls.
  45683. this.pressedButtons = {};
  45684. this.touchedButtons = {};
  45685. this.loader = new THREE.GLTFLoader();
  45686. this.loader.setCrossOrigin('anonymous');
  45687. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  45688. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  45689. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  45690. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  45691. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  45692. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  45693. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  45694. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  45695. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  45696. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  45697. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  45698. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  45699. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  45700. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  45701. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  45702. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  45703. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  45704. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  45705. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  45706. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  45707. this.onControllerConnected = this.onControllerConnected.bind(this);
  45708. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  45709. el.addEventListener('controllerconnected', this.onControllerConnected);
  45710. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  45711. // Hidden by default.
  45712. el.object3D.visible = false;
  45713. },
  45714. play: function () {
  45715. this.addEventListeners();
  45716. },
  45717. pause: function () {
  45718. this.removeEventListeners();
  45719. },
  45720. tick: function (time, delta) {
  45721. var mesh = this.el.getObject3D('mesh');
  45722. if (!mesh || !mesh.mixer) { return; }
  45723. mesh.mixer.update(delta / 1000);
  45724. },
  45725. onControllerConnected: function () {
  45726. this.el.object3D.visible = true;
  45727. },
  45728. onControllerDisconnected: function () {
  45729. this.el.object3D.visible = false;
  45730. },
  45731. addEventListeners: function () {
  45732. var el = this.el;
  45733. el.addEventListener('gripdown', this.onGripDown);
  45734. el.addEventListener('gripup', this.onGripUp);
  45735. el.addEventListener('trackpaddown', this.onTrackpadDown);
  45736. el.addEventListener('trackpadup', this.onTrackpadUp);
  45737. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45738. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45739. el.addEventListener('triggerdown', this.onTriggerDown);
  45740. el.addEventListener('triggerup', this.onTriggerUp);
  45741. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  45742. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  45743. el.addEventListener('griptouchstart', this.onGripTouchStart);
  45744. el.addEventListener('griptouchend', this.onGripTouchEnd);
  45745. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  45746. el.addEventListener('thumbstickup', this.onThumbstickUp);
  45747. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  45748. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  45749. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45750. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45751. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45752. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45753. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45754. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45755. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45756. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45757. },
  45758. removeEventListeners: function () {
  45759. var el = this.el;
  45760. el.removeEventListener('gripdown', this.onGripDown);
  45761. el.removeEventListener('gripup', this.onGripUp);
  45762. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  45763. el.removeEventListener('trackpadup', this.onTrackpadUp);
  45764. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45765. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45766. el.removeEventListener('triggerdown', this.onTriggerDown);
  45767. el.removeEventListener('triggerup', this.onTriggerUp);
  45768. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  45769. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  45770. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  45771. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  45772. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  45773. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  45774. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  45775. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  45776. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45777. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45778. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45779. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45780. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45781. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45782. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45783. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45784. },
  45785. /**
  45786. * Update handler. More like the `init` handler since the only property is the hand, and
  45787. * that won't be changing much.
  45788. */
  45789. update: function (previousHand) {
  45790. var controlConfiguration;
  45791. var el = this.el;
  45792. var hand = this.data.hand;
  45793. var handModelStyle = this.data.handModelStyle;
  45794. var handColor = this.data.color;
  45795. var self = this;
  45796. // Get common configuration to abstract different vendor controls.
  45797. controlConfiguration = {
  45798. hand: hand,
  45799. model: false
  45800. };
  45801. // Set model.
  45802. if (hand !== previousHand) {
  45803. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  45804. this.loader.load(handmodelUrl, function (gltf) {
  45805. var mesh = gltf.scene.children[0];
  45806. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  45807. mesh.mixer = new THREE.AnimationMixer(mesh);
  45808. self.clips = gltf.animations;
  45809. el.setObject3D('mesh', mesh);
  45810. var handMaterial = mesh.children[1].material;
  45811. handMaterial.color = new THREE.Color(handColor);
  45812. mesh.position.set(0, 0, 0);
  45813. mesh.rotation.set(0, 0, handModelOrientation);
  45814. el.setAttribute('magicleap-controls', controlConfiguration);
  45815. el.setAttribute('vive-controls', controlConfiguration);
  45816. el.setAttribute('oculus-touch-controls', controlConfiguration);
  45817. el.setAttribute('windows-motion-controls', controlConfiguration);
  45818. el.setAttribute('hp-mixed-reality-controls', controlConfiguration);
  45819. });
  45820. }
  45821. },
  45822. remove: function () {
  45823. this.el.removeObject3D('mesh');
  45824. },
  45825. /**
  45826. * Play model animation, based on which button was pressed and which kind of event.
  45827. *
  45828. * 1. Process buttons.
  45829. * 2. Determine gesture (this.determineGesture()).
  45830. * 3. Animation gesture (this.animationGesture()).
  45831. * 4. Emit gesture events (this.emitGestureEvents()).
  45832. *
  45833. * @param {string} button - Name of the button.
  45834. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  45835. */
  45836. handleButton: function (button, evt) {
  45837. var lastGesture;
  45838. var isPressed = evt === 'down';
  45839. var isTouched = evt === 'touchstart';
  45840. // Update objects.
  45841. if (evt.indexOf('touch') === 0) {
  45842. // Update touch object.
  45843. if (isTouched === this.touchedButtons[button]) { return; }
  45844. this.touchedButtons[button] = isTouched;
  45845. } else {
  45846. // Update button object.
  45847. if (isPressed === this.pressedButtons[button]) { return; }
  45848. this.pressedButtons[button] = isPressed;
  45849. }
  45850. // Determine the gesture.
  45851. lastGesture = this.gesture;
  45852. this.gesture = this.determineGesture();
  45853. // Same gesture.
  45854. if (this.gesture === lastGesture) { return; }
  45855. // Animate gesture.
  45856. this.animateGesture(this.gesture, lastGesture);
  45857. // Emit events.
  45858. this.emitGestureEvents(this.gesture, lastGesture);
  45859. },
  45860. /**
  45861. * Determine which pose hand should be in considering active and touched buttons.
  45862. */
  45863. determineGesture: function () {
  45864. var gesture;
  45865. var isGripActive = this.pressedButtons.grip;
  45866. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  45867. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  45868. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  45869. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  45870. var isVive = isViveController(this.el.components['tracked-controls']);
  45871. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  45872. if (isVive) {
  45873. if (isGripActive || isTriggerActive) {
  45874. gesture = ANIMATIONS.fist;
  45875. } else if (isTrackpadActive) {
  45876. gesture = ANIMATIONS.point;
  45877. }
  45878. } else {
  45879. if (isGripActive) {
  45880. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  45881. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  45882. } else {
  45883. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  45884. }
  45885. } else if (isTriggerActive) {
  45886. gesture = ANIMATIONS.hold;
  45887. }
  45888. }
  45889. return gesture;
  45890. },
  45891. /**
  45892. * Play corresponding clip to a gesture
  45893. */
  45894. getClip: function (gesture) {
  45895. var clip;
  45896. var i;
  45897. for (i = 0; i < this.clips.length; i++) {
  45898. clip = this.clips[i];
  45899. if (clip.name !== gesture) { continue; }
  45900. return clip;
  45901. }
  45902. },
  45903. /**
  45904. * Play gesture animation.
  45905. *
  45906. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  45907. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  45908. */
  45909. animateGesture: function (gesture, lastGesture) {
  45910. if (gesture) {
  45911. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  45912. return;
  45913. }
  45914. // If no gesture, then reverse the current gesture back to open pose.
  45915. this.playAnimation(lastGesture, lastGesture, true);
  45916. },
  45917. /**
  45918. * Emit `hand-controls`-specific events.
  45919. */
  45920. emitGestureEvents: function (gesture, lastGesture) {
  45921. var el = this.el;
  45922. var eventName;
  45923. if (lastGesture === gesture) { return; }
  45924. // Emit event for lastGesture not inactive.
  45925. eventName = getGestureEventName(lastGesture, false);
  45926. if (eventName) { el.emit(eventName); }
  45927. // Emit event for current gesture now active.
  45928. eventName = getGestureEventName(gesture, true);
  45929. if (eventName) { el.emit(eventName); }
  45930. },
  45931. /**
  45932. * Play hand animation based on button state.
  45933. *
  45934. * @param {string} gesture - Name of the animation as specified by the model.
  45935. * @param {string} lastGesture - Previous pose.
  45936. * @param {boolean} reverse - Whether animation should play in reverse.
  45937. */
  45938. playAnimation: function (gesture, lastGesture, reverse) {
  45939. var clip;
  45940. var fromAction;
  45941. var mesh = this.el.getObject3D('mesh');
  45942. var toAction;
  45943. if (!mesh) { return; }
  45944. // Stop all current animations.
  45945. mesh.mixer.stopAllAction();
  45946. // Grab clip action.
  45947. clip = this.getClip(gesture);
  45948. toAction = mesh.mixer.clipAction(clip);
  45949. toAction.clampWhenFinished = true;
  45950. toAction.loop = THREE.LoopRepeat;
  45951. toAction.repetitions = 0;
  45952. toAction.timeScale = reverse ? -1 : 1;
  45953. toAction.time = reverse ? clip.duration : 0;
  45954. toAction.weight = 1;
  45955. // No gesture to gesture or gesture to no gesture.
  45956. if (!lastGesture || gesture === lastGesture) {
  45957. // Stop all current animations.
  45958. mesh.mixer.stopAllAction();
  45959. // Play animation.
  45960. toAction.play();
  45961. return;
  45962. }
  45963. // Animate or crossfade from gesture to gesture.
  45964. clip = this.getClip(lastGesture);
  45965. fromAction = mesh.mixer.clipAction(clip);
  45966. fromAction.weight = 0.15;
  45967. fromAction.play();
  45968. toAction.play();
  45969. fromAction.crossFadeTo(toAction, 0.15, true);
  45970. }
  45971. });
  45972. /**
  45973. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  45974. *
  45975. * @param {string} gesture
  45976. * @param {boolean} active
  45977. */
  45978. function getGestureEventName (gesture, active) {
  45979. var eventName;
  45980. if (!gesture) { return; }
  45981. eventName = EVENTS[gesture];
  45982. if (eventName === 'grip') {
  45983. return eventName + (active ? 'close' : 'open');
  45984. }
  45985. if (eventName === 'point') {
  45986. return eventName + (active ? 'up' : 'down');
  45987. }
  45988. if (eventName === 'pointing' || eventName === 'pistol') {
  45989. return eventName + (active ? 'start' : 'end');
  45990. }
  45991. }
  45992. function isViveController (trackedControls) {
  45993. var controller = trackedControls && trackedControls.controller;
  45994. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  45995. (controller.profiles &&
  45996. controller.profiles[0] &&
  45997. controller.profiles[0] === 'htc-vive'));
  45998. return isVive;
  45999. }
  46000. },{"../core/component":135}],84:[function(require,module,exports){
  46001. /* global THREE, XRRigidTransform */
  46002. var registerComponent = require('../core/component').registerComponent;
  46003. var bind = require('../utils/bind');
  46004. var trackedControlsUtils = require('../utils/tracked-controls');
  46005. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46006. var LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v3/left.glb';
  46007. var RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v3/right.glb';
  46008. var BONE_PREFIX = {
  46009. left: 'b_l_',
  46010. right: 'b_r_'
  46011. };
  46012. var JOINTS = [
  46013. 'wrist',
  46014. 'thumb-metacarpal',
  46015. 'thumb-phalanx-proximal',
  46016. 'thumb-phalanx-distal',
  46017. 'thumb-tip',
  46018. 'index-finger-metacarpal',
  46019. 'index-finger-phalanx-proximal',
  46020. 'index-finger-phalanx-intermediate',
  46021. 'index-finger-phalanx-distal',
  46022. 'index-finger-tip',
  46023. 'middle-finger-metacarpal',
  46024. 'middle-finger-phalanx-proximal',
  46025. 'middle-finger-phalanx-intermediate',
  46026. 'middle-finger-phalanx-distal',
  46027. 'middle-finger-tip',
  46028. 'ring-finger-metacarpal',
  46029. 'ring-finger-phalanx-proximal',
  46030. 'ring-finger-phalanx-intermediate',
  46031. 'ring-finger-phalanx-distal',
  46032. 'ring-finger-tip',
  46033. 'pinky-finger-metacarpal',
  46034. 'pinky-finger-phalanx-proximal',
  46035. 'pinky-finger-phalanx-intermediate',
  46036. 'pinky-finger-phalanx-distal',
  46037. 'pinky-finger-tip'
  46038. ];
  46039. var BONE_MAPPING = {
  46040. 'wrist': 'wrist',
  46041. 'thumb-metacarpal': 'thumb1',
  46042. 'thumb-phalanx-proximal': 'thumb2',
  46043. 'thumb-phalanx-distal': 'thumb3',
  46044. 'thumb-tip': 'thumb_null',
  46045. 'index-finger-metacarpal': 'index0',
  46046. 'index-finger-phalanx-proximal': 'index1',
  46047. 'index-finger-phalanx-intermediate': 'index2',
  46048. 'index-finger-phalanx-distal': 'index3',
  46049. 'index-finger-tip': 'index_null',
  46050. 'middle-finger-metacarpal': 'middle0',
  46051. 'middle-finger-phalanx-proximal': 'middle1',
  46052. 'middle-finger-phalanx-intermediate': 'middle2',
  46053. 'middle-finger-phalanx-distal': 'middle3',
  46054. 'middle-finger-tip': 'middle_null',
  46055. 'ring-finger-metacarpal': 'ring0',
  46056. 'ring-finger-phalanx-proximal': 'ring1',
  46057. 'ring-finger-phalanx-intermediate': 'ring2',
  46058. 'ring-finger-phalanx-distal': 'ring3',
  46059. 'ring-finger-tip': 'ring_null',
  46060. 'pinky-finger-metacarpal': 'pinky0',
  46061. 'pinky-finger-phalanx-proximal': 'pinky1',
  46062. 'pinky-finger-phalanx-intermediate': 'pinky2',
  46063. 'pinky-finger-phalanx-distal': 'pinky3',
  46064. 'pinky-finger-tip': 'pinky_null'
  46065. };
  46066. var PINCH_START_DISTANCE = 0.015;
  46067. var PINCH_END_DISTANCE = 0.03;
  46068. var PINCH_POSITION_INTERPOLATION = 0.5;
  46069. /**
  46070. * Controls for hand tracking
  46071. */
  46072. module.exports.Component = registerComponent('hand-tracking-controls', {
  46073. schema: {
  46074. hand: {default: 'right', oneOf: ['left', 'right']},
  46075. modelStyle: {default: 'mesh', oneOf: ['dots', 'mesh']},
  46076. modelColor: {default: 'white'}
  46077. },
  46078. bindMethods: function () {
  46079. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46080. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46081. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46082. },
  46083. addEventListeners: function () {
  46084. this.el.addEventListener('model-loaded', this.onModelLoaded);
  46085. for (var i = 0; i < this.jointEls.length; ++i) {
  46086. this.jointEls[i].object3D.visible = true;
  46087. }
  46088. },
  46089. removeEventListeners: function () {
  46090. this.el.removeEventListener('model-loaded', this.onModelLoaded);
  46091. for (var i = 0; i < this.jointEls.length; ++i) {
  46092. this.jointEls[i].object3D.visible = false;
  46093. }
  46094. },
  46095. init: function () {
  46096. var sceneEl = this.el.sceneEl;
  46097. var webXROptionalAttributes = sceneEl.getAttribute('webxr').optionalFeatures;
  46098. webXROptionalAttributes.push('hand-tracking');
  46099. sceneEl.setAttribute('webxr', {optionalFeatures: webXROptionalAttributes});
  46100. this.onModelLoaded = this.onModelLoaded.bind(this);
  46101. this.jointEls = [];
  46102. this.controllerPresent = false;
  46103. this.isPinched = false;
  46104. this.pinchEventDetail = {position: new THREE.Vector3()};
  46105. this.indexTipPosition = new THREE.Vector3();
  46106. this.bindMethods();
  46107. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  46108. this.el.sceneEl.addEventListener('enter-vr', this.updateReferenceSpace);
  46109. this.el.sceneEl.addEventListener('exit-vr', this.updateReferenceSpace);
  46110. },
  46111. updateReferenceSpace: function () {
  46112. var self = this;
  46113. var xrSession = this.el.sceneEl.xrSession;
  46114. this.referenceSpace = undefined;
  46115. if (!xrSession) { return; }
  46116. var referenceSpaceType = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  46117. xrSession.requestReferenceSpace(referenceSpaceType).then(function (referenceSpace) {
  46118. self.referenceSpace = referenceSpace.getOffsetReferenceSpace(new XRRigidTransform({x: 0, y: 1.5, z: 0}));
  46119. }).catch(function (error) {
  46120. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(referenceSpaceType, 'tracked-controls-webxr uses reference space ' + referenceSpaceType);
  46121. throw error;
  46122. });
  46123. },
  46124. checkIfControllerPresent: function () {
  46125. var data = this.data;
  46126. var hand = data.hand ? data.hand : undefined;
  46127. checkControllerPresentAndSetup(
  46128. this, '',
  46129. {hand: hand, iterateControllerProfiles: true, handTracking: true});
  46130. },
  46131. play: function () {
  46132. this.checkIfControllerPresent();
  46133. this.addControllersUpdateListener();
  46134. },
  46135. tick: function () {
  46136. var sceneEl = this.el.sceneEl;
  46137. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46138. var frame = sceneEl.frame;
  46139. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46140. if (!controller || !frame || !trackedControlsWebXR) { return; }
  46141. if (controller.hand) {
  46142. this.el.object3D.position.set(0, 0, 0);
  46143. this.el.object3D.rotation.set(0, 0, 0);
  46144. if (frame.getJointPose) { this.updateHandModel(); }
  46145. this.detectGesture();
  46146. }
  46147. },
  46148. updateHandModel: function () {
  46149. if (this.data.modelStyle === 'dots') {
  46150. this.updateHandDotsModel();
  46151. }
  46152. if (this.data.modelStyle === 'mesh') {
  46153. this.updateHandMeshModel();
  46154. }
  46155. },
  46156. getBone: function (name) {
  46157. var bones = this.bones;
  46158. for (var i = 0; i < bones.length; i++) {
  46159. if (bones[i].name === name) { return bones[i]; }
  46160. }
  46161. return null;
  46162. },
  46163. updateHandMeshModel: function () {
  46164. var frame = this.el.sceneEl.frame;
  46165. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46166. var referenceSpace = this.referenceSpace;
  46167. if (!controller || !this.mesh || !referenceSpace) { return; }
  46168. this.mesh.visible = false;
  46169. for (var inputjoint of controller.hand.values()) {
  46170. var bone;
  46171. var jointPose;
  46172. var jointTransform;
  46173. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  46174. if (!BONE_MAPPING[inputjoint.jointName]) { continue; }
  46175. bone = this.getBone(BONE_PREFIX[this.data.hand] + BONE_MAPPING[inputjoint.jointName]);
  46176. if (bone != null && jointPose) {
  46177. jointTransform = jointPose.transform;
  46178. this.mesh.visible = true;
  46179. bone.position.copy(jointTransform.position).multiplyScalar(100);
  46180. bone.quaternion.set(jointTransform.orientation.x, jointTransform.orientation.y, jointTransform.orientation.z, jointTransform.orientation.w);
  46181. }
  46182. }
  46183. },
  46184. updateHandDotsModel: function () {
  46185. var frame = this.el.sceneEl.frame;
  46186. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46187. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46188. var referenceSpace = trackedControlsWebXR.system.referenceSpace;
  46189. var jointEl;
  46190. var object3D;
  46191. var jointPose;
  46192. var i = 0;
  46193. for (var inputjoint of controller.hand.values()) {
  46194. jointEl = this.jointEls[i++];
  46195. object3D = jointEl.object3D;
  46196. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  46197. jointEl.object3D.visible = !!jointPose;
  46198. if (!jointPose) { continue; }
  46199. object3D.matrix.elements = jointPose.transform.matrix;
  46200. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  46201. jointEl.setAttribute('scale', {x: jointPose.radius, y: jointPose.radius, z: jointPose.radius});
  46202. }
  46203. },
  46204. detectGesture: function () {
  46205. this.detectPinch();
  46206. },
  46207. detectPinch: (function () {
  46208. var thumbTipPosition = new THREE.Vector3();
  46209. return function () {
  46210. var frame = this.el.sceneEl.frame;
  46211. var indexTipPosition = this.indexTipPosition;
  46212. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46213. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  46214. var referenceSpace = this.referenceSpace || trackedControlsWebXR.system.referenceSpace;
  46215. var indexTip = controller.hand.get('index-finger-tip');
  46216. var thumbTip = controller.hand.get('thumb-tip');
  46217. if (!indexTip ||
  46218. !thumbTip) { return; }
  46219. var indexTipPose = frame.getJointPose(indexTip, referenceSpace);
  46220. var thumbTipPose = frame.getJointPose(thumbTip, referenceSpace);
  46221. if (!indexTipPose || !thumbTipPose) { return; }
  46222. thumbTipPosition.copy(thumbTipPose.transform.position);
  46223. indexTipPosition.copy(indexTipPose.transform.position);
  46224. var distance = indexTipPosition.distanceTo(thumbTipPosition);
  46225. if (distance < PINCH_START_DISTANCE && this.isPinched === false) {
  46226. this.isPinched = true;
  46227. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46228. this.pinchEventDetail.position.y += 1.5;
  46229. this.el.emit('pinchstarted', this.pinchEventDetail);
  46230. }
  46231. if (distance > PINCH_END_DISTANCE && this.isPinched === true) {
  46232. this.isPinched = false;
  46233. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46234. this.pinchEventDetail.position.y += 1.5;
  46235. this.el.emit('pinchended', this.pinchEventDetail);
  46236. }
  46237. if (this.isPinched) {
  46238. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  46239. this.pinchEventDetail.position.y += 1.5;
  46240. this.el.emit('pinchmoved', this.pinchEventDetail);
  46241. }
  46242. indexTipPosition.y += 1.5;
  46243. };
  46244. })(),
  46245. pause: function () {
  46246. this.removeEventListeners();
  46247. this.removeControllersUpdateListener();
  46248. },
  46249. injectTrackedControls: function () {
  46250. var el = this.el;
  46251. var data = this.data;
  46252. el.setAttribute('tracked-controls', {
  46253. hand: data.hand,
  46254. iterateControllerProfiles: true,
  46255. handTrackingEnabled: true
  46256. });
  46257. this.initDefaultModel();
  46258. },
  46259. addControllersUpdateListener: function () {
  46260. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46261. },
  46262. removeControllersUpdateListener: function () {
  46263. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46264. },
  46265. onControllersUpdate: function () {
  46266. var controller;
  46267. this.checkIfControllerPresent();
  46268. controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  46269. if (!this.el.getObject3D('mesh')) { return; }
  46270. if (!controller || !controller.hand || !controller.hand[0]) {
  46271. this.el.getObject3D('mesh').visible = false;
  46272. }
  46273. },
  46274. initDefaultModel: function () {
  46275. if (this.el.getObject3D('mesh')) { return; }
  46276. if (this.data.modelStyle === 'dots') {
  46277. this.initDotsModel();
  46278. }
  46279. if (this.data.modelStyle === 'mesh') {
  46280. this.initMeshHandModel();
  46281. }
  46282. },
  46283. initDotsModel: function () {
  46284. // Add models just once.
  46285. if (this.jointEls.length !== 0) { return; }
  46286. for (var i = 0; i < JOINTS.length; ++i) {
  46287. var jointEl = this.jointEl = document.createElement('a-entity');
  46288. jointEl.setAttribute('geometry', {
  46289. primitive: 'sphere',
  46290. radius: 1.0
  46291. });
  46292. jointEl.setAttribute('material', {color: this.data.modelColor});
  46293. jointEl.object3D.visible = false;
  46294. this.el.appendChild(jointEl);
  46295. this.jointEls.push(jointEl);
  46296. }
  46297. },
  46298. initMeshHandModel: function () {
  46299. var modelURL = this.data.hand === 'left' ? LEFT_HAND_MODEL_URL : RIGHT_HAND_MODEL_URL;
  46300. this.el.setAttribute('gltf-model', modelURL);
  46301. },
  46302. onModelLoaded: function () {
  46303. var mesh = this.mesh = this.el.getObject3D('mesh').children[0];
  46304. var skinnedMesh = this.skinnedMesh = mesh.children[30];
  46305. if (!this.skinnedMesh) { return; }
  46306. this.bones = skinnedMesh.skeleton.bones;
  46307. this.el.removeObject3D('mesh');
  46308. mesh.position.set(0, 1.5, 0);
  46309. mesh.rotation.set(0, 0, 0);
  46310. skinnedMesh.frustumCulled = false;
  46311. skinnedMesh.material = new THREE.MeshStandardMaterial({skinning: true, color: this.data.modelColor});
  46312. this.el.setObject3D('mesh', mesh);
  46313. }
  46314. });
  46315. },{"../core/component":135,"../utils/bind":204,"../utils/tracked-controls":219}],85:[function(require,module,exports){
  46316. var register = require('../core/component').registerComponent;
  46317. module.exports.Component = register('hide-on-enter-ar', {
  46318. init: function () {
  46319. var self = this;
  46320. this.el.sceneEl.addEventListener('enter-vr', function () {
  46321. if (self.el.sceneEl.is('ar-mode')) {
  46322. self.el.object3D.visible = false;
  46323. }
  46324. });
  46325. this.el.sceneEl.addEventListener('exit-vr', function () {
  46326. self.el.object3D.visible = true;
  46327. });
  46328. }
  46329. });
  46330. },{"../core/component":135}],86:[function(require,module,exports){
  46331. var bind = require('../utils/bind');
  46332. var registerComponent = require('../core/component').registerComponent;
  46333. var THREE = require('../lib/three');
  46334. var trackedControlsUtils = require('../utils/tracked-controls');
  46335. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46336. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46337. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46338. // See Profiles Registry:
  46339. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  46340. // TODO: Add a more robust system for deriving gamepad name.
  46341. var GAMEPAD_ID = 'hp-mixed-reality';
  46342. var HP_MIXEDL_REALITY_MODEL_GLB_BASE_URL = 'https://cdn.aframe.io/controllers/hp/mixed-reality/';
  46343. var HP_MIXED_REALITY_POSITION_OFFSET = {x: 0, y: 0, z: 0.06};
  46344. var HP_MIXED_REALITY_ROTATION_OFFSET = {_x: Math.PI / 4, _y: 0, _z: 0, _order: 'XYZ'};
  46345. /**
  46346. * Button IDs:
  46347. * 0 - trigger
  46348. * 1 - grip
  46349. * 3 - X / A
  46350. * 4 - Y / B
  46351. *
  46352. * Axis:
  46353. * 2 - joystick x axis
  46354. * 3 - joystick y axis
  46355. */
  46356. var INPUT_MAPPING_WEBXR = {
  46357. left: {
  46358. axes: {touchpad: [2, 3]},
  46359. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton']
  46360. },
  46361. right: {
  46362. axes: {touchpad: [2, 3]},
  46363. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton']
  46364. }
  46365. };
  46366. /**
  46367. * HP Mixed Reality Controls
  46368. */
  46369. module.exports.Component = registerComponent('hp-mixed-reality-controls', {
  46370. schema: {
  46371. hand: {default: 'none'},
  46372. model: {default: true},
  46373. orientationOffset: {type: 'vec3'}
  46374. },
  46375. mapping: INPUT_MAPPING_WEBXR,
  46376. init: function () {
  46377. var self = this;
  46378. this.controllerPresent = false;
  46379. this.lastControllerCheck = 0;
  46380. this.onButtonChanged = bind(this.onButtonChanged, this);
  46381. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  46382. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  46383. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  46384. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  46385. this.previousButtonValues = {};
  46386. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46387. this.bindMethods();
  46388. },
  46389. update: function () {
  46390. var data = this.data;
  46391. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  46392. },
  46393. play: function () {
  46394. this.checkIfControllerPresent();
  46395. this.addControllersUpdateListener();
  46396. },
  46397. pause: function () {
  46398. this.removeEventListeners();
  46399. this.removeControllersUpdateListener();
  46400. },
  46401. bindMethods: function () {
  46402. this.onModelLoaded = bind(this.onModelLoaded, this);
  46403. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46404. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46405. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46406. this.onAxisMoved = bind(this.onAxisMoved, this);
  46407. },
  46408. addEventListeners: function () {
  46409. var el = this.el;
  46410. el.addEventListener('buttonchanged', this.onButtonChanged);
  46411. el.addEventListener('buttondown', this.onButtonDown);
  46412. el.addEventListener('buttonup', this.onButtonUp);
  46413. el.addEventListener('touchstart', this.onButtonTouchStart);
  46414. el.addEventListener('touchend', this.onButtonTouchEnd);
  46415. el.addEventListener('axismove', this.onAxisMoved);
  46416. el.addEventListener('model-loaded', this.onModelLoaded);
  46417. this.controllerEventsActive = true;
  46418. },
  46419. removeEventListeners: function () {
  46420. var el = this.el;
  46421. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46422. el.removeEventListener('buttondown', this.onButtonDown);
  46423. el.removeEventListener('buttonup', this.onButtonUp);
  46424. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46425. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46426. el.removeEventListener('axismove', this.onAxisMoved);
  46427. el.removeEventListener('model-loaded', this.onModelLoaded);
  46428. this.controllerEventsActive = false;
  46429. },
  46430. checkIfControllerPresent: function () {
  46431. var data = this.data;
  46432. checkControllerPresentAndSetup(this, GAMEPAD_ID,
  46433. {index: this.controllerIndex, hand: data.hand});
  46434. },
  46435. injectTrackedControls: function () {
  46436. var el = this.el;
  46437. var data = this.data;
  46438. el.setAttribute('tracked-controls', {
  46439. // TODO: verify expected behavior between reserved prefixes.
  46440. idPrefix: GAMEPAD_ID,
  46441. hand: data.hand,
  46442. controller: this.controllerIndex,
  46443. orientationOffset: data.orientationOffset
  46444. });
  46445. // Load model.
  46446. if (!this.data.model) { return; }
  46447. this.el.setAttribute('gltf-model', HP_MIXEDL_REALITY_MODEL_GLB_BASE_URL + this.data.hand + '.glb');
  46448. },
  46449. addControllersUpdateListener: function () {
  46450. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46451. },
  46452. removeControllersUpdateListener: function () {
  46453. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46454. },
  46455. onControllersUpdate: function () {
  46456. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  46457. this.checkIfControllerPresent();
  46458. },
  46459. onButtonChanged: function (evt) {
  46460. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  46461. var analogValue;
  46462. if (!button) { return; }
  46463. if (button === 'trigger') {
  46464. analogValue = evt.detail.state.value;
  46465. console.log('analog value of trigger press: ' + analogValue);
  46466. }
  46467. // Pass along changed event with button state, using button mapping for convenience.
  46468. this.el.emit(button + 'changed', evt.detail.state);
  46469. },
  46470. onModelLoaded: function (evt) {
  46471. var controllerObject3D = evt.detail.model;
  46472. if (!this.data.model) { return; }
  46473. controllerObject3D.position.copy(HP_MIXED_REALITY_POSITION_OFFSET);
  46474. controllerObject3D.rotation.copy(HP_MIXED_REALITY_ROTATION_OFFSET);
  46475. this.el.emit('controllermodelready', {
  46476. name: 'hp-mixed-reality-controls',
  46477. model: this.data.model,
  46478. rayOrigin: new THREE.Vector3(0, 0, 0)
  46479. });
  46480. },
  46481. onAxisMoved: function (evt) {
  46482. emitIfAxesChanged(this, this.mapping.axes, evt);
  46483. }
  46484. });
  46485. },{"../core/component":135,"../lib/three":183,"../utils/bind":204,"../utils/tracked-controls":219}],87:[function(require,module,exports){
  46486. require('./animation');
  46487. require('./camera');
  46488. require('./cursor');
  46489. require('./daydream-controls');
  46490. require('./gearvr-controls');
  46491. require('./geometry');
  46492. require('./generic-tracked-controller-controls');
  46493. require('./gltf-model');
  46494. require('./hand-tracking-controls');
  46495. require('./hand-controls');
  46496. require('./hide-on-enter-ar');
  46497. require('./hp-mixed-reality-controls');
  46498. require('./layer');
  46499. require('./laser-controls');
  46500. require('./light');
  46501. require('./line');
  46502. require('./link');
  46503. require('./look-controls');
  46504. require('./magicleap-controls');
  46505. require('./material');
  46506. require('./obj-model');
  46507. require('./oculus-go-controls');
  46508. require('./oculus-touch-controls');
  46509. require('./position');
  46510. require('./raycaster');
  46511. require('./rotation');
  46512. require('./scale');
  46513. require('./shadow');
  46514. require('./sound');
  46515. require('./text');
  46516. require('./tracked-controls');
  46517. require('./tracked-controls-webvr');
  46518. require('./tracked-controls-webxr');
  46519. require('./visible');
  46520. require('./valve-index-controls');
  46521. require('./vive-controls');
  46522. require('./vive-focus-controls');
  46523. require('./wasd-controls');
  46524. require('./windows-motion-controls');
  46525. require('./scene/ar-hit-test');
  46526. require('./scene/background');
  46527. require('./scene/debug');
  46528. require('./scene/device-orientation-permission-ui');
  46529. require('./scene/embedded');
  46530. require('./scene/inspector');
  46531. require('./scene/fog');
  46532. require('./scene/keyboard-shortcuts');
  46533. require('./scene/pool');
  46534. require('./scene/screenshot');
  46535. require('./scene/stats');
  46536. require('./scene/vr-mode-ui');
  46537. },{"./animation":75,"./camera":76,"./cursor":77,"./daydream-controls":78,"./gearvr-controls":79,"./generic-tracked-controller-controls":80,"./geometry":81,"./gltf-model":82,"./hand-controls":83,"./hand-tracking-controls":84,"./hide-on-enter-ar":85,"./hp-mixed-reality-controls":86,"./laser-controls":88,"./layer":89,"./light":90,"./line":91,"./link":92,"./look-controls":93,"./magicleap-controls":94,"./material":95,"./obj-model":96,"./oculus-go-controls":97,"./oculus-touch-controls":98,"./position":99,"./raycaster":100,"./rotation":101,"./scale":102,"./scene/ar-hit-test":103,"./scene/background":104,"./scene/debug":105,"./scene/device-orientation-permission-ui":106,"./scene/embedded":107,"./scene/fog":108,"./scene/inspector":109,"./scene/keyboard-shortcuts":110,"./scene/pool":111,"./scene/screenshot":112,"./scene/stats":113,"./scene/vr-mode-ui":114,"./shadow":115,"./sound":116,"./text":117,"./tracked-controls":120,"./tracked-controls-webvr":118,"./tracked-controls-webxr":119,"./valve-index-controls":121,"./visible":122,"./vive-controls":123,"./vive-focus-controls":124,"./wasd-controls":125,"./windows-motion-controls":126}],88:[function(require,module,exports){
  46538. var registerComponent = require('../core/component').registerComponent;
  46539. var utils = require('../utils/');
  46540. registerComponent('laser-controls', {
  46541. schema: {
  46542. hand: {default: 'right'},
  46543. model: {default: true},
  46544. defaultModelColor: {type: 'color', default: 'grey'}
  46545. },
  46546. init: function () {
  46547. var config = this.config;
  46548. var data = this.data;
  46549. var el = this.el;
  46550. var self = this;
  46551. var controlsConfiguration = {hand: data.hand, model: data.model};
  46552. // Set all controller models.
  46553. el.setAttribute('daydream-controls', controlsConfiguration);
  46554. el.setAttribute('gearvr-controls', controlsConfiguration);
  46555. el.setAttribute('hp-mixed-reality-controls', controlsConfiguration);
  46556. el.setAttribute('magicleap-controls', controlsConfiguration);
  46557. el.setAttribute('oculus-go-controls', controlsConfiguration);
  46558. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  46559. el.setAttribute('valve-index-controls', controlsConfiguration);
  46560. el.setAttribute('vive-controls', controlsConfiguration);
  46561. el.setAttribute('vive-focus-controls', controlsConfiguration);
  46562. el.setAttribute('windows-motion-controls', controlsConfiguration);
  46563. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  46564. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  46565. el.addEventListener('controllerconnected', createRay);
  46566. el.addEventListener('controllerdisconnected', hideRay);
  46567. el.addEventListener('controllermodelready', function (evt) {
  46568. createRay(evt);
  46569. self.modelReady = true;
  46570. });
  46571. function createRay (evt) {
  46572. var controllerConfig = config[evt.detail.name];
  46573. if (!controllerConfig) { return; }
  46574. // Show the line unless a particular config opts to hide it, until a controllermodelready
  46575. // event comes through.
  46576. var raycasterConfig = utils.extend({
  46577. showLine: true
  46578. }, controllerConfig.raycaster || {});
  46579. // The controllermodelready event contains a rayOrigin that takes into account
  46580. // offsets specific to the loaded model.
  46581. if (evt.detail.rayOrigin) {
  46582. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  46583. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  46584. raycasterConfig.showLine = true;
  46585. }
  46586. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  46587. // config applied from a controllermodelready event.
  46588. if (evt.detail.rayOrigin || !self.modelReady) {
  46589. el.setAttribute('raycaster', raycasterConfig);
  46590. } else {
  46591. el.setAttribute('raycaster', 'showLine', true);
  46592. }
  46593. el.setAttribute('cursor', utils.extend({
  46594. fuse: false
  46595. }, controllerConfig.cursor));
  46596. }
  46597. function hideRay () {
  46598. el.setAttribute('raycaster', 'showLine', false);
  46599. }
  46600. },
  46601. config: {
  46602. 'daydream-controls': {
  46603. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46604. },
  46605. 'gearvr-controls': {
  46606. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46607. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  46608. },
  46609. 'generic-tracked-controller-controls': {
  46610. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46611. },
  46612. 'hp-mixed-reality-controls': {
  46613. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46614. raycaster: {origin: {x: 0, y: 0, z: 0}}
  46615. },
  46616. 'magicleap-controls': {
  46617. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46618. },
  46619. 'oculus-go-controls': {
  46620. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46621. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  46622. },
  46623. 'oculus-touch-controls': {
  46624. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46625. raycaster: {origin: {x: 0, y: 0, z: 0}}
  46626. },
  46627. 'valve-index-controls': {
  46628. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46629. },
  46630. 'vive-controls': {
  46631. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  46632. },
  46633. 'vive-focus-controls': {
  46634. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  46635. },
  46636. 'windows-motion-controls': {
  46637. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  46638. raycaster: {showLine: false}
  46639. }
  46640. }
  46641. });
  46642. },{"../core/component":135,"../utils/":210}],89:[function(require,module,exports){
  46643. /* global THREE, XRRigidTransform, XRWebGLBinding */
  46644. var registerComponent = require('../core/component').registerComponent;
  46645. var utils = require('../utils/');
  46646. var warn = utils.debug('components:layer:warn');
  46647. module.exports.Component = registerComponent('layer', {
  46648. schema: {
  46649. type: {default: 'quad', oneOf: ['quad', 'monocubemap', 'stereocubemap']},
  46650. src: {type: 'map'},
  46651. rotateCubemap: {default: false},
  46652. width: {default: 0},
  46653. height: {default: 0}
  46654. },
  46655. init: function () {
  46656. var gl = this.el.sceneEl.renderer.getContext();
  46657. this.quaternion = new THREE.Quaternion();
  46658. this.position = new THREE.Vector3();
  46659. this.bindMethods();
  46660. this.needsRedraw = false;
  46661. this.frameBuffer = gl.createFramebuffer();
  46662. var requiredFeatures = this.el.sceneEl.getAttribute('webxr').requiredFeatures;
  46663. requiredFeatures.push('layers');
  46664. this.el.sceneEl.getAttribute('webxr', 'requiredFeatures', requiredFeatures);
  46665. this.el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  46666. this.el.sceneEl.addEventListener('exit-vr', this.onExitVR);
  46667. },
  46668. bindMethods: function () {
  46669. this.onRequestedReferenceSpace = this.onRequestedReferenceSpace.bind(this);
  46670. this.onEnterVR = this.onEnterVR.bind(this);
  46671. this.onExitVR = this.onExitVR.bind(this);
  46672. },
  46673. update: function (oldData) {
  46674. if (this.data.src !== oldData.src) { this.updateSrc(); }
  46675. },
  46676. updateSrc: function () {
  46677. var type = this.data.type;
  46678. this.texture = undefined;
  46679. if (type === 'quad') {
  46680. this.loadQuadImage();
  46681. return;
  46682. }
  46683. if (type === 'monocubemap' || type === 'stereocubemap') {
  46684. this.loadCubeMapImages();
  46685. return;
  46686. }
  46687. },
  46688. loadCubeMapImages: function () {
  46689. var type = this.data.type;
  46690. var glayer;
  46691. var xrGLFactory = this.xrGLFactory;
  46692. var frame = this.el.sceneEl.frame;
  46693. var src = this.data.src;
  46694. this.visibilityChanged = false;
  46695. if (!this.layer) { return; }
  46696. if (!src.complete) {
  46697. this.pendingCubeMapUpdate = true;
  46698. } else {
  46699. this.pendingCubeMapUpdate = false;
  46700. }
  46701. if (!this.loadingScreen) {
  46702. this.loadingScreen = true;
  46703. } else {
  46704. this.loadingScreen = false;
  46705. }
  46706. if (type === 'monocubemap') {
  46707. glayer = xrGLFactory.getSubImage(this.layer, frame);
  46708. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  46709. } else {
  46710. glayer = xrGLFactory.getSubImage(this.layer, frame, 'left');
  46711. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  46712. glayer = xrGLFactory.getSubImage(this.layer, frame, 'right');
  46713. this.loadCubeMapImage(glayer.colorTexture, src, 6);
  46714. }
  46715. },
  46716. loadQuadImage: function () {
  46717. var src = this.data.src;
  46718. var self = this;
  46719. this.el.sceneEl.systems.material.loadTexture(src, {src: src}, function textureLoaded (texture) {
  46720. self.el.sceneEl.renderer.initTexture(texture);
  46721. self.texture = texture;
  46722. if (src.tagName === 'VIDEO') { setTimeout(function () { self.textureIsVideo = true; }, 1000); }
  46723. if (self.layer) {
  46724. self.layer.height = self.data.height / 2 || self.texture.image.height / 1000;
  46725. self.layer.width = self.data.width / 2 || self.texture.image.width / 1000;
  46726. self.needsRedraw = true;
  46727. }
  46728. self.updateQuadPanel();
  46729. });
  46730. },
  46731. preGenerateCubeMapTextures: function (src, callback) {
  46732. if (this.data.type === 'monocubemap') {
  46733. this.generateCubeMapTextures(src, 0, callback);
  46734. } else {
  46735. this.generateCubeMapTextures(src, 0, callback);
  46736. this.generateCubeMapTextures(src, 6, callback);
  46737. }
  46738. },
  46739. generateCubeMapTextures: function (src, faceOffset, callback) {
  46740. var data = this.data;
  46741. var cubeFaceSize = this.cubeFaceSize;
  46742. var textureSourceCubeFaceSize = Math.min(src.width, src.height);
  46743. var cubefaceTextures = [];
  46744. var imgTmp0;
  46745. var imgTmp2;
  46746. for (var i = 0; i < 6; i++) {
  46747. var tempCanvas = document.createElement('CANVAS');
  46748. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  46749. var tempCanvasContext = tempCanvas.getContext('2d');
  46750. if (data.rotateCubemap) {
  46751. if (i === 2 || i === 3) {
  46752. tempCanvasContext.save();
  46753. tempCanvasContext.translate(cubeFaceSize, cubeFaceSize);
  46754. tempCanvasContext.rotate(Math.PI);
  46755. }
  46756. }
  46757. // Note that this call to drawImage will not only copy the bytes to the
  46758. // canvas but also could resized the image if our cube face size is
  46759. // smaller than the source image due to GL max texture size.
  46760. tempCanvasContext.drawImage(
  46761. src,
  46762. (i + faceOffset) * textureSourceCubeFaceSize, // top left x coord in source
  46763. 0, // top left y coord in source
  46764. textureSourceCubeFaceSize, // x pixel count from source
  46765. textureSourceCubeFaceSize, // y pixel count from source
  46766. 0, // dest x offset in the canvas
  46767. 0, // dest y offset in the canvas
  46768. cubeFaceSize, // x pixel count in dest
  46769. cubeFaceSize // y pixel count in dest
  46770. );
  46771. tempCanvasContext.restore();
  46772. if (callback) { callback(); }
  46773. cubefaceTextures.push(tempCanvas);
  46774. }
  46775. if (data.rotateCubemap) {
  46776. imgTmp0 = cubefaceTextures[0];
  46777. imgTmp2 = cubefaceTextures[1];
  46778. cubefaceTextures[0] = imgTmp2;
  46779. cubefaceTextures[1] = imgTmp0;
  46780. imgTmp0 = cubefaceTextures[4];
  46781. imgTmp2 = cubefaceTextures[5];
  46782. cubefaceTextures[4] = imgTmp2;
  46783. cubefaceTextures[5] = imgTmp0;
  46784. }
  46785. if (callback) { callback(); }
  46786. return cubefaceTextures;
  46787. },
  46788. loadCubeMapImage: function (layerColorTexture, src, faceOffset) {
  46789. var gl = this.el.sceneEl.renderer.getContext();
  46790. var cubefaceTextures;
  46791. // dont flip the pixels as we load them into the texture buffer.
  46792. // TEXTURE_CUBE_MAP expects the Y to be flipped for the faces and it already
  46793. // is flipped in our texture image.
  46794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  46795. gl.bindTexture(gl.TEXTURE_CUBE_MAP, layerColorTexture);
  46796. if (!src.complete || this.loadingScreen) {
  46797. cubefaceTextures = this.loadingScreenImages;
  46798. } else {
  46799. cubefaceTextures = this.generateCubeMapTextures(src, faceOffset);
  46800. }
  46801. var errorCode = 0;
  46802. cubefaceTextures.forEach(function (canvas, i) {
  46803. gl.texSubImage2D(
  46804. gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,
  46805. 0,
  46806. 0, 0,
  46807. gl.RGBA,
  46808. gl.UNSIGNED_BYTE,
  46809. canvas
  46810. );
  46811. errorCode = gl.getError();
  46812. });
  46813. if (errorCode !== 0) {
  46814. console.log('renderingError, WebGL Error Code: ' + errorCode);
  46815. }
  46816. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  46817. },
  46818. tick: function () {
  46819. if (!this.el.sceneEl.xrSession) { return; }
  46820. if (!this.layer && this.el.sceneEl.is('vr-mode')) { this.initLayer(); }
  46821. this.updateTransform();
  46822. if (this.data.src.complete && (this.pendingCubeMapUpdate || this.loadingScreen || this.visibilityChanged)) { this.loadCubeMapImages(); }
  46823. if (!this.needsRedraw && !this.layer.needsRedraw && !this.textureIsVideo) { return; }
  46824. if (this.data.type === 'quad') { this.draw(); }
  46825. this.needsRedraw = false;
  46826. },
  46827. initLayer: function () {
  46828. var self = this;
  46829. var type = this.data.type;
  46830. this.el.sceneEl.xrSession.onvisibilitychange = function (evt) {
  46831. self.visibilityChanged = evt.session.visibilityState !== 'hidden';
  46832. };
  46833. if (type === 'quad') {
  46834. this.initQuadLayer();
  46835. return;
  46836. }
  46837. if (type === 'monocubemap' || type === 'stereocubemap') {
  46838. this.initCubeMapLayer();
  46839. return;
  46840. }
  46841. },
  46842. initQuadLayer: function () {
  46843. var sceneEl = this.el.sceneEl;
  46844. var gl = sceneEl.renderer.getContext();
  46845. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  46846. if (!this.texture) { return; }
  46847. this.layer = xrGLFactory.createQuadLayer({
  46848. space: this.referenceSpace,
  46849. viewPixelHeight: 2048,
  46850. viewPixelWidth: 2048,
  46851. height: this.data.height / 2 || this.texture.image.height / 1000,
  46852. width: this.data.width / 2 || this.texture.image.width / 1000
  46853. });
  46854. sceneEl.renderer.xr.addLayer(this.layer);
  46855. },
  46856. initCubeMapLayer: function () {
  46857. var src = this.data.src;
  46858. var sceneEl = this.el.sceneEl;
  46859. var gl = sceneEl.renderer.getContext();
  46860. var glSizeLimit = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  46861. var cubeFaceSize = this.cubeFaceSize = Math.min(glSizeLimit, Math.min(src.width, src.height));
  46862. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  46863. this.layer = xrGLFactory.createCubeLayer({
  46864. space: this.referenceSpace,
  46865. viewPixelWidth: cubeFaceSize,
  46866. viewPixelHeight: cubeFaceSize,
  46867. layout: this.data.type === 'monocubemap' ? 'mono' : 'stereo',
  46868. isStatic: false
  46869. });
  46870. this.initLoadingScreenImages();
  46871. this.loadCubeMapImages();
  46872. sceneEl.renderer.xr.addLayer(this.layer);
  46873. },
  46874. initLoadingScreenImages: function () {
  46875. var cubeFaceSize = this.cubeFaceSize;
  46876. var loadingScreenImages = this.loadingScreenImages = [];
  46877. for (var i = 0; i < 6; i++) {
  46878. var tempCanvas = document.createElement('CANVAS');
  46879. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  46880. var tempCanvasContext = tempCanvas.getContext('2d');
  46881. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  46882. tempCanvasContext.fillStyle = 'black';
  46883. tempCanvasContext.fillRect(0, 0, cubeFaceSize, cubeFaceSize);
  46884. if (i !== 2 && i !== 3) {
  46885. tempCanvasContext.translate(cubeFaceSize, 0);
  46886. tempCanvasContext.scale(-1, 1);
  46887. tempCanvasContext.fillStyle = 'white';
  46888. tempCanvasContext.font = '30px Arial';
  46889. tempCanvasContext.fillText('Loading', cubeFaceSize / 2, cubeFaceSize / 2);
  46890. }
  46891. loadingScreenImages.push(tempCanvas);
  46892. }
  46893. },
  46894. destroyLayer: function () {
  46895. if (!this.layer) { return; }
  46896. this.el.sceneEl.renderer.xr.removeLayer(this.layer);
  46897. this.layer.destroy();
  46898. this.layer = undefined;
  46899. },
  46900. toggleCompositorLayer: function () {
  46901. this.enableCompositorLayer(!this.layerEnabled);
  46902. },
  46903. enableCompositorLayer: function (enable) {
  46904. this.layerEnabled = enable;
  46905. this.quadPanelEl.object3D.visible = !this.layerEnabled;
  46906. },
  46907. updateQuadPanel: function () {
  46908. var quadPanelEl = this.quadPanelEl;
  46909. if (!this.quadPanelEl) {
  46910. quadPanelEl = this.quadPanelEl = document.createElement('a-entity');
  46911. this.el.appendChild(quadPanelEl);
  46912. }
  46913. quadPanelEl.setAttribute('material', {
  46914. shader: 'flat',
  46915. src: this.data.src,
  46916. transparent: true
  46917. });
  46918. quadPanelEl.setAttribute('geometry', {
  46919. primitive: 'plane',
  46920. height: this.data.height || this.texture.image.height / 1000,
  46921. width: this.data.width || this.texture.image.height / 1000
  46922. });
  46923. },
  46924. draw: function () {
  46925. var sceneEl = this.el.sceneEl;
  46926. var gl = this.el.sceneEl.renderer.getContext();
  46927. var glayer = this.xrGLFactory.getSubImage(this.layer, sceneEl.frame);
  46928. var texture = sceneEl.renderer.properties.get(this.texture).__webglTexture;
  46929. var previousFrameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  46930. gl.viewport(glayer.viewport.x, glayer.viewport.y, glayer.viewport.width, glayer.viewport.height);
  46931. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer);
  46932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glayer.colorTexture, 0);
  46933. blitTexture(gl, texture, glayer, this.data.src);
  46934. gl.bindFramebuffer(gl.FRAMEBUFFER, previousFrameBuffer);
  46935. },
  46936. updateTransform: function () {
  46937. var el = this.el;
  46938. var position = this.position;
  46939. var quaternion = this.quaternion;
  46940. el.object3D.updateMatrixWorld();
  46941. position.setFromMatrixPosition(el.object3D.matrixWorld);
  46942. quaternion.setFromRotationMatrix(el.object3D.matrixWorld);
  46943. if (!this.layerEnabled) { position.set(0, 0, 100000000); }
  46944. this.layer.transform = new XRRigidTransform(position, quaternion);
  46945. },
  46946. onEnterVR: function () {
  46947. var sceneEl = this.el.sceneEl;
  46948. var xrSession = sceneEl.xrSession;
  46949. if (!sceneEl.hasWebXR || !XRWebGLBinding || !xrSession) {
  46950. warn('The layer component requires WebXR and the layers API enabled');
  46951. return;
  46952. }
  46953. xrSession.requestReferenceSpace('local').then(this.onRequestedReferenceSpace);
  46954. this.needsRedraw = true;
  46955. this.layerEnabled = true;
  46956. if (this.quadPanelEl) {
  46957. this.quadPanelEl.object3D.visible = false;
  46958. }
  46959. if (this.data.src.play) { this.data.src.play(); }
  46960. },
  46961. onExitVR: function () {
  46962. if (this.quadPanelEl) {
  46963. this.quadPanelEl.object3D.visible = true;
  46964. }
  46965. this.destroyLayer();
  46966. },
  46967. onRequestedReferenceSpace: function (referenceSpace) {
  46968. this.referenceSpace = referenceSpace;
  46969. }
  46970. });
  46971. function blitTexture (gl, texture, subImage, textureEl) {
  46972. var xrReadFramebuffer = gl.createFramebuffer();
  46973. let x1offset = subImage.viewport.x;
  46974. let y1offset = subImage.viewport.y;
  46975. let x2offset = subImage.viewport.x + subImage.viewport.width;
  46976. let y2offset = subImage.viewport.y + subImage.viewport.height;
  46977. // Update video texture.
  46978. if (textureEl.tagName === 'VIDEO') {
  46979. gl.bindTexture(gl.TEXTURE_2D, texture);
  46980. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, textureEl.width, textureEl.height, gl.RGB, gl.UNSIGNED_BYTE, textureEl);
  46981. }
  46982. // Bind texture to read framebuffer.
  46983. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, xrReadFramebuffer);
  46984. gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  46985. // Blit into layer buffer.
  46986. gl.readBuffer(gl.COLOR_ATTACHMENT0);
  46987. gl.blitFramebuffer(0, 0, textureEl.width, textureEl.height, x1offset, y1offset, x2offset, y2offset, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  46988. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  46989. gl.deleteFramebuffer(xrReadFramebuffer);
  46990. }
  46991. },{"../core/component":135,"../utils/":210}],90:[function(require,module,exports){
  46992. var bind = require('../utils/bind');
  46993. var utils = require('../utils');
  46994. var diff = utils.diff;
  46995. var debug = require('../utils/debug');
  46996. var registerComponent = require('../core/component').registerComponent;
  46997. var THREE = require('../lib/three');
  46998. var degToRad = THREE.Math.degToRad;
  46999. var warn = debug('components:light:warn');
  47000. var CubeLoader = new THREE.CubeTextureLoader();
  47001. var probeCache = {};
  47002. /**
  47003. * Light component.
  47004. */
  47005. module.exports.Component = registerComponent('light', {
  47006. schema: {
  47007. angle: {default: 60, if: {type: ['spot']}},
  47008. color: {type: 'color', if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  47009. envMap: {default: '', if: {type: ['probe']}},
  47010. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  47011. decay: {default: 1, if: {type: ['point', 'spot']}},
  47012. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  47013. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot', 'probe']}},
  47014. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  47015. type: {
  47016. default: 'directional',
  47017. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot', 'probe'],
  47018. schemaChange: true
  47019. },
  47020. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  47021. // Shadows.
  47022. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  47023. shadowBias: {default: 0, if: {castShadow: true}},
  47024. shadowCameraFar: {default: 500, if: {castShadow: true}},
  47025. shadowCameraFov: {default: 90, if: {castShadow: true}},
  47026. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  47027. shadowCameraTop: {default: 5, if: {castShadow: true}},
  47028. shadowCameraRight: {default: 5, if: {castShadow: true}},
  47029. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  47030. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  47031. shadowCameraVisible: {default: false, if: {castShadow: true}},
  47032. shadowMapHeight: {default: 512, if: {castShadow: true}},
  47033. shadowMapWidth: {default: 512, if: {castShadow: true}},
  47034. shadowRadius: {default: 1, if: {castShadow: true}}
  47035. },
  47036. /**
  47037. * Notifies scene a light has been added to remove default lighting.
  47038. */
  47039. init: function () {
  47040. var el = this.el;
  47041. this.light = null;
  47042. this.defaultTarget = null;
  47043. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47044. this.system.registerLight(el);
  47045. },
  47046. /**
  47047. * (Re)create or update light.
  47048. */
  47049. update: function (oldData) {
  47050. var data = this.data;
  47051. var diffData = diff(data, oldData);
  47052. var light = this.light;
  47053. var rendererSystem = this.rendererSystem;
  47054. var self = this;
  47055. // Existing light.
  47056. if (light && !('type' in diffData)) {
  47057. var shadowsLoaded = false;
  47058. // Light type has not changed. Update light.
  47059. Object.keys(diffData).forEach(function (key) {
  47060. var value = data[key];
  47061. switch (key) {
  47062. case 'color': {
  47063. light.color.set(value);
  47064. rendererSystem.applyColorCorrection(light.color);
  47065. break;
  47066. }
  47067. case 'groundColor': {
  47068. light.groundColor.set(value);
  47069. rendererSystem.applyColorCorrection(light.groundColor);
  47070. break;
  47071. }
  47072. case 'angle': {
  47073. light.angle = degToRad(value);
  47074. break;
  47075. }
  47076. case 'target': {
  47077. // Reset target if selector is null.
  47078. if (value === null) {
  47079. if (data.type === 'spot' || data.type === 'directional') {
  47080. light.target = self.defaultTarget;
  47081. }
  47082. } else {
  47083. // Target specified, set target to entity's `object3D` when it is loaded.
  47084. if (value.hasLoaded) {
  47085. self.onSetTarget(value, light);
  47086. } else {
  47087. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  47088. }
  47089. }
  47090. break;
  47091. }
  47092. case 'envMap':
  47093. this.updateProbeMap(data, light);
  47094. break;
  47095. case 'castShadow':
  47096. case 'shadowBias':
  47097. case 'shadowCameraFar':
  47098. case 'shadowCameraFov':
  47099. case 'shadowCameraNear':
  47100. case 'shadowCameraTop':
  47101. case 'shadowCameraRight':
  47102. case 'shadowCameraBottom':
  47103. case 'shadowCameraLeft':
  47104. case 'shadowCameraVisible':
  47105. case 'shadowMapHeight':
  47106. case 'shadowMapWidth':
  47107. case 'shadowRadius':
  47108. if (!shadowsLoaded) {
  47109. self.updateShadow();
  47110. shadowsLoaded = true;
  47111. }
  47112. break;
  47113. default: {
  47114. light[key] = value;
  47115. }
  47116. }
  47117. });
  47118. return;
  47119. }
  47120. // No light yet or light type has changed. Create and add light.
  47121. this.setLight(this.data);
  47122. this.updateShadow();
  47123. },
  47124. setLight: function (data) {
  47125. var el = this.el;
  47126. var newLight = this.getLight(data);
  47127. if (newLight) {
  47128. if (this.light) {
  47129. el.removeObject3D('light');
  47130. }
  47131. this.light = newLight;
  47132. this.light.el = el;
  47133. el.setObject3D('light', this.light);
  47134. // HACK solution for issue #1624
  47135. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  47136. el.getObject3D('light').translateY(-1);
  47137. }
  47138. // set and position default lighttarget as a child to enable spotlight orientation
  47139. if (data.type === 'spot') {
  47140. el.setObject3D('light-target', this.defaultTarget);
  47141. el.getObject3D('light-target').position.set(0, 0, -1);
  47142. }
  47143. }
  47144. },
  47145. /**
  47146. * Updates shadow-related properties on the current light.
  47147. */
  47148. updateShadow: function () {
  47149. var el = this.el;
  47150. var data = this.data;
  47151. var light = this.light;
  47152. light.castShadow = data.castShadow;
  47153. // Shadow camera helper.
  47154. var cameraHelper = el.getObject3D('cameraHelper');
  47155. if (data.shadowCameraVisible && !cameraHelper) {
  47156. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  47157. } else if (!data.shadowCameraVisible && cameraHelper) {
  47158. el.removeObject3D('cameraHelper');
  47159. }
  47160. if (!data.castShadow) { return light; }
  47161. // Shadow appearance.
  47162. light.shadow.bias = data.shadowBias;
  47163. light.shadow.radius = data.shadowRadius;
  47164. light.shadow.mapSize.height = data.shadowMapHeight;
  47165. light.shadow.mapSize.width = data.shadowMapWidth;
  47166. // Shadow camera.
  47167. light.shadow.camera.near = data.shadowCameraNear;
  47168. light.shadow.camera.far = data.shadowCameraFar;
  47169. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  47170. light.shadow.camera.top = data.shadowCameraTop;
  47171. light.shadow.camera.right = data.shadowCameraRight;
  47172. light.shadow.camera.bottom = data.shadowCameraBottom;
  47173. light.shadow.camera.left = data.shadowCameraLeft;
  47174. } else {
  47175. light.shadow.camera.fov = data.shadowCameraFov;
  47176. }
  47177. light.shadow.camera.updateProjectionMatrix();
  47178. if (cameraHelper) { cameraHelper.update(); }
  47179. },
  47180. /**
  47181. * Creates a new three.js light object given data object defining the light.
  47182. *
  47183. * @param {object} data
  47184. */
  47185. getLight: function (data) {
  47186. var angle = data.angle;
  47187. var color = new THREE.Color(data.color);
  47188. this.rendererSystem.applyColorCorrection(color);
  47189. color = color.getHex();
  47190. var decay = data.decay;
  47191. var distance = data.distance;
  47192. var groundColor = new THREE.Color(data.groundColor);
  47193. this.rendererSystem.applyColorCorrection(groundColor);
  47194. groundColor = groundColor.getHex();
  47195. var intensity = data.intensity;
  47196. var type = data.type;
  47197. var target = data.target;
  47198. var light = null;
  47199. switch (type.toLowerCase()) {
  47200. case 'ambient': {
  47201. return new THREE.AmbientLight(color, intensity);
  47202. }
  47203. case 'directional': {
  47204. light = new THREE.DirectionalLight(color, intensity);
  47205. this.defaultTarget = light.target;
  47206. if (target) {
  47207. if (target.hasLoaded) {
  47208. this.onSetTarget(target, light);
  47209. } else {
  47210. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  47211. }
  47212. }
  47213. return light;
  47214. }
  47215. case 'hemisphere': {
  47216. return new THREE.HemisphereLight(color, groundColor, intensity);
  47217. }
  47218. case 'point': {
  47219. return new THREE.PointLight(color, intensity, distance, decay);
  47220. }
  47221. case 'spot': {
  47222. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  47223. this.defaultTarget = light.target;
  47224. if (target) {
  47225. if (target.hasLoaded) {
  47226. this.onSetTarget(target, light);
  47227. } else {
  47228. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  47229. }
  47230. }
  47231. return light;
  47232. }
  47233. case 'probe': {
  47234. light = new THREE.LightProbe();
  47235. this.updateProbeMap(data, light);
  47236. return light;
  47237. }
  47238. default: {
  47239. warn('%s is not a valid light type. ' +
  47240. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  47241. }
  47242. }
  47243. },
  47244. /**
  47245. * Generate the spherical harmonics for the LightProbe from a cube map
  47246. */
  47247. updateProbeMap: function (data, light) {
  47248. if (!data.envMap) {
  47249. // reset parameters if no map
  47250. light.copy(new THREE.LightProbe());
  47251. }
  47252. if (probeCache[data.envMap] instanceof window.Promise) {
  47253. probeCache[data.envMap].then(function (tempLightProbe) {
  47254. light.copy(tempLightProbe);
  47255. });
  47256. }
  47257. if (probeCache[data.envMap] instanceof THREE.LightProbe) {
  47258. light.copy(probeCache[data.envMap]);
  47259. }
  47260. probeCache[data.envMap] = new window.Promise(function (resolve) {
  47261. utils.srcLoader.validateCubemapSrc(data.envMap, function loadEnvMap (urls) {
  47262. CubeLoader.load(urls, function (cube) {
  47263. var tempLightProbe = THREE.LightProbeGenerator.fromCubeTexture(cube);
  47264. probeCache[data.envMap] = tempLightProbe;
  47265. light.copy(tempLightProbe);
  47266. });
  47267. });
  47268. });
  47269. },
  47270. onSetTarget: function (targetEl, light) {
  47271. light.target = targetEl.object3D;
  47272. },
  47273. /**
  47274. * Remove light on remove (callback).
  47275. */
  47276. remove: function () {
  47277. var el = this.el;
  47278. el.removeObject3D('light');
  47279. if (el.getObject3D('cameraHelper')) {
  47280. el.removeObject3D('cameraHelper');
  47281. }
  47282. }
  47283. });
  47284. },{"../core/component":135,"../lib/three":183,"../utils":210,"../utils/bind":204,"../utils/debug":206}],91:[function(require,module,exports){
  47285. /* global THREE */
  47286. var registerComponent = require('../core/component').registerComponent;
  47287. module.exports.Component = registerComponent('line', {
  47288. schema: {
  47289. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  47290. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  47291. color: {type: 'color', default: '#74BEC1'},
  47292. opacity: {type: 'number', default: 1},
  47293. visible: {default: true}
  47294. },
  47295. multiple: true,
  47296. init: function () {
  47297. var data = this.data;
  47298. var geometry;
  47299. var material;
  47300. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47301. material = this.material = new THREE.LineBasicMaterial({
  47302. color: data.color,
  47303. opacity: data.opacity,
  47304. transparent: data.opacity < 1,
  47305. visible: data.visible
  47306. });
  47307. geometry = this.geometry = new THREE.BufferGeometry();
  47308. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  47309. this.rendererSystem.applyColorCorrection(material.color);
  47310. this.line = new THREE.Line(geometry, material);
  47311. this.el.setObject3D(this.attrName, this.line);
  47312. },
  47313. update: function (oldData) {
  47314. var data = this.data;
  47315. var geometry = this.geometry;
  47316. var geoNeedsUpdate = false;
  47317. var material = this.material;
  47318. var positionArray = geometry.attributes.position.array;
  47319. // Update geometry.
  47320. if (!isEqualVec3(data.start, oldData.start)) {
  47321. positionArray[0] = data.start.x;
  47322. positionArray[1] = data.start.y;
  47323. positionArray[2] = data.start.z;
  47324. geoNeedsUpdate = true;
  47325. }
  47326. if (!isEqualVec3(data.end, oldData.end)) {
  47327. positionArray[3] = data.end.x;
  47328. positionArray[4] = data.end.y;
  47329. positionArray[5] = data.end.z;
  47330. geoNeedsUpdate = true;
  47331. }
  47332. if (geoNeedsUpdate) {
  47333. geometry.attributes.position.needsUpdate = true;
  47334. geometry.computeBoundingSphere();
  47335. }
  47336. material.color.setStyle(data.color);
  47337. this.rendererSystem.applyColorCorrection(material.color);
  47338. material.opacity = data.opacity;
  47339. material.transparent = data.opacity < 1;
  47340. material.visible = data.visible;
  47341. },
  47342. remove: function () {
  47343. this.el.removeObject3D('line', this.line);
  47344. }
  47345. });
  47346. function isEqualVec3 (a, b) {
  47347. if (!a || !b) { return false; }
  47348. return (a.x === b.x && a.y === b.y && a.z === b.z);
  47349. }
  47350. },{"../core/component":135}],92:[function(require,module,exports){
  47351. var registerComponent = require('../core/component').registerComponent;
  47352. var registerShader = require('../core/shader').registerShader;
  47353. var THREE = require('../lib/three');
  47354. /**
  47355. * Link component. Connect experiences and traverse between them in VR
  47356. *
  47357. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  47358. */
  47359. module.exports.Component = registerComponent('link', {
  47360. schema: {
  47361. backgroundColor: {default: 'red', type: 'color'},
  47362. borderColor: {default: 'white', type: 'color'},
  47363. highlighted: {default: false},
  47364. highlightedColor: {default: '#24CAFF', type: 'color'},
  47365. href: {default: ''},
  47366. image: {type: 'asset'},
  47367. on: {default: 'click'},
  47368. peekMode: {default: false},
  47369. title: {default: ''},
  47370. titleColor: {default: 'white', type: 'color'},
  47371. visualAspectEnabled: {default: false}
  47372. },
  47373. init: function () {
  47374. this.navigate = this.navigate.bind(this);
  47375. this.previousQuaternion = undefined;
  47376. this.quaternionClone = new THREE.Quaternion();
  47377. // Store hidden elements during peek mode so we can show them again later.
  47378. this.hiddenEls = [];
  47379. },
  47380. update: function (oldData) {
  47381. var data = this.data;
  47382. var el = this.el;
  47383. var backgroundColor;
  47384. var strokeColor;
  47385. if (!data.visualAspectEnabled) { return; }
  47386. this.initVisualAspect();
  47387. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  47388. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  47389. el.setAttribute('material', 'backgroundColor', backgroundColor);
  47390. el.setAttribute('material', 'strokeColor', strokeColor);
  47391. if (data.on !== oldData.on) { this.updateEventListener(); }
  47392. if (oldData.peekMode !== undefined &&
  47393. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  47394. if (!data.image || oldData.image === data.image) { return; }
  47395. el.setAttribute('material', 'pano',
  47396. typeof data.image === 'string' ? data.image : data.image.src);
  47397. },
  47398. /*
  47399. * Toggle all elements and full 360 preview of the linked page.
  47400. */
  47401. updatePeekMode: function () {
  47402. var el = this.el;
  47403. var sphereEl = this.sphereEl;
  47404. if (this.data.peekMode) {
  47405. this.hideAll();
  47406. el.getObject3D('mesh').visible = false;
  47407. sphereEl.setAttribute('visible', true);
  47408. } else {
  47409. this.showAll();
  47410. el.getObject3D('mesh').visible = true;
  47411. sphereEl.setAttribute('visible', false);
  47412. }
  47413. },
  47414. play: function () {
  47415. this.updateEventListener();
  47416. },
  47417. pause: function () {
  47418. this.removeEventListener();
  47419. },
  47420. updateEventListener: function () {
  47421. var el = this.el;
  47422. if (!el.isPlaying) { return; }
  47423. this.removeEventListener();
  47424. el.addEventListener(this.data.on, this.navigate);
  47425. },
  47426. removeEventListener: function () {
  47427. var on = this.data.on;
  47428. if (!on) { return; }
  47429. this.el.removeEventListener(on, this.navigate);
  47430. },
  47431. initVisualAspect: function () {
  47432. var el = this.el;
  47433. var semiSphereEl;
  47434. var sphereEl;
  47435. var textEl;
  47436. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  47437. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  47438. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  47439. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  47440. // Set portal.
  47441. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  47442. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  47443. // Set text that displays the link title and URL.
  47444. textEl.setAttribute('text', {
  47445. color: this.data.titleColor,
  47446. align: 'center',
  47447. font: 'kelsonsans',
  47448. value: this.data.title || this.data.href,
  47449. width: 4
  47450. });
  47451. textEl.setAttribute('position', '0 1.5 0');
  47452. el.appendChild(textEl);
  47453. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  47454. semiSphereEl.setAttribute('geometry', {
  47455. primitive: 'sphere',
  47456. radius: 1.0,
  47457. phiStart: 0,
  47458. segmentsWidth: 64,
  47459. segmentsHeight: 64,
  47460. phiLength: 180,
  47461. thetaStart: 0,
  47462. thetaLength: 360
  47463. });
  47464. semiSphereEl.setAttribute('material', {
  47465. shader: 'portal',
  47466. borderEnabled: 0.0,
  47467. pano: this.data.image,
  47468. side: 'back'
  47469. });
  47470. semiSphereEl.setAttribute('rotation', '0 180 0');
  47471. semiSphereEl.setAttribute('position', '0 0 0');
  47472. semiSphereEl.setAttribute('visible', false);
  47473. el.appendChild(semiSphereEl);
  47474. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  47475. sphereEl.setAttribute('geometry', {
  47476. primitive: 'sphere',
  47477. radius: 10,
  47478. segmentsWidth: 64,
  47479. segmentsHeight: 64
  47480. });
  47481. sphereEl.setAttribute('material', {
  47482. shader: 'portal',
  47483. borderEnabled: 0.0,
  47484. pano: this.data.image,
  47485. side: 'back'
  47486. });
  47487. sphereEl.setAttribute('visible', false);
  47488. el.appendChild(sphereEl);
  47489. this.visualAspectInitialized = true;
  47490. },
  47491. navigate: function () {
  47492. window.location = this.data.href;
  47493. },
  47494. /**
  47495. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  47496. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  47497. * from where user enters.
  47498. * 2. Place the url/title above or inside portal depending on distance to camera.
  47499. * 3. Face portal to camera when far away from user.
  47500. */
  47501. tick: (function () {
  47502. var cameraWorldPosition = new THREE.Vector3();
  47503. var elWorldPosition = new THREE.Vector3();
  47504. var quaternion = new THREE.Quaternion();
  47505. var scale = new THREE.Vector3();
  47506. return function () {
  47507. var el = this.el;
  47508. var object3D = el.object3D;
  47509. var camera = el.sceneEl.camera;
  47510. var cameraPortalOrientation;
  47511. var distance;
  47512. var textEl = this.textEl;
  47513. if (!this.data.visualAspectEnabled) { return; }
  47514. // Update matrices
  47515. object3D.updateMatrixWorld();
  47516. camera.parent.updateMatrixWorld();
  47517. camera.updateMatrixWorld();
  47518. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  47519. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  47520. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  47521. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  47522. if (distance > 20) {
  47523. // Store original orientation to be restored when the portal stops facing the camera.
  47524. if (!this.previousQuaternion) {
  47525. this.quaternionClone.copy(quaternion);
  47526. this.previousQuaternion = this.quaternionClone;
  47527. }
  47528. // If the portal is far away from the user, face portal to camera.
  47529. object3D.lookAt(cameraWorldPosition);
  47530. } else {
  47531. // When portal is close to the user/camera.
  47532. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  47533. // If user gets very close to portal, replace with holed sphere they can peek in.
  47534. if (distance < 0.5) {
  47535. // Configure text size and sphere orientation depending side user approaches portal.
  47536. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  47537. textEl.setAttribute('text', 'width', 1.5);
  47538. if (cameraPortalOrientation <= 0.0) {
  47539. textEl.setAttribute('position', '0 0 0.75');
  47540. textEl.setAttribute('rotation', '0 180 0');
  47541. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  47542. } else {
  47543. textEl.setAttribute('position', '0 0 -0.75');
  47544. textEl.setAttribute('rotation', '0 0 0');
  47545. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  47546. }
  47547. el.getObject3D('mesh').visible = false;
  47548. this.semiSphereEl.setAttribute('visible', true);
  47549. this.peekCameraPortalOrientation = cameraPortalOrientation;
  47550. } else {
  47551. // Calculate wich side the camera is approaching the camera (back / front).
  47552. // Adjust text orientation based on camera position.
  47553. if (cameraPortalOrientation <= 0.0) {
  47554. textEl.setAttribute('rotation', '0 180 0');
  47555. } else {
  47556. textEl.setAttribute('rotation', '0 0 0');
  47557. }
  47558. textEl.setAttribute('text', 'width', 5);
  47559. textEl.setAttribute('position', '0 1.5 0');
  47560. el.getObject3D('mesh').visible = true;
  47561. this.semiSphereEl.setAttribute('visible', false);
  47562. this.peekCameraPortalOrientation = undefined;
  47563. }
  47564. if (this.previousQuaternion) {
  47565. object3D.quaternion.copy(this.previousQuaternion);
  47566. this.previousQuaternion = undefined;
  47567. }
  47568. }
  47569. };
  47570. })(),
  47571. hideAll: function () {
  47572. var el = this.el;
  47573. var hiddenEls = this.hiddenEls;
  47574. var self = this;
  47575. if (hiddenEls.length > 0) { return; }
  47576. el.sceneEl.object3D.traverse(function (object) {
  47577. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  47578. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  47579. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  47580. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  47581. object.el === self.semiSphereEl) {
  47582. return;
  47583. }
  47584. object.el.setAttribute('visible', false);
  47585. hiddenEls.push(object.el);
  47586. });
  47587. },
  47588. showAll: function () {
  47589. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  47590. this.hiddenEls = [];
  47591. },
  47592. /**
  47593. * Calculate whether the camera faces the front or back face of the portal.
  47594. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  47595. */
  47596. calculateCameraPortalOrientation: (function () {
  47597. var mat4 = new THREE.Matrix4();
  47598. var cameraPosition = new THREE.Vector3();
  47599. var portalNormal = new THREE.Vector3(0, 0, 1);
  47600. var portalPosition = new THREE.Vector3(0, 0, 0);
  47601. return function () {
  47602. var el = this.el;
  47603. var camera = el.sceneEl.camera;
  47604. // Reset tmp variables.
  47605. cameraPosition.set(0, 0, 0);
  47606. portalNormal.set(0, 0, 1);
  47607. portalPosition.set(0, 0, 0);
  47608. // Apply portal orientation to the normal.
  47609. el.object3D.matrixWorld.extractRotation(mat4);
  47610. portalNormal.applyMatrix4(mat4);
  47611. // Calculate portal world position.
  47612. el.object3D.updateMatrixWorld();
  47613. el.object3D.localToWorld(portalPosition);
  47614. // Calculate camera world position.
  47615. camera.parent.parent.updateMatrixWorld();
  47616. camera.parent.updateMatrixWorld();
  47617. camera.updateMatrixWorld();
  47618. camera.localToWorld(cameraPosition);
  47619. // Calculate vector from portal to camera.
  47620. // (portal) -------> (camera)
  47621. cameraPosition.sub(portalPosition).normalize();
  47622. portalNormal.normalize();
  47623. // Side where camera approaches portal is given by sign of dot product of portal normal
  47624. // and portal to camera vectors.
  47625. return Math.sign(portalNormal.dot(cameraPosition));
  47626. };
  47627. })(),
  47628. remove: function () {
  47629. this.removeEventListener();
  47630. }
  47631. });
  47632. /* eslint-disable */
  47633. registerShader('portal', {
  47634. schema: {
  47635. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  47636. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  47637. pano: {type: 'map', is: 'uniform'},
  47638. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  47639. },
  47640. vertexShader: [
  47641. 'vec3 portalPosition;',
  47642. 'varying vec3 vWorldPosition;',
  47643. 'varying float vDistanceToCenter;',
  47644. 'varying float vDistance;',
  47645. 'void main() {',
  47646. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  47647. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  47648. 'vDistance = length(portalPosition - cameraPosition);',
  47649. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  47650. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  47651. '}'
  47652. ].join('\n'),
  47653. fragmentShader: [
  47654. '#define RECIPROCAL_PI2 0.15915494',
  47655. 'uniform sampler2D pano;',
  47656. 'uniform vec3 strokeColor;',
  47657. 'uniform vec3 backgroundColor;',
  47658. 'uniform float borderEnabled;',
  47659. 'varying float vDistanceToCenter;',
  47660. 'varying float vDistance;',
  47661. 'varying vec3 vWorldPosition;',
  47662. 'void main() {',
  47663. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  47664. 'vec2 sampleUV;',
  47665. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  47666. 'sampleUV.y = clamp(direction.y * 0.5 + 0.5, 0.0, 1.0);',
  47667. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  47668. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  47669. 'gl_FragColor = vec4(strokeColor, 1.0);',
  47670. '} else {',
  47671. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  47672. '}',
  47673. '}'
  47674. ].join('\n')
  47675. });
  47676. /* eslint-enable */
  47677. },{"../core/component":135,"../core/shader":145,"../lib/three":183}],93:[function(require,module,exports){
  47678. /* global DeviceOrientationEvent */
  47679. var registerComponent = require('../core/component').registerComponent;
  47680. var THREE = require('../lib/three');
  47681. var utils = require('../utils/');
  47682. var bind = utils.bind;
  47683. // To avoid recalculation at every mouse movement tick
  47684. var PI_2 = Math.PI / 2;
  47685. /**
  47686. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  47687. */
  47688. module.exports.Component = registerComponent('look-controls', {
  47689. dependencies: ['position', 'rotation'],
  47690. schema: {
  47691. enabled: {default: true},
  47692. magicWindowTrackingEnabled: {default: true},
  47693. pointerLockEnabled: {default: false},
  47694. reverseMouseDrag: {default: false},
  47695. reverseTouchDrag: {default: false},
  47696. touchEnabled: {default: true},
  47697. mouseEnabled: {default: true}
  47698. },
  47699. init: function () {
  47700. this.deltaYaw = 0;
  47701. this.previousHMDPosition = new THREE.Vector3();
  47702. this.hmdQuaternion = new THREE.Quaternion();
  47703. this.magicWindowAbsoluteEuler = new THREE.Euler();
  47704. this.magicWindowDeltaEuler = new THREE.Euler();
  47705. this.position = new THREE.Vector3();
  47706. this.magicWindowObject = new THREE.Object3D();
  47707. this.rotation = {};
  47708. this.deltaRotation = {};
  47709. this.savedPose = null;
  47710. this.pointerLocked = false;
  47711. this.setupMouseControls();
  47712. this.bindMethods();
  47713. this.previousMouseEvent = {};
  47714. this.setupMagicWindowControls();
  47715. // To save / restore camera pose
  47716. this.savedPose = {
  47717. position: new THREE.Vector3(),
  47718. rotation: new THREE.Euler()
  47719. };
  47720. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  47721. if (this.el.sceneEl.is('vr-mode') || this.el.sceneEl.is('ar-mode')) { this.onEnterVR(); }
  47722. },
  47723. setupMagicWindowControls: function () {
  47724. var magicWindowControls;
  47725. var data = this.data;
  47726. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  47727. if (utils.device.isMobile() || utils.device.isMobileDeviceRequestingDesktopSite()) {
  47728. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  47729. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  47730. magicWindowControls.enabled = false;
  47731. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  47732. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47733. } else {
  47734. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  47735. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47736. });
  47737. }
  47738. }
  47739. }
  47740. },
  47741. update: function (oldData) {
  47742. var data = this.data;
  47743. // Disable grab cursor classes if no longer enabled.
  47744. if (data.enabled !== oldData.enabled) {
  47745. this.updateGrabCursor(data.enabled);
  47746. }
  47747. // Reset magic window eulers if tracking is disabled.
  47748. if (oldData && !data.magicWindowTrackingEnabled && oldData.magicWindowTrackingEnabled) {
  47749. this.magicWindowAbsoluteEuler.set(0, 0, 0);
  47750. this.magicWindowDeltaEuler.set(0, 0, 0);
  47751. }
  47752. // Pass on magic window tracking setting to magicWindowControls.
  47753. if (this.magicWindowControls) {
  47754. this.magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  47755. }
  47756. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  47757. this.removeEventListeners();
  47758. this.addEventListeners();
  47759. if (this.pointerLocked) { this.exitPointerLock(); }
  47760. }
  47761. },
  47762. tick: function (t) {
  47763. var data = this.data;
  47764. if (!data.enabled) { return; }
  47765. this.updateOrientation();
  47766. },
  47767. play: function () {
  47768. this.addEventListeners();
  47769. },
  47770. pause: function () {
  47771. this.removeEventListeners();
  47772. if (this.pointerLocked) { this.exitPointerLock(); }
  47773. },
  47774. remove: function () {
  47775. this.removeEventListeners();
  47776. if (this.pointerLocked) { this.exitPointerLock(); }
  47777. },
  47778. bindMethods: function () {
  47779. this.onMouseDown = bind(this.onMouseDown, this);
  47780. this.onMouseMove = bind(this.onMouseMove, this);
  47781. this.onMouseUp = bind(this.onMouseUp, this);
  47782. this.onTouchStart = bind(this.onTouchStart, this);
  47783. this.onTouchMove = bind(this.onTouchMove, this);
  47784. this.onTouchEnd = bind(this.onTouchEnd, this);
  47785. this.onEnterVR = bind(this.onEnterVR, this);
  47786. this.onExitVR = bind(this.onExitVR, this);
  47787. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  47788. this.onPointerLockError = bind(this.onPointerLockError, this);
  47789. },
  47790. /**
  47791. * Set up states and Object3Ds needed to store rotation data.
  47792. */
  47793. setupMouseControls: function () {
  47794. this.mouseDown = false;
  47795. this.pitchObject = new THREE.Object3D();
  47796. this.yawObject = new THREE.Object3D();
  47797. this.yawObject.position.y = 10;
  47798. this.yawObject.add(this.pitchObject);
  47799. },
  47800. /**
  47801. * Add mouse and touch event listeners to canvas.
  47802. */
  47803. addEventListeners: function () {
  47804. var sceneEl = this.el.sceneEl;
  47805. var canvasEl = sceneEl.canvas;
  47806. // Wait for canvas to load.
  47807. if (!canvasEl) {
  47808. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  47809. return;
  47810. }
  47811. // Mouse events.
  47812. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  47813. window.addEventListener('mousemove', this.onMouseMove, false);
  47814. window.addEventListener('mouseup', this.onMouseUp, false);
  47815. // Touch events.
  47816. canvasEl.addEventListener('touchstart', this.onTouchStart);
  47817. window.addEventListener('touchmove', this.onTouchMove);
  47818. window.addEventListener('touchend', this.onTouchEnd);
  47819. // sceneEl events.
  47820. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  47821. sceneEl.addEventListener('exit-vr', this.onExitVR);
  47822. // Pointer Lock events.
  47823. if (this.data.pointerLockEnabled) {
  47824. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  47825. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  47826. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  47827. }
  47828. },
  47829. /**
  47830. * Remove mouse and touch event listeners from canvas.
  47831. */
  47832. removeEventListeners: function () {
  47833. var sceneEl = this.el.sceneEl;
  47834. var canvasEl = sceneEl && sceneEl.canvas;
  47835. if (!canvasEl) { return; }
  47836. // Mouse events.
  47837. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  47838. window.removeEventListener('mousemove', this.onMouseMove);
  47839. window.removeEventListener('mouseup', this.onMouseUp);
  47840. // Touch events.
  47841. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  47842. window.removeEventListener('touchmove', this.onTouchMove);
  47843. window.removeEventListener('touchend', this.onTouchEnd);
  47844. // sceneEl events.
  47845. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  47846. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  47847. // Pointer Lock events.
  47848. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  47849. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  47850. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  47851. },
  47852. /**
  47853. * Update orientation for mobile, mouse drag, and headset.
  47854. * Mouse-drag only enabled if HMD is not active.
  47855. */
  47856. updateOrientation: function () {
  47857. var object3D = this.el.object3D;
  47858. var pitchObject = this.pitchObject;
  47859. var yawObject = this.yawObject;
  47860. var sceneEl = this.el.sceneEl;
  47861. // In VR or AR mode, THREE is in charge of updating the camera pose.
  47862. if ((sceneEl.is('vr-mode') || sceneEl.is('ar-mode')) && sceneEl.checkHeadsetConnected()) {
  47863. // With WebXR THREE applies headset pose to the object3D internally.
  47864. return;
  47865. }
  47866. this.updateMagicWindowOrientation();
  47867. // On mobile, do camera rotation with touch events and sensors.
  47868. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  47869. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  47870. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  47871. },
  47872. updateMagicWindowOrientation: function () {
  47873. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  47874. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  47875. // Calculate magic window HMD quaternion.
  47876. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  47877. this.magicWindowControls.update();
  47878. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  47879. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  47880. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  47881. }
  47882. if (this.previousMagicWindowYaw) {
  47883. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  47884. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  47885. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  47886. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  47887. }
  47888. }
  47889. },
  47890. /**
  47891. * Translate mouse drag into rotation.
  47892. *
  47893. * Dragging up and down rotates the camera around the X-axis (yaw).
  47894. * Dragging left and right rotates the camera around the Y-axis (pitch).
  47895. */
  47896. onMouseMove: function (evt) {
  47897. var direction;
  47898. var movementX;
  47899. var movementY;
  47900. var pitchObject = this.pitchObject;
  47901. var previousMouseEvent = this.previousMouseEvent;
  47902. var yawObject = this.yawObject;
  47903. // Not dragging or not enabled.
  47904. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  47905. // Calculate delta.
  47906. if (this.pointerLocked) {
  47907. movementX = evt.movementX || evt.mozMovementX || 0;
  47908. movementY = evt.movementY || evt.mozMovementY || 0;
  47909. } else {
  47910. movementX = evt.screenX - previousMouseEvent.screenX;
  47911. movementY = evt.screenY - previousMouseEvent.screenY;
  47912. }
  47913. this.previousMouseEvent.screenX = evt.screenX;
  47914. this.previousMouseEvent.screenY = evt.screenY;
  47915. // Calculate rotation.
  47916. direction = this.data.reverseMouseDrag ? 1 : -1;
  47917. yawObject.rotation.y += movementX * 0.002 * direction;
  47918. pitchObject.rotation.x += movementY * 0.002 * direction;
  47919. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  47920. },
  47921. /**
  47922. * Register mouse down to detect mouse drag.
  47923. */
  47924. onMouseDown: function (evt) {
  47925. var sceneEl = this.el.sceneEl;
  47926. if (!this.data.enabled || !this.data.mouseEnabled || ((sceneEl.is('vr-mode') || sceneEl.is('ar-mode')) && sceneEl.checkHeadsetConnected())) { return; }
  47927. // Handle only primary button.
  47928. if (evt.button !== 0) { return; }
  47929. var canvasEl = sceneEl && sceneEl.canvas;
  47930. this.mouseDown = true;
  47931. this.previousMouseEvent.screenX = evt.screenX;
  47932. this.previousMouseEvent.screenY = evt.screenY;
  47933. this.showGrabbingCursor();
  47934. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  47935. if (canvasEl.requestPointerLock) {
  47936. canvasEl.requestPointerLock();
  47937. } else if (canvasEl.mozRequestPointerLock) {
  47938. canvasEl.mozRequestPointerLock();
  47939. }
  47940. }
  47941. },
  47942. /**
  47943. * Shows grabbing cursor on scene
  47944. */
  47945. showGrabbingCursor: function () {
  47946. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  47947. },
  47948. /**
  47949. * Hides grabbing cursor on scene
  47950. */
  47951. hideGrabbingCursor: function () {
  47952. this.el.sceneEl.canvas.style.cursor = '';
  47953. },
  47954. /**
  47955. * Register mouse up to detect release of mouse drag.
  47956. */
  47957. onMouseUp: function () {
  47958. this.mouseDown = false;
  47959. this.hideGrabbingCursor();
  47960. },
  47961. /**
  47962. * Register touch down to detect touch drag.
  47963. */
  47964. onTouchStart: function (evt) {
  47965. if (evt.touches.length !== 1 ||
  47966. !this.data.touchEnabled ||
  47967. this.el.sceneEl.is('vr-mode') ||
  47968. this.el.sceneEl.is('ar-mode')) { return; }
  47969. this.touchStart = {
  47970. x: evt.touches[0].pageX,
  47971. y: evt.touches[0].pageY
  47972. };
  47973. this.touchStarted = true;
  47974. },
  47975. /**
  47976. * Translate touch move to Y-axis rotation.
  47977. */
  47978. onTouchMove: function (evt) {
  47979. var direction;
  47980. var canvas = this.el.sceneEl.canvas;
  47981. var deltaY;
  47982. var yawObject = this.yawObject;
  47983. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  47984. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  47985. direction = this.data.reverseTouchDrag ? 1 : -1;
  47986. // Limit touch orientaion to to yaw (y axis).
  47987. yawObject.rotation.y -= deltaY * 0.5 * direction;
  47988. this.touchStart = {
  47989. x: evt.touches[0].pageX,
  47990. y: evt.touches[0].pageY
  47991. };
  47992. },
  47993. /**
  47994. * Register touch end to detect release of touch drag.
  47995. */
  47996. onTouchEnd: function () {
  47997. this.touchStarted = false;
  47998. },
  47999. /**
  48000. * Save pose.
  48001. */
  48002. onEnterVR: function () {
  48003. var sceneEl = this.el.sceneEl;
  48004. if (!sceneEl.checkHeadsetConnected()) { return; }
  48005. this.saveCameraPose();
  48006. this.el.object3D.position.set(0, 0, 0);
  48007. this.el.object3D.rotation.set(0, 0, 0);
  48008. if (sceneEl.hasWebXR) {
  48009. this.el.object3D.matrixAutoUpdate = false;
  48010. this.el.object3D.updateMatrix();
  48011. }
  48012. },
  48013. /**
  48014. * Restore the pose.
  48015. */
  48016. onExitVR: function () {
  48017. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  48018. this.restoreCameraPose();
  48019. this.previousHMDPosition.set(0, 0, 0);
  48020. this.el.object3D.matrixAutoUpdate = true;
  48021. },
  48022. /**
  48023. * Update Pointer Lock state.
  48024. */
  48025. onPointerLockChange: function () {
  48026. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  48027. },
  48028. /**
  48029. * Recover from Pointer Lock error.
  48030. */
  48031. onPointerLockError: function () {
  48032. this.pointerLocked = false;
  48033. },
  48034. // Exits pointer-locked mode.
  48035. exitPointerLock: function () {
  48036. document.exitPointerLock();
  48037. this.pointerLocked = false;
  48038. },
  48039. /**
  48040. * Toggle the feature of showing/hiding the grab cursor.
  48041. */
  48042. updateGrabCursor: function (enabled) {
  48043. var sceneEl = this.el.sceneEl;
  48044. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  48045. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  48046. if (!sceneEl.canvas) {
  48047. if (enabled) {
  48048. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  48049. } else {
  48050. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  48051. }
  48052. return;
  48053. }
  48054. if (enabled) {
  48055. enableGrabCursor();
  48056. return;
  48057. }
  48058. disableGrabCursor();
  48059. },
  48060. /**
  48061. * Save camera pose before entering VR to restore later if exiting.
  48062. */
  48063. saveCameraPose: function () {
  48064. var el = this.el;
  48065. this.savedPose.position.copy(el.object3D.position);
  48066. this.savedPose.rotation.copy(el.object3D.rotation);
  48067. this.hasSavedPose = true;
  48068. },
  48069. /**
  48070. * Reset camera pose to before entering VR.
  48071. */
  48072. restoreCameraPose: function () {
  48073. var el = this.el;
  48074. var savedPose = this.savedPose;
  48075. if (!this.hasSavedPose) { return; }
  48076. // Reset camera orientation.
  48077. el.object3D.position.copy(savedPose.position);
  48078. el.object3D.rotation.copy(savedPose.rotation);
  48079. this.hasSavedPose = false;
  48080. }
  48081. });
  48082. },{"../core/component":135,"../lib/three":183,"../utils/":210}],94:[function(require,module,exports){
  48083. var bind = require('../utils/bind');
  48084. var registerComponent = require('../core/component').registerComponent;
  48085. var trackedControlsUtils = require('../utils/tracked-controls');
  48086. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48087. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48088. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48089. // See Profiles Registry:
  48090. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  48091. // TODO: Add a more robust system for deriving gamepad name.
  48092. var GAMEPAD_ID_PREFIX = 'magicleap';
  48093. var GAMEPAD_ID_SUFFIX = '-one';
  48094. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  48095. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  48096. /**
  48097. * Button IDs:
  48098. * 0 - trigger
  48099. * 1 - grip
  48100. * 2 - touchpad
  48101. * 3 - menu (never dispatched on this layer)
  48102. *
  48103. * Axis:
  48104. * 0 - touchpad x axis
  48105. * 1 - touchpad y axis
  48106. */
  48107. var INPUT_MAPPING_WEBXR = {
  48108. axes: {touchpad: [0, 1]},
  48109. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  48110. };
  48111. /**
  48112. * Magic Leap Controls
  48113. * Interface with Magic Leap control and map Gamepad events to controller
  48114. * buttons: trigger, grip, touchpad, and menu.
  48115. * Load a controller model.
  48116. */
  48117. module.exports.Component = registerComponent('magicleap-controls', {
  48118. schema: {
  48119. hand: {default: 'none'},
  48120. model: {default: true},
  48121. orientationOffset: {type: 'vec3'}
  48122. },
  48123. mapping: INPUT_MAPPING_WEBXR,
  48124. init: function () {
  48125. var self = this;
  48126. this.controllerPresent = false;
  48127. this.lastControllerCheck = 0;
  48128. this.onButtonChanged = bind(this.onButtonChanged, this);
  48129. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48130. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48131. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48132. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48133. this.previousButtonValues = {};
  48134. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48135. this.bindMethods();
  48136. },
  48137. update: function () {
  48138. var data = this.data;
  48139. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  48140. },
  48141. play: function () {
  48142. this.checkIfControllerPresent();
  48143. this.addControllersUpdateListener();
  48144. },
  48145. pause: function () {
  48146. this.removeEventListeners();
  48147. this.removeControllersUpdateListener();
  48148. },
  48149. bindMethods: function () {
  48150. this.onModelLoaded = bind(this.onModelLoaded, this);
  48151. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48152. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48153. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48154. this.onAxisMoved = bind(this.onAxisMoved, this);
  48155. },
  48156. addEventListeners: function () {
  48157. var el = this.el;
  48158. el.addEventListener('buttonchanged', this.onButtonChanged);
  48159. el.addEventListener('buttondown', this.onButtonDown);
  48160. el.addEventListener('buttonup', this.onButtonUp);
  48161. el.addEventListener('touchstart', this.onButtonTouchStart);
  48162. el.addEventListener('touchend', this.onButtonTouchEnd);
  48163. el.addEventListener('axismove', this.onAxisMoved);
  48164. el.addEventListener('model-loaded', this.onModelLoaded);
  48165. this.controllerEventsActive = true;
  48166. },
  48167. removeEventListeners: function () {
  48168. var el = this.el;
  48169. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48170. el.removeEventListener('buttondown', this.onButtonDown);
  48171. el.removeEventListener('buttonup', this.onButtonUp);
  48172. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48173. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48174. el.removeEventListener('axismove', this.onAxisMoved);
  48175. el.removeEventListener('model-loaded', this.onModelLoaded);
  48176. this.controllerEventsActive = false;
  48177. },
  48178. checkIfControllerPresent: function () {
  48179. var data = this.data;
  48180. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  48181. {index: this.controllerIndex, hand: data.hand});
  48182. },
  48183. injectTrackedControls: function () {
  48184. var el = this.el;
  48185. var data = this.data;
  48186. el.setAttribute('tracked-controls', {
  48187. // TODO: verify expected behavior between reserved prefixes.
  48188. idPrefix: GAMEPAD_ID_COMPOSITE,
  48189. hand: data.hand,
  48190. controller: this.controllerIndex,
  48191. orientationOffset: data.orientationOffset
  48192. });
  48193. // Load model.
  48194. if (!this.data.model) { return; }
  48195. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  48196. },
  48197. addControllersUpdateListener: function () {
  48198. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48199. },
  48200. removeControllersUpdateListener: function () {
  48201. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48202. },
  48203. onControllersUpdate: function () {
  48204. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  48205. this.checkIfControllerPresent();
  48206. },
  48207. /**
  48208. * Rotate the trigger button based on how hard the trigger is pressed.
  48209. */
  48210. onButtonChanged: function (evt) {
  48211. var button = this.mapping.buttons[evt.detail.id];
  48212. var analogValue;
  48213. if (!button) { return; }
  48214. if (button === 'trigger') {
  48215. analogValue = evt.detail.state.value;
  48216. console.log('analog value of trigger press: ' + analogValue);
  48217. }
  48218. // Pass along changed event with button state, using button mapping for convenience.
  48219. this.el.emit(button + 'changed', evt.detail.state);
  48220. },
  48221. onModelLoaded: function (evt) {
  48222. var controllerObject3D = evt.detail.model;
  48223. // our glb scale is too large.
  48224. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  48225. },
  48226. onAxisMoved: function (evt) {
  48227. emitIfAxesChanged(this, this.mapping.axes, evt);
  48228. },
  48229. updateModel: function (buttonName, evtName) {},
  48230. setButtonColor: function (buttonName, color) {}
  48231. });
  48232. },{"../core/component":135,"../utils/bind":204,"../utils/tracked-controls":219}],95:[function(require,module,exports){
  48233. /* global Promise */
  48234. var utils = require('../utils/');
  48235. var component = require('../core/component');
  48236. var THREE = require('../lib/three');
  48237. var shader = require('../core/shader');
  48238. var error = utils.debug('components:material:error');
  48239. var registerComponent = component.registerComponent;
  48240. var shaders = shader.shaders;
  48241. var shaderNames = shader.shaderNames;
  48242. /**
  48243. * Material component.
  48244. *
  48245. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  48246. * three.js's implementation of PBR. Another standard shading model is `flat` which
  48247. * uses MeshBasicMaterial.
  48248. */
  48249. module.exports.Component = registerComponent('material', {
  48250. schema: {
  48251. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  48252. depthTest: {default: true},
  48253. depthWrite: {default: true},
  48254. flatShading: {default: false},
  48255. npot: {default: false},
  48256. offset: {type: 'vec2', default: {x: 0, y: 0}},
  48257. opacity: {default: 1.0, min: 0.0, max: 1.0},
  48258. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  48259. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  48260. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  48261. transparent: {default: false},
  48262. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  48263. visible: {default: true},
  48264. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  48265. dithering: {default: true}
  48266. },
  48267. init: function () {
  48268. this.material = null;
  48269. },
  48270. /**
  48271. * Update or create material.
  48272. *
  48273. * @param {object|null} oldData
  48274. */
  48275. update: function (oldData) {
  48276. var data = this.data;
  48277. if (!this.shader || data.shader !== oldData.shader) {
  48278. this.updateShader(data.shader);
  48279. }
  48280. this.shader.update(this.data);
  48281. this.updateMaterial(oldData);
  48282. },
  48283. updateSchema: function (data) {
  48284. var currentShader;
  48285. var newShader;
  48286. var schema;
  48287. var shader;
  48288. newShader = data && data.shader;
  48289. currentShader = this.oldData && this.oldData.shader;
  48290. shader = newShader || currentShader;
  48291. schema = shaders[shader] && shaders[shader].schema;
  48292. if (!schema) { error('Unknown shader schema ' + shader); }
  48293. if (currentShader && newShader === currentShader) { return; }
  48294. this.extendSchema(schema);
  48295. this.updateBehavior();
  48296. },
  48297. updateBehavior: function () {
  48298. var key;
  48299. var sceneEl = this.el.sceneEl;
  48300. var schema = this.schema;
  48301. var self = this;
  48302. var tickProperties;
  48303. function tickTime (time, delta) {
  48304. var key;
  48305. for (key in tickProperties) {
  48306. tickProperties[key] = time;
  48307. }
  48308. self.shader.update(tickProperties);
  48309. }
  48310. this.tick = undefined;
  48311. tickProperties = {};
  48312. for (key in schema) {
  48313. if (schema[key].type === 'time') {
  48314. this.tick = tickTime;
  48315. tickProperties[key] = true;
  48316. }
  48317. }
  48318. if (!sceneEl) { return; }
  48319. if (this.tick) {
  48320. sceneEl.addBehavior(this);
  48321. } else {
  48322. sceneEl.removeBehavior(this);
  48323. }
  48324. },
  48325. updateShader: function (shaderName) {
  48326. var data = this.data;
  48327. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  48328. var shaderInstance;
  48329. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  48330. // Get material from A-Frame shader.
  48331. shaderInstance = this.shader = new Shader();
  48332. shaderInstance.el = this.el;
  48333. shaderInstance.init(data);
  48334. this.setMaterial(shaderInstance.material);
  48335. this.updateSchema(data);
  48336. },
  48337. /**
  48338. * Set and update base material properties.
  48339. * Set `needsUpdate` when needed.
  48340. */
  48341. updateMaterial: function (oldData) {
  48342. var data = this.data;
  48343. var material = this.material;
  48344. var oldDataHasKeys;
  48345. // Base material properties.
  48346. material.alphaTest = data.alphaTest;
  48347. material.depthTest = data.depthTest !== false;
  48348. material.depthWrite = data.depthWrite !== false;
  48349. material.opacity = data.opacity;
  48350. material.flatShading = data.flatShading;
  48351. material.side = parseSide(data.side);
  48352. material.transparent = data.transparent !== false || data.opacity < 1.0;
  48353. material.vertexColors = parseVertexColors(data.vertexColors);
  48354. material.visible = data.visible;
  48355. material.blending = parseBlending(data.blending);
  48356. material.dithering = data.dithering;
  48357. // Check if material needs update.
  48358. for (oldDataHasKeys in oldData) { break; }
  48359. if (oldDataHasKeys &&
  48360. (oldData.alphaTest !== data.alphaTest ||
  48361. oldData.side !== data.side ||
  48362. oldData.vertexColors !== data.vertexColors)) {
  48363. material.needsUpdate = true;
  48364. }
  48365. },
  48366. /**
  48367. * Remove material on remove (callback).
  48368. * Dispose of it from memory and unsubscribe from scene updates.
  48369. */
  48370. remove: function () {
  48371. var defaultMaterial = new THREE.MeshBasicMaterial();
  48372. var material = this.material;
  48373. var object3D = this.el.getObject3D('mesh');
  48374. if (object3D) { object3D.material = defaultMaterial; }
  48375. disposeMaterial(material, this.system);
  48376. },
  48377. /**
  48378. * (Re)create new material. Has side-effects of setting `this.material` and updating
  48379. * material registration in scene.
  48380. *
  48381. * @param {object} data - Material component data.
  48382. * @param {object} type - Material type to create.
  48383. * @returns {object} Material.
  48384. */
  48385. setMaterial: function (material) {
  48386. var el = this.el;
  48387. var mesh;
  48388. var system = this.system;
  48389. if (this.material) { disposeMaterial(this.material, system); }
  48390. this.material = material;
  48391. system.registerMaterial(material);
  48392. // Set on mesh. If mesh does not exist, wait for it.
  48393. mesh = el.getObject3D('mesh');
  48394. if (mesh) {
  48395. mesh.material = material;
  48396. } else {
  48397. el.addEventListener('object3dset', function waitForMesh (evt) {
  48398. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  48399. el.getObject3D('mesh').material = material;
  48400. el.removeEventListener('object3dset', waitForMesh);
  48401. });
  48402. }
  48403. }
  48404. });
  48405. /**
  48406. * Return a three.js constant determining which material face sides to render
  48407. * based on the side parameter (passed as a component property).
  48408. *
  48409. * @param {string} [side=front] - `front`, `back`, or `double`.
  48410. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  48411. */
  48412. function parseSide (side) {
  48413. switch (side) {
  48414. case 'back': {
  48415. return THREE.BackSide;
  48416. }
  48417. case 'double': {
  48418. return THREE.DoubleSide;
  48419. }
  48420. default: {
  48421. // Including case `front`.
  48422. return THREE.FrontSide;
  48423. }
  48424. }
  48425. }
  48426. /**
  48427. * Return a three.js constant determining vertex coloring.
  48428. */
  48429. function parseVertexColors (coloring) {
  48430. switch (coloring) {
  48431. case 'face': {
  48432. return THREE.FaceColors;
  48433. }
  48434. case 'vertex': {
  48435. return THREE.VertexColors;
  48436. }
  48437. default: {
  48438. return THREE.NoColors;
  48439. }
  48440. }
  48441. }
  48442. /**
  48443. * Return a three.js constant determining blending
  48444. *
  48445. * @param {string} [blending=normal]
  48446. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  48447. * @returns {number}
  48448. */
  48449. function parseBlending (blending) {
  48450. switch (blending) {
  48451. case 'none': {
  48452. return THREE.NoBlending;
  48453. }
  48454. case 'additive': {
  48455. return THREE.AdditiveBlending;
  48456. }
  48457. case 'subtractive': {
  48458. return THREE.SubtractiveBlending;
  48459. }
  48460. case 'multiply': {
  48461. return THREE.MultiplyBlending;
  48462. }
  48463. default: {
  48464. return THREE.NormalBlending;
  48465. }
  48466. }
  48467. }
  48468. /**
  48469. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  48470. */
  48471. function disposeMaterial (material, system) {
  48472. material.dispose();
  48473. system.unregisterMaterial(material);
  48474. }
  48475. },{"../core/component":135,"../core/shader":145,"../lib/three":183,"../utils/":210}],96:[function(require,module,exports){
  48476. var debug = require('../utils/debug');
  48477. var registerComponent = require('../core/component').registerComponent;
  48478. var THREE = require('../lib/three');
  48479. var warn = debug('components:obj-model:warn');
  48480. module.exports.Component = registerComponent('obj-model', {
  48481. schema: {
  48482. mtl: {type: 'model'},
  48483. obj: {type: 'model'}
  48484. },
  48485. init: function () {
  48486. var self = this;
  48487. this.model = null;
  48488. this.objLoader = new THREE.OBJLoader();
  48489. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  48490. // Allow cross-origin images to be loaded.
  48491. this.mtlLoader.crossOrigin = '';
  48492. this.el.addEventListener('componentinitialized', function (evt) {
  48493. if (!self.model) { return; }
  48494. if (evt.detail.name !== 'material') { return; }
  48495. self.applyMaterial();
  48496. });
  48497. },
  48498. update: function () {
  48499. var data = this.data;
  48500. if (!data.obj) { return; }
  48501. this.resetMesh();
  48502. this.loadObj(data.obj, data.mtl);
  48503. },
  48504. remove: function () {
  48505. if (!this.model) { return; }
  48506. this.resetMesh();
  48507. },
  48508. resetMesh: function () {
  48509. this.el.removeObject3D('mesh');
  48510. },
  48511. loadObj: function (objUrl, mtlUrl) {
  48512. var self = this;
  48513. var el = this.el;
  48514. var mtlLoader = this.mtlLoader;
  48515. var objLoader = this.objLoader;
  48516. var rendererSystem = this.el.sceneEl.systems.renderer;
  48517. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  48518. if (mtlUrl) {
  48519. // .OBJ with an .MTL.
  48520. if (el.hasAttribute('material')) {
  48521. warn('Material component properties are ignored when a .MTL is provided');
  48522. }
  48523. mtlLoader.setResourcePath(BASE_PATH);
  48524. mtlLoader.load(mtlUrl, function (materials) {
  48525. materials.preload();
  48526. objLoader.setMaterials(materials);
  48527. objLoader.load(objUrl, function (objModel) {
  48528. self.model = objModel;
  48529. self.model.traverse(function (object) {
  48530. if (object.isMesh) {
  48531. var material = object.material;
  48532. if (material.color) rendererSystem.applyColorCorrection(material.color);
  48533. if (material.map) rendererSystem.applyColorCorrection(material.map);
  48534. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  48535. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  48536. }
  48537. });
  48538. el.setObject3D('mesh', objModel);
  48539. el.emit('model-loaded', {format: 'obj', model: objModel});
  48540. });
  48541. });
  48542. return;
  48543. }
  48544. // .OBJ only.
  48545. objLoader.load(objUrl, function loadObjOnly (objModel) {
  48546. self.model = objModel;
  48547. self.applyMaterial();
  48548. el.setObject3D('mesh', objModel);
  48549. el.emit('model-loaded', {format: 'obj', model: objModel});
  48550. });
  48551. },
  48552. /**
  48553. * Apply material from material component recursively.
  48554. */
  48555. applyMaterial: function () {
  48556. var material = this.el.components.material;
  48557. if (!material) { return; }
  48558. this.model.traverse(function (child) {
  48559. if (child instanceof THREE.Mesh) {
  48560. child.material = material.material;
  48561. }
  48562. });
  48563. }
  48564. });
  48565. },{"../core/component":135,"../lib/three":183,"../utils/debug":206}],97:[function(require,module,exports){
  48566. var registerComponent = require('../core/component').registerComponent;
  48567. var bind = require('../utils/bind');
  48568. var trackedControlsUtils = require('../utils/tracked-controls');
  48569. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48570. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48571. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48572. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  48573. var GAMEPAD_ID_WEBXR = 'oculus-go';
  48574. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  48575. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  48576. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  48577. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  48578. /**
  48579. * Button indices:
  48580. * 0 - trackpad
  48581. * 1 - trigger
  48582. *
  48583. * Axis:
  48584. * 0 - trackpad x
  48585. * 1 - trackpad y
  48586. */
  48587. var INPUT_MAPPING_WEBVR = {
  48588. axes: {trackpad: [0, 1]},
  48589. buttons: ['trackpad', 'trigger']
  48590. };
  48591. /**
  48592. * Button indices:
  48593. * 0 - trigger
  48594. * 1 - none
  48595. * 2 - touchpad
  48596. *
  48597. * Axis:
  48598. * 0 - touchpad x
  48599. * 1 - touchpad y
  48600. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  48601. */
  48602. var INPUT_MAPPING_WEBXR = {
  48603. axes: {touchpad: [0, 1]},
  48604. buttons: ['trigger', 'none', 'touchpad']
  48605. };
  48606. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  48607. /**
  48608. * Oculus Go controls.
  48609. * Interface with Oculus Go controller and map Gamepad events to
  48610. * controller buttons: trackpad, trigger
  48611. * Load a controller model and highlight the pressed buttons.
  48612. */
  48613. module.exports.Component = registerComponent('oculus-go-controls', {
  48614. schema: {
  48615. hand: {default: ''}, // This informs the degenerate arm model.
  48616. buttonColor: {type: 'color', default: '#FFFFFF'},
  48617. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  48618. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  48619. model: {default: true},
  48620. orientationOffset: {type: 'vec3'},
  48621. armModel: {default: true}
  48622. },
  48623. mapping: INPUT_MAPPING,
  48624. bindMethods: function () {
  48625. this.onModelLoaded = bind(this.onModelLoaded, this);
  48626. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48627. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48628. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  48629. this.onAxisMoved = bind(this.onAxisMoved, this);
  48630. },
  48631. init: function () {
  48632. var self = this;
  48633. this.onButtonChanged = bind(this.onButtonChanged, this);
  48634. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  48635. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  48636. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  48637. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  48638. this.controllerPresent = false;
  48639. this.lastControllerCheck = 0;
  48640. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48641. this.bindMethods();
  48642. },
  48643. addEventListeners: function () {
  48644. var el = this.el;
  48645. el.addEventListener('buttonchanged', this.onButtonChanged);
  48646. el.addEventListener('buttondown', this.onButtonDown);
  48647. el.addEventListener('buttonup', this.onButtonUp);
  48648. el.addEventListener('touchstart', this.onButtonTouchStart);
  48649. el.addEventListener('touchend', this.onButtonTouchEnd);
  48650. el.addEventListener('model-loaded', this.onModelLoaded);
  48651. el.addEventListener('axismove', this.onAxisMoved);
  48652. this.controllerEventsActive = true;
  48653. },
  48654. removeEventListeners: function () {
  48655. var el = this.el;
  48656. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48657. el.removeEventListener('buttondown', this.onButtonDown);
  48658. el.removeEventListener('buttonup', this.onButtonUp);
  48659. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48660. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48661. el.removeEventListener('model-loaded', this.onModelLoaded);
  48662. el.removeEventListener('axismove', this.onAxisMoved);
  48663. this.controllerEventsActive = false;
  48664. },
  48665. checkIfControllerPresent: function () {
  48666. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  48667. this.data.hand ? {hand: this.data.hand} : {});
  48668. },
  48669. play: function () {
  48670. this.checkIfControllerPresent();
  48671. this.addControllersUpdateListener();
  48672. },
  48673. pause: function () {
  48674. this.removeEventListeners();
  48675. this.removeControllersUpdateListener();
  48676. },
  48677. injectTrackedControls: function () {
  48678. var el = this.el;
  48679. var data = this.data;
  48680. el.setAttribute('tracked-controls', {
  48681. armModel: data.armModel,
  48682. hand: data.hand,
  48683. idPrefix: GAMEPAD_ID_PREFIX,
  48684. orientationOffset: data.orientationOffset
  48685. });
  48686. if (!this.data.model) { return; }
  48687. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  48688. },
  48689. addControllersUpdateListener: function () {
  48690. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48691. },
  48692. removeControllersUpdateListener: function () {
  48693. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48694. },
  48695. onControllersUpdate: function () {
  48696. this.checkIfControllerPresent();
  48697. },
  48698. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  48699. onModelLoaded: function (evt) {
  48700. var controllerObject3D = evt.detail.model;
  48701. var buttonMeshes;
  48702. if (!this.data.model) { return; }
  48703. buttonMeshes = this.buttonMeshes = {};
  48704. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  48705. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  48706. buttonMeshes.touchpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  48707. },
  48708. onButtonChanged: function (evt) {
  48709. var button = this.mapping.buttons[evt.detail.id];
  48710. if (!button) return;
  48711. // Pass along changed event with button state, using button mapping for convenience.
  48712. this.el.emit(button + 'changed', evt.detail.state);
  48713. },
  48714. onAxisMoved: function (evt) {
  48715. emitIfAxesChanged(this, this.mapping.axes, evt);
  48716. },
  48717. updateModel: function (buttonName, evtName) {
  48718. if (!this.data.model) { return; }
  48719. this.updateButtonModel(buttonName, evtName);
  48720. },
  48721. updateButtonModel: function (buttonName, state) {
  48722. var buttonMeshes = this.buttonMeshes;
  48723. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  48724. var color;
  48725. var button;
  48726. switch (state) {
  48727. case 'down':
  48728. color = this.data.buttonHighlightColor;
  48729. break;
  48730. case 'touchstart':
  48731. color = this.data.buttonTouchedColor;
  48732. break;
  48733. default:
  48734. color = this.data.buttonColor;
  48735. }
  48736. button = buttonMeshes[buttonName];
  48737. button.material.color.set(color);
  48738. this.rendererSystem.applyColorCorrection(button.material.color);
  48739. }
  48740. });
  48741. },{"../core/component":135,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],98:[function(require,module,exports){
  48742. var bind = require('../utils/bind');
  48743. var registerComponent = require('../core/component').registerComponent;
  48744. var THREE = require('../lib/three');
  48745. var trackedControlsUtils = require('../utils/tracked-controls');
  48746. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48747. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48748. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48749. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  48750. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  48751. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  48752. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  48753. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  48754. // First generation model URL.
  48755. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  48756. var OCULUS_TOUCH_WEBVR = {
  48757. left: {
  48758. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  48759. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  48760. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  48761. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48762. },
  48763. right: {
  48764. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  48765. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  48766. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  48767. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48768. }
  48769. };
  48770. var OCULUS_TOUCH_WEBXR = {
  48771. left: {
  48772. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  48773. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  48774. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  48775. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  48776. },
  48777. right: {
  48778. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  48779. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  48780. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  48781. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  48782. }
  48783. };
  48784. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  48785. var CONTROLLER_DEFAULT = 'oculus-touch';
  48786. var CONTROLLER_PROPERTIES = {
  48787. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  48788. 'oculus-touch-v2': {
  48789. left: {
  48790. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  48791. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  48792. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  48793. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48794. },
  48795. right: {
  48796. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  48797. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  48798. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  48799. modelPivotRotation: new THREE.Euler(0, 0, 0)
  48800. }
  48801. },
  48802. 'oculus-touch-v3': {
  48803. left: {
  48804. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-left.glb',
  48805. rayOrigin: {origin: {x: 0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  48806. modelPivotOffset: new THREE.Vector3(0.01, -0.01, 0.05),
  48807. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  48808. },
  48809. right: {
  48810. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-right.glb',
  48811. rayOrigin: {origin: {x: -0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  48812. modelPivotOffset: new THREE.Vector3(-0.01, -0.01, 0.05),
  48813. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  48814. }
  48815. }
  48816. };
  48817. /**
  48818. * Button indices:
  48819. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  48820. * 1 - trigger (with analog value, which goes up to 1)
  48821. * 2 - grip (with analog value, which goes up to 1)
  48822. * 3 - X (left) or A (right)
  48823. * 4 - Y (left) or B (right)
  48824. * 5 - surface (touch only)
  48825. */
  48826. var INPUT_MAPPING_WEBVR = {
  48827. left: {
  48828. axes: {thumbstick: [0, 1]},
  48829. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  48830. },
  48831. right: {
  48832. axes: {thumbstick: [0, 1]},
  48833. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  48834. }
  48835. };
  48836. /**
  48837. * Button indices:
  48838. * 0 - trigger
  48839. * 1 - grip
  48840. * 2 - none
  48841. * 3 - thumbstick
  48842. * 4 - X or A button
  48843. * 5 - Y or B button
  48844. * 6 - surface
  48845. *
  48846. * Axis:
  48847. * 0 - none
  48848. * 1 - none
  48849. * 2 - thumbstick
  48850. * 3 - thumbstick
  48851. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  48852. */
  48853. var INPUT_MAPPING_WEBXR = {
  48854. left: {
  48855. axes: {thumbstick: [2, 3]},
  48856. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  48857. },
  48858. right: {
  48859. axes: {thumbstick: [2, 3]},
  48860. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  48861. }
  48862. };
  48863. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  48864. /**
  48865. * Oculus Touch controls.
  48866. * Interface with Oculus Touch controllers and map Gamepad events to
  48867. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  48868. * Load a controller model and highlight the pressed buttons.
  48869. */
  48870. module.exports.Component = registerComponent('oculus-touch-controls', {
  48871. schema: {
  48872. hand: {default: 'left'},
  48873. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  48874. buttonTouchColor: {type: 'color', default: '#8AB'},
  48875. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  48876. model: {default: true},
  48877. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2', 'oculus-touch-v3']},
  48878. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  48879. },
  48880. mapping: INPUT_MAPPING,
  48881. bindMethods: function () {
  48882. this.onModelLoaded = bind(this.onModelLoaded, this);
  48883. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48884. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48885. this.onAxisMoved = bind(this.onAxisMoved, this);
  48886. },
  48887. init: function () {
  48888. var self = this;
  48889. this.onButtonChanged = bind(this.onButtonChanged, this);
  48890. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  48891. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  48892. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  48893. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  48894. this.controllerPresent = false;
  48895. this.lastControllerCheck = 0;
  48896. this.previousButtonValues = {};
  48897. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48898. this.bindMethods();
  48899. },
  48900. addEventListeners: function () {
  48901. var el = this.el;
  48902. el.addEventListener('buttonchanged', this.onButtonChanged);
  48903. el.addEventListener('buttondown', this.onButtonDown);
  48904. el.addEventListener('buttonup', this.onButtonUp);
  48905. el.addEventListener('touchstart', this.onButtonTouchStart);
  48906. el.addEventListener('touchend', this.onButtonTouchEnd);
  48907. el.addEventListener('axismove', this.onAxisMoved);
  48908. el.addEventListener('model-loaded', this.onModelLoaded);
  48909. this.controllerEventsActive = true;
  48910. },
  48911. removeEventListeners: function () {
  48912. var el = this.el;
  48913. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48914. el.removeEventListener('buttondown', this.onButtonDown);
  48915. el.removeEventListener('buttonup', this.onButtonUp);
  48916. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48917. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48918. el.removeEventListener('axismove', this.onAxisMoved);
  48919. el.removeEventListener('model-loaded', this.onModelLoaded);
  48920. this.controllerEventsActive = false;
  48921. },
  48922. checkIfControllerPresent: function () {
  48923. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  48924. hand: this.data.hand
  48925. });
  48926. },
  48927. play: function () {
  48928. this.checkIfControllerPresent();
  48929. this.addControllersUpdateListener();
  48930. },
  48931. pause: function () {
  48932. this.removeEventListeners();
  48933. this.removeControllersUpdateListener();
  48934. },
  48935. loadModel: function (controller) {
  48936. var data = this.data;
  48937. var controllerId;
  48938. if (!data.model) { return; }
  48939. // Set the controller display model based on the data passed in.
  48940. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  48941. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  48942. // This only works for WebVR currently.
  48943. if (data.controllerType === 'auto') {
  48944. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  48945. // WebVR
  48946. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  48947. var displayName = trackedControlsSystem.vrDisplay.displayName;
  48948. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  48949. if (/^Oculus Quest$/.test(displayName)) {
  48950. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  48951. }
  48952. } else { // WebXR
  48953. controllerId = CONTROLLER_DEFAULT;
  48954. controllerId = controller.profiles.indexOf('oculus-touch-v2') !== -1 ? 'oculus-touch-v2' : controllerId;
  48955. controllerId = controller.profiles.indexOf('oculus-touch-v3') !== -1 ? 'oculus-touch-v3' : controllerId;
  48956. this.displayModel = CONTROLLER_PROPERTIES[controllerId];
  48957. }
  48958. }
  48959. var modelUrl = this.displayModel[data.hand].modelUrl;
  48960. this.el.setAttribute('gltf-model', modelUrl);
  48961. },
  48962. injectTrackedControls: function (controller) {
  48963. var data = this.data;
  48964. var webXRId = GAMEPAD_ID_WEBXR;
  48965. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  48966. var id = isWebXRAvailable ? webXRId : webVRId;
  48967. this.el.setAttribute('tracked-controls', {
  48968. id: id,
  48969. hand: data.hand,
  48970. orientationOffset: data.orientationOffset,
  48971. handTrackingEnabled: false
  48972. });
  48973. this.loadModel(controller);
  48974. },
  48975. addControllersUpdateListener: function () {
  48976. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48977. },
  48978. removeControllersUpdateListener: function () {
  48979. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48980. },
  48981. onControllersUpdate: function () {
  48982. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  48983. this.checkIfControllerPresent();
  48984. },
  48985. onButtonChanged: function (evt) {
  48986. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  48987. var buttonMeshes = this.buttonMeshes;
  48988. var analogValue;
  48989. if (!button) { return; }
  48990. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  48991. // Update trigger and/or grip meshes, if any.
  48992. if (buttonMeshes) {
  48993. if (button === 'trigger' && buttonMeshes.trigger) {
  48994. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  48995. }
  48996. if (button === 'grip' && buttonMeshes.grip) {
  48997. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  48998. }
  48999. }
  49000. // Pass along changed event with button state, using the buttom mapping for convenience.
  49001. this.el.emit(button + 'changed', evt.detail.state);
  49002. },
  49003. onModelLoaded: function (evt) {
  49004. var controllerObject3D = this.controllerObject3D = evt.detail.model;
  49005. var buttonMeshes;
  49006. if (!this.data.model) { return; }
  49007. buttonMeshes = this.buttonMeshes = {};
  49008. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  49009. this.originalXPositionGrip = buttonMeshes.grip && buttonMeshes.grip.position.x;
  49010. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  49011. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  49012. this.originalXRotationTrigger = buttonMeshes.trigger && buttonMeshes.trigger.rotation.x;
  49013. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  49014. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  49015. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  49016. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  49017. // Offset pivot point
  49018. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  49019. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  49020. this.el.emit('controllermodelready', {
  49021. name: 'oculus-touch-controls',
  49022. model: this.data.model,
  49023. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  49024. });
  49025. },
  49026. onAxisMoved: function (evt) {
  49027. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  49028. },
  49029. updateModel: function (buttonName, evtName) {
  49030. if (!this.data.model) { return; }
  49031. this.updateButtonModel(buttonName, evtName);
  49032. },
  49033. updateButtonModel: function (buttonName, state) {
  49034. var button;
  49035. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  49036. var buttonMeshes = this.buttonMeshes;
  49037. if (!this.data.model) { return; }
  49038. if (buttonMeshes && buttonMeshes[buttonName]) {
  49039. button = buttonMeshes[buttonName];
  49040. button.material.color.set(color);
  49041. this.rendererSystem.applyColorCorrection(button.material.color);
  49042. }
  49043. }
  49044. });
  49045. },{"../core/component":135,"../lib/three":183,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],99:[function(require,module,exports){
  49046. var registerComponent = require('../core/component').registerComponent;
  49047. module.exports.Component = registerComponent('position', {
  49048. schema: {type: 'vec3'},
  49049. update: function () {
  49050. var object3D = this.el.object3D;
  49051. var data = this.data;
  49052. object3D.position.set(data.x, data.y, data.z);
  49053. },
  49054. remove: function () {
  49055. // Pretty much for mixins.
  49056. this.el.object3D.position.set(0, 0, 0);
  49057. }
  49058. });
  49059. },{"../core/component":135}],100:[function(require,module,exports){
  49060. /* global MutationObserver */
  49061. var registerComponent = require('../core/component').registerComponent;
  49062. var THREE = require('../lib/three');
  49063. var utils = require('../utils/');
  49064. var warn = utils.debug('components:raycaster:warn');
  49065. // Defines selectors that should be 'safe' for the MutationObserver used to
  49066. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  49067. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  49068. // reliably detected and are therefore disallowed.
  49069. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  49070. // Configuration for the MutationObserver used to refresh the whitelist.
  49071. // Listens for addition/removal of elements and attributes within the scene.
  49072. var OBSERVER_CONFIG = {
  49073. childList: true,
  49074. attributes: true,
  49075. subtree: true
  49076. };
  49077. var EVENTS = {
  49078. INTERSECT: 'raycaster-intersected',
  49079. INTERSECTION: 'raycaster-intersection',
  49080. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  49081. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  49082. };
  49083. /**
  49084. * Raycaster component.
  49085. *
  49086. * Pass options to three.js Raycaster including which objects to test.
  49087. * Poll for intersections.
  49088. * Emit event on origin entity and on target entity on intersect.
  49089. *
  49090. * @member {array} intersectedEls - List of currently intersected entities.
  49091. * @member {array} objects - Cached list of meshes to intersect.
  49092. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  49093. * @member {object} raycaster - three.js Raycaster.
  49094. */
  49095. module.exports.Component = registerComponent('raycaster', {
  49096. schema: {
  49097. autoRefresh: {default: true},
  49098. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  49099. enabled: {default: true},
  49100. far: {default: 1000},
  49101. interval: {default: 0},
  49102. near: {default: 0},
  49103. objects: {default: ''},
  49104. origin: {type: 'vec3'},
  49105. showLine: {default: false},
  49106. lineColor: {default: 'white'},
  49107. lineOpacity: {default: 1},
  49108. useWorldCoordinates: {default: false}
  49109. },
  49110. multiple: true,
  49111. init: function () {
  49112. this.clearedIntersectedEls = [];
  49113. this.unitLineEndVec3 = new THREE.Vector3();
  49114. this.intersectedEls = [];
  49115. this.intersections = [];
  49116. this.newIntersectedEls = [];
  49117. this.newIntersections = [];
  49118. this.objects = [];
  49119. this.prevCheckTime = undefined;
  49120. this.prevIntersectedEls = [];
  49121. this.rawIntersections = [];
  49122. this.raycaster = new THREE.Raycaster();
  49123. this.updateOriginDirection();
  49124. this.setDirty = this.setDirty.bind(this);
  49125. this.updateLine = this.updateLine.bind(this);
  49126. this.observer = new MutationObserver(this.setDirty);
  49127. this.dirty = true;
  49128. this.lineEndVec3 = new THREE.Vector3();
  49129. this.otherLineEndVec3 = new THREE.Vector3();
  49130. this.lineData = {end: this.lineEndVec3};
  49131. this.getIntersection = this.getIntersection.bind(this);
  49132. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  49133. this.intersectedClearedDetail = {el: this.el};
  49134. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  49135. this.intersectionDetail = {};
  49136. },
  49137. /**
  49138. * Create or update raycaster object.
  49139. */
  49140. update: function (oldData) {
  49141. var data = this.data;
  49142. var el = this.el;
  49143. var raycaster = this.raycaster;
  49144. // Set raycaster properties.
  49145. raycaster.far = data.far;
  49146. raycaster.near = data.near;
  49147. // Draw line.
  49148. if (data.showLine &&
  49149. (data.far !== oldData.far || data.origin !== oldData.origin ||
  49150. data.direction !== oldData.direction || !oldData.showLine)) {
  49151. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  49152. // adjust line length.
  49153. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  49154. this.drawLine();
  49155. }
  49156. if (!data.showLine && oldData.showLine) {
  49157. el.removeAttribute('line');
  49158. }
  49159. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  49160. warn('[raycaster] Selector "' + data.objects +
  49161. '" may not update automatically with DOM changes.');
  49162. }
  49163. if (!data.objects) {
  49164. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  49165. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  49166. 'e.g., raycaster="objects: [data-raycastable]".');
  49167. }
  49168. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  49169. data.autoRefresh
  49170. ? this.addEventListeners()
  49171. : this.removeEventListeners();
  49172. }
  49173. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  49174. this.setDirty();
  49175. },
  49176. play: function () {
  49177. this.addEventListeners();
  49178. },
  49179. pause: function () {
  49180. this.removeEventListeners();
  49181. },
  49182. remove: function () {
  49183. if (this.data.showLine) {
  49184. this.el.removeAttribute('line');
  49185. }
  49186. this.clearAllIntersections();
  49187. },
  49188. addEventListeners: function () {
  49189. if (!this.data.autoRefresh) { return; }
  49190. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  49191. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  49192. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  49193. },
  49194. removeEventListeners: function () {
  49195. this.observer.disconnect();
  49196. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  49197. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  49198. },
  49199. /**
  49200. * Mark the object list as dirty, to be refreshed before next raycast.
  49201. */
  49202. setDirty: function () {
  49203. this.dirty = true;
  49204. },
  49205. /**
  49206. * Update list of objects to test for intersection.
  49207. */
  49208. refreshObjects: function () {
  49209. var data = this.data;
  49210. var els;
  49211. // If objects not defined, intersect with everything.
  49212. els = data.objects
  49213. ? this.el.sceneEl.querySelectorAll(data.objects)
  49214. : this.el.sceneEl.querySelectorAll('*');
  49215. this.objects = this.flattenObject3DMaps(els);
  49216. this.dirty = false;
  49217. },
  49218. /**
  49219. * Check for intersections and cleared intersections on an interval.
  49220. */
  49221. tock: function (time) {
  49222. var data = this.data;
  49223. var prevCheckTime = this.prevCheckTime;
  49224. if (!data.enabled) { return; }
  49225. // Only check for intersection if interval time has passed.
  49226. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  49227. // Update check time.
  49228. this.prevCheckTime = time;
  49229. this.checkIntersections();
  49230. },
  49231. /**
  49232. * Raycast for intersections and emit events for current and cleared intersections.
  49233. */
  49234. checkIntersections: function () {
  49235. var clearedIntersectedEls = this.clearedIntersectedEls;
  49236. var el = this.el;
  49237. var data = this.data;
  49238. var i;
  49239. var intersectedEls = this.intersectedEls;
  49240. var intersection;
  49241. var intersections = this.intersections;
  49242. var newIntersectedEls = this.newIntersectedEls;
  49243. var newIntersections = this.newIntersections;
  49244. var prevIntersectedEls = this.prevIntersectedEls;
  49245. var rawIntersections = this.rawIntersections;
  49246. // Refresh the object whitelist if needed.
  49247. if (this.dirty) { this.refreshObjects(); }
  49248. // Store old previously intersected entities.
  49249. copyArray(this.prevIntersectedEls, this.intersectedEls);
  49250. // Raycast.
  49251. this.updateOriginDirection();
  49252. rawIntersections.length = 0;
  49253. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  49254. // Only keep intersections against objects that have a reference to an entity.
  49255. intersections.length = 0;
  49256. intersectedEls.length = 0;
  49257. for (i = 0; i < rawIntersections.length; i++) {
  49258. intersection = rawIntersections[i];
  49259. // Don't intersect with own line.
  49260. if (data.showLine && intersection.object === el.getObject3D('line')) {
  49261. continue;
  49262. }
  49263. if (intersection.object.el) {
  49264. intersections.push(intersection);
  49265. intersectedEls.push(intersection.object.el);
  49266. }
  49267. }
  49268. // Get newly intersected entities.
  49269. newIntersections.length = 0;
  49270. newIntersectedEls.length = 0;
  49271. for (i = 0; i < intersections.length; i++) {
  49272. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  49273. newIntersections.push(intersections[i]);
  49274. newIntersectedEls.push(intersections[i].object.el);
  49275. }
  49276. }
  49277. // Emit intersection cleared on both entities per formerly intersected entity.
  49278. clearedIntersectedEls.length = 0;
  49279. for (i = 0; i < prevIntersectedEls.length; i++) {
  49280. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  49281. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  49282. this.intersectedClearedDetail);
  49283. clearedIntersectedEls.push(prevIntersectedEls[i]);
  49284. }
  49285. if (clearedIntersectedEls.length) {
  49286. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  49287. }
  49288. // Emit intersected on intersected entity per intersected entity.
  49289. for (i = 0; i < newIntersectedEls.length; i++) {
  49290. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  49291. }
  49292. // Emit all intersections at once on raycasting entity.
  49293. if (newIntersections.length) {
  49294. this.intersectionDetail.els = newIntersectedEls;
  49295. this.intersectionDetail.intersections = newIntersections;
  49296. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  49297. }
  49298. // Update line length.
  49299. if (data.showLine) { setTimeout(this.updateLine); }
  49300. },
  49301. updateLine: function () {
  49302. var el = this.el;
  49303. var intersections = this.intersections;
  49304. var lineLength;
  49305. if (intersections.length) {
  49306. if (intersections[0].object.el === el && intersections[1]) {
  49307. lineLength = intersections[1].distance;
  49308. } else {
  49309. lineLength = intersections[0].distance;
  49310. }
  49311. }
  49312. this.drawLine(lineLength);
  49313. },
  49314. /**
  49315. * Return the most recent intersection details for a given entity, if any.
  49316. * @param {AEntity} el
  49317. * @return {Object}
  49318. */
  49319. getIntersection: function (el) {
  49320. var i;
  49321. var intersection;
  49322. for (i = 0; i < this.intersections.length; i++) {
  49323. intersection = this.intersections[i];
  49324. if (intersection.object.el === el) { return intersection; }
  49325. }
  49326. return null;
  49327. },
  49328. /**
  49329. * Update origin and direction of raycaster using entity transforms and supplied origin or
  49330. * direction offsets.
  49331. */
  49332. updateOriginDirection: (function () {
  49333. var direction = new THREE.Vector3();
  49334. var originVec3 = new THREE.Vector3();
  49335. // Closure to make quaternion/vector3 objects private.
  49336. return function updateOriginDirection () {
  49337. var el = this.el;
  49338. var data = this.data;
  49339. if (data.useWorldCoordinates) {
  49340. this.raycaster.set(data.origin, data.direction);
  49341. return;
  49342. }
  49343. el.object3D.updateMatrixWorld();
  49344. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  49345. // If non-zero origin, translate the origin into world space.
  49346. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  49347. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  49348. }
  49349. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  49350. // provide. Apply the offset to the direction, then rotation from the object,
  49351. // and normalize.
  49352. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  49353. // Apply offset and direction, in world coordinates.
  49354. this.raycaster.set(originVec3, direction);
  49355. };
  49356. })(),
  49357. /**
  49358. * Create or update line to give raycaster visual representation.
  49359. * Customize the line through through line component.
  49360. * We draw the line in the raycaster component to customize the line to the
  49361. * raycaster's origin, direction, and far.
  49362. *
  49363. * Unlike the raycaster, we create the line as a child of the object. The line will
  49364. * be affected by the transforms of the objects, so we don't have to calculate transforms
  49365. * like we do with the raycaster.
  49366. *
  49367. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  49368. * point. If not provided, length will default to the max length, `raycaster.far`.
  49369. */
  49370. drawLine: function (length) {
  49371. var data = this.data;
  49372. var el = this.el;
  49373. var endVec3;
  49374. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  49375. endVec3 = this.lineData.end === this.lineEndVec3
  49376. ? this.otherLineEndVec3
  49377. : this.lineEndVec3;
  49378. // Treat Infinity as 1000m for the line.
  49379. if (length === undefined) {
  49380. length = data.far === Infinity ? 1000 : data.far;
  49381. }
  49382. // Update the length of the line if given. `unitLineEndVec3` is the direction
  49383. // given by data.direction, then we apply a scalar to give it a length.
  49384. this.lineData.start = data.origin;
  49385. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  49386. this.lineData.color = data.lineColor;
  49387. this.lineData.opacity = data.lineOpacity;
  49388. el.setAttribute('line', this.lineData);
  49389. },
  49390. /**
  49391. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  49392. * Children are flattened by one level, removing the THREE.Group wrapper,
  49393. * so that non-recursive raycasting remains useful.
  49394. *
  49395. * Only push children defined as component attachements (e.g., setObject3D),
  49396. * NOT actual children in the scene graph hierarchy.
  49397. *
  49398. * @param {Array<Element>} els
  49399. * @return {Array<THREE.Object3D>}
  49400. */
  49401. flattenObject3DMaps: function (els) {
  49402. var key;
  49403. var i;
  49404. var objects = this.objects;
  49405. // Push meshes and other attachments onto list of objects to intersect.
  49406. objects.length = 0;
  49407. for (i = 0; i < els.length; i++) {
  49408. if (els[i].isEntity && els[i].object3D) {
  49409. for (key in els[i].object3DMap) {
  49410. objects.push(els[i].getObject3D(key));
  49411. }
  49412. }
  49413. }
  49414. return objects;
  49415. },
  49416. clearAllIntersections: function () {
  49417. var i;
  49418. for (i = 0; i < this.intersectedEls.length; i++) {
  49419. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  49420. this.intersectedClearedDetail);
  49421. }
  49422. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  49423. this.intersectedEls.length = 0;
  49424. this.intersections.length = 0;
  49425. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  49426. }
  49427. });
  49428. /**
  49429. * Copy contents of one array to another without allocating new array.
  49430. */
  49431. function copyArray (a, b) {
  49432. var i;
  49433. a.length = b.length;
  49434. for (i = 0; i < b.length; i++) {
  49435. a[i] = b[i];
  49436. }
  49437. }
  49438. },{"../core/component":135,"../lib/three":183,"../utils/":210}],101:[function(require,module,exports){
  49439. var degToRad = require('../lib/three').Math.degToRad;
  49440. var registerComponent = require('../core/component').registerComponent;
  49441. module.exports.Component = registerComponent('rotation', {
  49442. schema: {type: 'vec3'},
  49443. /**
  49444. * Updates object3D rotation.
  49445. */
  49446. update: function () {
  49447. var data = this.data;
  49448. var object3D = this.el.object3D;
  49449. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  49450. object3D.rotation.order = 'YXZ';
  49451. },
  49452. remove: function () {
  49453. // Pretty much for mixins.
  49454. this.el.object3D.rotation.set(0, 0, 0);
  49455. }
  49456. });
  49457. },{"../core/component":135,"../lib/three":183}],102:[function(require,module,exports){
  49458. var registerComponent = require('../core/component').registerComponent;
  49459. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  49460. var zeroScale = 0.00001;
  49461. module.exports.Component = registerComponent('scale', {
  49462. schema: {
  49463. type: 'vec3',
  49464. default: {x: 1, y: 1, z: 1}
  49465. },
  49466. update: function () {
  49467. var data = this.data;
  49468. var object3D = this.el.object3D;
  49469. var x = data.x === 0 ? zeroScale : data.x;
  49470. var y = data.y === 0 ? zeroScale : data.y;
  49471. var z = data.z === 0 ? zeroScale : data.z;
  49472. object3D.scale.set(x, y, z);
  49473. },
  49474. remove: function () {
  49475. // Pretty much for mixins.
  49476. this.el.object3D.scale.set(1, 1, 1);
  49477. }
  49478. });
  49479. },{"../core/component":135}],103:[function(require,module,exports){
  49480. /* global ImageData, Map, Set */
  49481. var arrowURL = 'data:image/webp;base64,UklGRkQHAABXRUJQVlA4WAoAAAAQAAAA/wEA/wEAQUxQSL0DAAARDzD/ERGCjrY9sYYFfgo6aa1kJ7K0w9Lo3AadLSVeFxevQwj5kuM8RfR/Atw/C0+ozB/oUBrloFZs6ElSW88j1KA4yExNWQaqRZquIDF0JYmlq0hAuUDTFu66tng3teW7pa3cQf1V1edvur54M/Slm6Wv3Gx9zw0MXlQLntcsBN6wkHjTQuYtC4W3LTw8mGRVG57TbAROtxHfZNhInGkjc5aNwtk2Hg6Mvki14k+NkZzCwQgCxalcAv3kddRTPI1DcUrXId1FLf1uHpzaQz4tquhZVLlKesbVpqKeTj0n0F5PpXDlFN9UqmhalL/ImuZFo6KmToWLoKlddMprqlS8cKovBvHo2kTiFV2LN4msaxKZl3QNiair8xYRdDWivIvXVXmbcMqJ51UebZuFXxZt6xd4laxtciqRtA3Cv0nU1t+kEUFbI8JvCa+tvkm3FDlO/W+OR99+kWEp/YYo+tYfTVnf/K8cE/F///3vv//993eeL+a+uvjawLcX3xjYvJotBFY3kVjTRGFtE+BU2AiMbiQyhpHMWEYeBozAH5qNBYRDB5KBCaTDBKKBAZTDBoKBDjwHAN5ABeCJBsAZcAAC0YHHxAYSMYBiYgGZWEA2MYFCbCCZGAAIANFEB+AnYgMQTDQAYSJ2AN5EBZAm4gDgTDgAeSIu4DGygTIRN1CMLOCZiACykQlg4jsAycgA8AO+BxCNdJyDkcbwRirDGXGnx8w+FDPrkM3MQ9JQZMYhiiwV/RDMtIM3U1/DmXHUo+IR2kSR2ToWkQ1NIn2qf2J8LCqJKiDUiSADHY3whirhdHgZ94HKaR97PhE+twEUJUFoAcgyTct8hfSxSkShASDKdMJ/ritKHwgyQ0sD4D/miCxU5SbhOOUDTnZpccCjYP/i0bZ/8bAgtVGEoGapWIQXyzKVKLwgNJFk2rtMIgoNRJlOZF7SNSSyUEeQmbxBFKEmtYjEe8S8zOZ1AkJVCmS88FJOtF40Ksg4oUaFiygk3C8qlTVNyl8UTevCUdAE2t14PfVqU1FPp57TopKeQZWromddTQp6QOfTOEQt/ZDuipZ11w/wOiqO8dRORcc6BQEkDQMClaHcn5wV9yLbxsNZNgpn2sicYSNxuo34Js1G4FQbnuNsOPa28PCWhcKbFjJvWEi8ZiHwqgXPcxbc5db33Cx95WboSzddX7yp+vyN0+eul7ZyN7Xlu64t3jVt4c5pc4JLV5EYupJE0xUknC4nOjVlmaYpyLit53HCQ0+ScnqceNcS5dzUkd0/CwMAVlA4IGADAAAQXwCdASoAAgACP8ne6Wy/tjCpqJ/IA/A5CWlu4XYBG/Pz8AfwD8APz//f3v8E1fuHZnxKYACtfuHZnxKYACrYTb5mOslhxu843ecbvON3nG7zjd3a0VCn7G1MABVxwH/Xd25gAK1+4dmfEpe2+PHhQaj75++riG6FuYACtfuHZnxKYACRrK3q9xO8Ss3uWKnMhs/rDF1hi6wxdYYusMXWGI5QRcCFDZog5OgqNlse1NDuz/UoFa/cOzPiUwAEsAOK4/nu5eZHK2tlXxJfNYlMABWv3Dsz4bvNJ5YA/LtxJ38SmAArX7h2Z8Sk5vdZUYv7mZPiUwAFa/cOzPh21s5OgZxf1mfEpemRyFr/rM+JS9noA/LtxJ38SmAAlUJIotzAASn6TjdhK+D3Dsz4dyvB7h2Z8O2tnJ0DOL+sz4lL2nKLT4lL/+iSLOocxq639w7M34MNZdm55uJ8v8ra2cpVZnxKTq2F3PN/cNksAfl24k7+JTAASqrD37h2Z7b1W+VtbOUqsz4lJ1bC7nm/uGyWAPy7cSd/EpgAJVVh79w7M9t6rfK2tnKVWZ8Sk6thdzzf3DZLAH5duJO/iUwAEqqw9+4dme29VvlbWzlKrM+JSdWwu55v7hslgD8u3EnfxKYACVVYe/cOzPbeq3ytrZylVme0kYJ8557FLerqFrzIbPrrf3DZLAH5duJO/iUvaVMS9BoaF4p7pSDFTP1XMyfElelrM0DOL+sz4eBJ13nV1OppBGPuKb4YzXQgq9uH19uS/0+JS9t9fr6ZUlQBelDG6GMgq97otb5QMPJwtKyBTbFp8Sl7b6/X0ykkawEOsgdiE6Fi0vb/Eve6xkwsmug0Z4nGNHQO8839bpTsjpz7SWIJxKagvd1QWMa6FYT1KEw3j4XDT6vJ9Xk+nyfT5Pq8n1eEmk5dinMM/9Fcfz4Z3Dsz3KD2dw7LxBRxKrqUUGQPH/7zxr1KIfNpLEJ0MZB2ITM/0Z2EFoh12NlXnEcpYcbvON3nG7zjd5xu84vfcNIAAP7+y8ceyzbVxkakPYY4lcr72fqOnDwipv+yxC71wAADBrjKnAAAAAAAAAAAAAAw7oNGHttqWONcoFN/2WIDc2pa6WVFtFYROlsaMaTXdcOjXHz93+YxAglKa4AAAAA=';
  49482. var register = require('../../core/component').registerComponent;
  49483. var THREE = require('../../lib/three');
  49484. var CAM_LAYER = 21;
  49485. var applyPose = (function () {
  49486. var tempQuaternion = new THREE.Quaternion();
  49487. var tempVec3 = new THREE.Vector3();
  49488. function applyPose (pose, object3D, offset) {
  49489. object3D.position.copy(pose.transform.position);
  49490. object3D.quaternion.copy(pose.transform.orientation);
  49491. tempVec3.copy(offset);
  49492. tempQuaternion.copy(pose.transform.orientation);
  49493. tempVec3.applyQuaternion(tempQuaternion);
  49494. object3D.position.sub(tempVec3);
  49495. }
  49496. return applyPose;
  49497. }());
  49498. applyPose.tempFakePose = {
  49499. transform: {
  49500. orientation: new THREE.Quaternion(),
  49501. position: new THREE.Vector3()
  49502. }
  49503. };
  49504. /**
  49505. * Class to handle hit-test from a single source
  49506. *
  49507. * For a normal space provide it as a space option
  49508. * new HitTest(renderer, {
  49509. * space: viewerSpace
  49510. * });
  49511. *
  49512. * this is also useful for the targetRaySpace of an XRInputSource
  49513. *
  49514. * It can also describe a transient input source like so:
  49515. *
  49516. * var profileToSupport = 'generic-touchscreen';
  49517. * var transientHitTest = new HitTest(renderer, {
  49518. * profile: profileToSupport
  49519. * });
  49520. *
  49521. * Where the profile matches an item in a type of controller, profiles matching 'generic-touchscreen'
  49522. * will always be a transient input and as of 08/2021 all transient inputs are 'generic-touchscreen'
  49523. *
  49524. * @param {WebGLRenderer} renderer THREE.JS Renderer
  49525. * @param {} hitTestSourceDetails The source information either as the information for a transient hit-test or a regular hit-test
  49526. */
  49527. function HitTest (renderer, hitTestSourceDetails) {
  49528. this.renderer = renderer;
  49529. this.xrHitTestSource = null;
  49530. renderer.xr.addEventListener('sessionend', function () {
  49531. this.xrHitTestSource = null;
  49532. }.bind(this));
  49533. renderer.xr.addEventListener('sessionstart', function () {
  49534. this.sessionStart(hitTestSourceDetails);
  49535. }.bind(this));
  49536. if (this.renderer.xr.isPresenting) {
  49537. this.sessionStart(hitTestSourceDetails);
  49538. }
  49539. }
  49540. HitTest.prototype.previousFrameAnchors = new Set();
  49541. HitTest.prototype.anchorToObject3D = new Map();
  49542. function warnAboutHitTest (e) {
  49543. console.warn(e.message);
  49544. console.warn('Cannot requestHitTestSource Are you missing: webxr="optionalFeatures: hit-test;" from <a-scene>?');
  49545. }
  49546. HitTest.prototype.sessionStart = function sessionStart (hitTestSourceDetails) {
  49547. this.session = this.renderer.xr.getSession();
  49548. if (!('requestHitTestSource' in this.session)) {
  49549. warnAboutHitTest({message: 'No requestHitTestSource on the session.'});
  49550. return;
  49551. }
  49552. if (hitTestSourceDetails.space) {
  49553. this.session.requestHitTestSource(hitTestSourceDetails)
  49554. .then(function (xrHitTestSource) {
  49555. this.xrHitTestSource = xrHitTestSource;
  49556. }.bind(this))
  49557. .catch(warnAboutHitTest);
  49558. } else if (hitTestSourceDetails.profile) {
  49559. this.session.requestHitTestSourceForTransientInput(hitTestSourceDetails)
  49560. .then(function (xrHitTestSource) {
  49561. this.xrHitTestSource = xrHitTestSource;
  49562. this.transient = true;
  49563. }.bind(this))
  49564. .catch(warnAboutHitTest);
  49565. }
  49566. };
  49567. /**
  49568. * Turns the last hit test into an anchor, the provided Object3D will have it's
  49569. * position update to track the anchor.
  49570. *
  49571. * @param {Object3D} object3D object to track
  49572. * @param {Vector3} offset offset of the object from the origin that gets subtracted
  49573. * @returns
  49574. */
  49575. HitTest.prototype.anchorFromLastHitTestResult = function (object3D, offset) {
  49576. var hitTest = this.lastHitTest;
  49577. if (!hitTest) { return; }
  49578. var object3DOptions = {
  49579. object3D: object3D,
  49580. offset: offset
  49581. };
  49582. Array.from(this.anchorToObject3D.entries())
  49583. .forEach(function (entry) {
  49584. var entryObject = entry[1].object3D;
  49585. var anchor = entry[0];
  49586. if (entryObject === object3D) {
  49587. this.anchorToObject3D.delete(anchor);
  49588. anchor.delete();
  49589. }
  49590. }.bind(this));
  49591. if (hitTest.createAnchor) {
  49592. hitTest.createAnchor()
  49593. .then(function (anchor) {
  49594. this.anchorToObject3D.set(anchor, object3DOptions);
  49595. }.bind(this))
  49596. .catch(function (e) {
  49597. console.warn(e.message);
  49598. console.warn('Cannot create anchor, are you missing: webxr="optionalFeatures: anchors;" from <a-scene>?');
  49599. });
  49600. }
  49601. };
  49602. HitTest.prototype.doHit = function doHit (frame) {
  49603. if (!this.renderer.xr.isPresenting) { return; }
  49604. var refSpace = this.renderer.xr.getReferenceSpace();
  49605. var xrViewerPose = frame.getViewerPose(refSpace);
  49606. var hitTestResults;
  49607. var results;
  49608. if (this.xrHitTestSource && xrViewerPose) {
  49609. if (this.transient) {
  49610. hitTestResults = frame.getHitTestResultsForTransientInput(this.xrHitTestSource);
  49611. if (hitTestResults.length > 0) {
  49612. results = hitTestResults[0].results;
  49613. if (results.length > 0) {
  49614. this.lastHitTest = results[0];
  49615. return results[0].getPose(refSpace);
  49616. } else {
  49617. return false;
  49618. }
  49619. } else {
  49620. return false;
  49621. }
  49622. } else {
  49623. hitTestResults = frame.getHitTestResults(this.xrHitTestSource);
  49624. if (hitTestResults.length > 0) {
  49625. this.lastHitTest = hitTestResults[0];
  49626. return hitTestResults[0].getPose(refSpace);
  49627. } else {
  49628. return false;
  49629. }
  49630. }
  49631. }
  49632. };
  49633. // static function
  49634. HitTest.updateAnchorPoses = function (frame, refSpace) {
  49635. // If tracked anchors isn't defined because it's not supported then just use the empty set
  49636. var trackedAnchors = frame.trackedAnchors || HitTest.prototype.previousFrameAnchors;
  49637. HitTest.prototype.previousFrameAnchors.forEach(function (anchor) {
  49638. // Handle anchor tracking loss - `anchor` was present
  49639. // in the present frame but is no longer tracked.
  49640. if (!trackedAnchors.has(anchor)) {
  49641. HitTest.prototype.anchorToObject3D.delete(anchor);
  49642. }
  49643. });
  49644. trackedAnchors.forEach(function (anchor) {
  49645. var anchorPose;
  49646. var object3DOptions;
  49647. var offset;
  49648. var object3D;
  49649. try {
  49650. // Query most recent pose of the anchor relative to some reference space:
  49651. anchorPose = frame.getPose(anchor.anchorSpace, refSpace);
  49652. } catch (e) {
  49653. // This will fail if the anchor has been deleted that frame
  49654. }
  49655. if (anchorPose) {
  49656. object3DOptions = HitTest.prototype.anchorToObject3D.get(anchor);
  49657. offset = object3DOptions.offset;
  49658. object3D = object3DOptions.object3D;
  49659. applyPose(anchorPose, object3D, offset);
  49660. }
  49661. });
  49662. };
  49663. var hitTestCache;
  49664. module.exports.Component = register('ar-hit-test', {
  49665. schema: {
  49666. target: { type: 'selector' },
  49667. enabled: { default: true },
  49668. src: {
  49669. default: arrowURL,
  49670. type: 'map'
  49671. },
  49672. type: {
  49673. default: 'footprint',
  49674. oneOf: ['footprint', 'map']
  49675. },
  49676. footprintDepth: {
  49677. default: 0.1
  49678. },
  49679. mapSize: {
  49680. type: 'vec2',
  49681. default: {
  49682. x: 0.5,
  49683. y: 0.5
  49684. }
  49685. }
  49686. },
  49687. init: function () {
  49688. this.hitTest = null;
  49689. this.imageDataArray = new Uint8ClampedArray(512 * 512 * 4);
  49690. this.imageData = new ImageData(this.imageDataArray, 512, 512);
  49691. this.textureCache = new Map();
  49692. this.orthoCam = new THREE.OrthographicCamera();
  49693. this.orthoCam.layers.set(CAM_LAYER);
  49694. this.textureTarget = new THREE.WebGLRenderTarget(512, 512, {});
  49695. this.basicMaterial = new THREE.MeshBasicMaterial({
  49696. color: 0x000000,
  49697. side: THREE.DoubleSide
  49698. });
  49699. this.canvas = document.createElement('canvas');
  49700. this.context = this.canvas.getContext('2d');
  49701. this.context.imageSmoothingEnabled = false;
  49702. this.canvas.width = 512;
  49703. this.canvas.height = 512;
  49704. this.canvasTexture = new THREE.CanvasTexture(this.canvas, {
  49705. alpha: true
  49706. });
  49707. this.canvasTexture.flipY = false;
  49708. // Update WebXR to support hit-test and anchors
  49709. var webxrData = this.el.getAttribute('webxr');
  49710. var optionalFeaturesArray = webxrData.optionalFeatures;
  49711. if (
  49712. !optionalFeaturesArray.includes('hit-test') ||
  49713. !optionalFeaturesArray.includes('anchors')
  49714. ) {
  49715. optionalFeaturesArray.push('hit-test');
  49716. optionalFeaturesArray.push('anchors');
  49717. this.el.setAttribute('webxr', webxrData);
  49718. }
  49719. this.el.sceneEl.renderer.xr.addEventListener('sessionend', function () {
  49720. this.hitTest = null;
  49721. }.bind(this));
  49722. this.el.sceneEl.renderer.xr.addEventListener('sessionstart', function () {
  49723. var renderer = this.el.sceneEl.renderer;
  49724. var session = this.session = renderer.xr.getSession();
  49725. this.hasPosedOnce = false;
  49726. this.bboxMesh.visible = false;
  49727. if (!hitTestCache) { hitTestCache = new Map(); }
  49728. // Default to selecting through the face
  49729. session.requestReferenceSpace('viewer')
  49730. .then(function (viewerSpace) {
  49731. this.hitTest = new HitTest(renderer, {
  49732. space: viewerSpace
  49733. });
  49734. hitTestCache.set(viewerSpace, this.hitTest);
  49735. this.el.emit('ar-hit-test-start');
  49736. }.bind(this));
  49737. // These are transient inputs so need to be handled seperately
  49738. var profileToSupport = 'generic-touchscreen';
  49739. var transientHitTest = new HitTest(renderer, {
  49740. profile: profileToSupport
  49741. });
  49742. session.addEventListener('selectstart', function (e) {
  49743. if (this.data.enabled !== true) { return; }
  49744. var inputSource = e.inputSource;
  49745. this.bboxMesh.visible = true;
  49746. if (this.hasPosedOnce === true) {
  49747. this.el.emit('ar-hit-test-select-start', {
  49748. inputSource: inputSource,
  49749. position: this.bboxMesh.position,
  49750. orientation: this.bboxMesh.quaternion
  49751. });
  49752. if (inputSource.profiles[0] === profileToSupport) {
  49753. this.hitTest = transientHitTest;
  49754. } else {
  49755. this.hitTest = hitTestCache.get(inputSource) || new HitTest(renderer, {
  49756. space: inputSource.targetRaySpace
  49757. });
  49758. hitTestCache.set(inputSource, this.hitTest);
  49759. }
  49760. }
  49761. }.bind(this));
  49762. session.addEventListener('selectend', function (e) {
  49763. if (!this.hitTest || this.data.enabled !== true) {
  49764. this.hitTest = null;
  49765. return;
  49766. }
  49767. var inputSource = e.inputSource;
  49768. var object;
  49769. if (this.hasPosedOnce === true) {
  49770. this.bboxMesh.visible = false;
  49771. // if we have a target with a 3D object then automatically generate an anchor for it.
  49772. if (this.data.target) {
  49773. object = this.data.target.object3D;
  49774. if (object) {
  49775. applyPose.tempFakePose.transform.position.copy(this.bboxMesh.position);
  49776. applyPose.tempFakePose.transform.orientation.copy(this.bboxMesh.quaternion);
  49777. applyPose(applyPose.tempFakePose, object, this.bboxOffset);
  49778. object.visible = true;
  49779. // create an anchor attatched to the object
  49780. this.hitTest.anchorFromLastHitTestResult(object, this.bboxOffset);
  49781. }
  49782. }
  49783. this.el.emit('ar-hit-test-select', {
  49784. inputSource: inputSource,
  49785. position: this.bboxMesh.position,
  49786. orientation: this.bboxMesh.quaternion
  49787. });
  49788. }
  49789. this.hitTest = null;
  49790. }.bind(this));
  49791. }.bind(this));
  49792. this.bboxOffset = new THREE.Vector3();
  49793. this.update = this.update.bind(this);
  49794. this.makeBBox();
  49795. },
  49796. update: function () {
  49797. if (this.data.target) {
  49798. if (this.data.target.object3D) {
  49799. this.data.target.addEventListener('model-loaded', this.update);
  49800. this.data.target.object3D.layers.enable(CAM_LAYER);
  49801. this.data.target.object3D.traverse(function (child) {
  49802. child.layers.enable(CAM_LAYER);
  49803. });
  49804. } else {
  49805. this.data.target.addEventListener('loaded', this.update, {once: true});
  49806. }
  49807. }
  49808. this.bboxNeedsUpdate = true;
  49809. },
  49810. makeBBox: function () {
  49811. var geometry = new THREE.PlaneGeometry(1, 1);
  49812. var material = new THREE.MeshBasicMaterial({
  49813. transparent: true,
  49814. color: 0xffffff
  49815. });
  49816. geometry.rotateX(-Math.PI / 2);
  49817. geometry.rotateY(-Math.PI / 2);
  49818. this.bbox = new THREE.Box3();
  49819. this.bboxMesh = new THREE.Mesh(geometry, material);
  49820. this.el.setObject3D('ar-hit-test', this.bboxMesh);
  49821. this.bboxMesh.visible = false;
  49822. },
  49823. updateFootprint: function () {
  49824. var tempImageData;
  49825. var renderer = this.el.sceneEl.renderer;
  49826. var oldRenderTarget, oldBackground;
  49827. var isXREnabled = renderer.xr.enabled;
  49828. this.bboxMesh.material.map = this.canvasTexture;
  49829. this.bboxMesh.material.needsUpdate = true;
  49830. this.orthoCam.rotation.set(-Math.PI / 2, 0, -Math.PI / 2);
  49831. this.orthoCam.position.copy(this.bboxMesh.position);
  49832. this.orthoCam.position.y -= this.bboxMesh.scale.y / 2;
  49833. this.orthoCam.near = 0.1;
  49834. this.orthoCam.far = this.orthoCam.near + (this.data.footprintDepth * this.bboxMesh.scale.y);
  49835. this.orthoCam.position.y += this.orthoCam.far;
  49836. this.orthoCam.right = this.bboxMesh.scale.z / 2;
  49837. this.orthoCam.left = -this.bboxMesh.scale.z / 2;
  49838. this.orthoCam.top = this.bboxMesh.scale.x / 2;
  49839. this.orthoCam.bottom = -this.bboxMesh.scale.x / 2;
  49840. this.orthoCam.updateProjectionMatrix();
  49841. oldRenderTarget = renderer.getRenderTarget();
  49842. renderer.setRenderTarget(this.textureTarget);
  49843. renderer.xr.enabled = false;
  49844. oldBackground = this.el.object3D.background;
  49845. this.el.object3D.overrideMaterial = this.basicMaterial;
  49846. this.el.object3D.background = null;
  49847. renderer.render(this.el.object3D, this.orthoCam);
  49848. this.el.object3D.background = oldBackground;
  49849. this.el.object3D.overrideMaterial = null;
  49850. renderer.xr.enabled = isXREnabled;
  49851. renderer.setRenderTarget(oldRenderTarget);
  49852. renderer.readRenderTargetPixels(this.textureTarget, 0, 0, 512, 512, this.imageDataArray);
  49853. this.context.putImageData(this.imageData, 0, 0);
  49854. this.context.shadowColor = 'white';
  49855. this.context.shadowBlur = 10;
  49856. this.context.drawImage(this.canvas, 0, 0);
  49857. tempImageData = this.context.getImageData(0, 0, 512, 512);
  49858. for (var i = 0; i < 512 * 512; i++) {
  49859. // if it's a little bit transparent but not opaque make it middle transparent
  49860. if (tempImageData.data[ i * 4 + 3 ] !== 0 && tempImageData.data[ i * 4 + 3 ] !== 255) {
  49861. tempImageData.data[ i * 4 + 3 ] = 128;
  49862. }
  49863. }
  49864. this.context.putImageData(tempImageData, 0, 0);
  49865. this.canvasTexture.needsUpdate = true;
  49866. },
  49867. tick: function () {
  49868. var pose;
  49869. var frame = this.el.sceneEl.frame;
  49870. var renderer = this.el.sceneEl.renderer;
  49871. if (frame) {
  49872. // if we are in XR then update the positions of the objects attatched to anchors
  49873. HitTest.updateAnchorPoses(frame, renderer.xr.getReferenceSpace());
  49874. }
  49875. if (this.bboxNeedsUpdate) {
  49876. this.bboxNeedsUpdate = false;
  49877. if (!this.data.target || this.data.type === 'map') {
  49878. var texture;
  49879. if (this.textureCache.has(this.data.src)) {
  49880. texture = this.textureCache.get(this.data.src);
  49881. } else {
  49882. texture = new THREE.TextureLoader().load(this.data.src);
  49883. this.textureCache.set(this.data.src, texture);
  49884. }
  49885. this.bboxMesh.material.map = texture;
  49886. this.bboxMesh.material.needsUpdate = true;
  49887. }
  49888. if (this.data.target && this.data.target.object3D) {
  49889. this.bbox.setFromObject(this.data.target.object3D);
  49890. this.bbox.getCenter(this.bboxMesh.position);
  49891. this.bbox.getSize(this.bboxMesh.scale);
  49892. if (this.data.type === 'footprint') {
  49893. // Add a little buffer for the footprint border
  49894. this.bboxMesh.scale.x *= 1.04;
  49895. this.bboxMesh.scale.z *= 1.04;
  49896. this.updateFootprint();
  49897. }
  49898. this.bboxMesh.position.y -= this.bboxMesh.scale.y / 2;
  49899. this.bboxOffset.copy(this.bboxMesh.position);
  49900. this.bboxOffset.sub(this.data.target.object3D.position);
  49901. } else {
  49902. this.bboxMesh.scale.set(this.data.mapSize.x, 1, this.data.mapSize.y);
  49903. }
  49904. }
  49905. if (this.hitTest) {
  49906. pose = this.hitTest.doHit(frame);
  49907. if (pose) {
  49908. if (this.hasPosedOnce !== true) {
  49909. this.hasPosedOnce = true;
  49910. this.el.emit('ar-hit-test-achieved');
  49911. }
  49912. this.bboxMesh.visible = true;
  49913. this.bboxMesh.position.copy(pose.transform.position);
  49914. this.bboxMesh.quaternion.copy(pose.transform.orientation);
  49915. }
  49916. }
  49917. }
  49918. });
  49919. },{"../../core/component":135,"../../lib/three":183}],104:[function(require,module,exports){
  49920. /* global THREE, XRWebGLBinding */
  49921. var register = require('../../core/component').registerComponent;
  49922. var COMPONENTS = require('../../core/component').components;
  49923. // source: view-source:https://storage.googleapis.com/chromium-webxr-test/r886480/proposals/lighting-estimation.html
  49924. function updateLights (estimate, probeLight, directionalLight, directionalLightPosition) {
  49925. var intensityScalar =
  49926. Math.max(1.0,
  49927. Math.max(estimate.primaryLightIntensity.x,
  49928. Math.max(estimate.primaryLightIntensity.y,
  49929. estimate.primaryLightIntensity.z)));
  49930. probeLight.sh.fromArray(estimate.sphericalHarmonicsCoefficients);
  49931. probeLight.intensity = 1;
  49932. directionalLight.color.setRGB(
  49933. estimate.primaryLightIntensity.x / intensityScalar,
  49934. estimate.primaryLightIntensity.y / intensityScalar,
  49935. estimate.primaryLightIntensity.z / intensityScalar);
  49936. directionalLight.intensity = intensityScalar;
  49937. directionalLightPosition.copy(estimate.primaryLightDirection);
  49938. }
  49939. module.exports.Component = register('background', {
  49940. schema: {
  49941. color: { type: 'color', default: 'black' },
  49942. transparent: { default: false },
  49943. generateEnvironment: { default: true },
  49944. directionalLight: { type: 'selector' }
  49945. },
  49946. init: function () {
  49947. var self = this;
  49948. this.pmremGenerator = new THREE.PMREMGenerator(this.el.renderer);
  49949. this.pmremGenerator.compileCubemapShader();
  49950. this.cubeRenderTarget = new THREE.WebGLCubeRenderTarget(256, { format: THREE.RGBFormat, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
  49951. this.lightProbeTarget = new THREE.WebGLCubeRenderTarget(16, { format: THREE.RGBFormat, generateMipmaps: false });
  49952. this.cubeCamera = new THREE.CubeCamera(0.1, 1000, this.cubeRenderTarget);
  49953. this.needsEnvironmentUpdate = true;
  49954. this.timeSinceUpdate = 0;
  49955. // Update WebXR to support light-estimation
  49956. var webxrData = this.el.getAttribute('webxr');
  49957. var optionalFeaturesArray = webxrData.optionalFeatures;
  49958. if (!optionalFeaturesArray.includes('light-estimation')) {
  49959. optionalFeaturesArray.push('light-estimation');
  49960. this.el.setAttribute('webxr', webxrData);
  49961. }
  49962. this.el.sceneEl.addEventListener('enter-vr', function () {
  49963. var renderer = self.el.renderer;
  49964. var session = renderer.xr.getSession();
  49965. if (
  49966. session.requestLightProbe && self.el.sceneEl.is('ar-mode')
  49967. ) {
  49968. self.startLightProbe();
  49969. }
  49970. });
  49971. this.el.sceneEl.addEventListener('exit-vr', function () {
  49972. self.stopLightProbe();
  49973. });
  49974. },
  49975. stopLightProbe: function () {
  49976. var data = this.data;
  49977. var scene = this.el.sceneEl.object3D;
  49978. this.xrLightProbe = null;
  49979. this.probeLight.components.light.light.intensity = 0;
  49980. if (this.ownDirectionalLight) {
  49981. this.ownDirectionalLight.components.light.light.intensity = 0;
  49982. }
  49983. if (data.generateEnvironment) {
  49984. this.needsEnvironmentUpdate = true;
  49985. } else {
  49986. scene.environment = null;
  49987. }
  49988. },
  49989. setupLightsForLightingEstimation: function () {
  49990. // Make a directionalLight if required
  49991. if (this.data.directionalLight) {
  49992. this.directionalLight = this.data.directionalLight;
  49993. } else {
  49994. var directionalLight = this.ownDirectionalLight || document.createElement('a-light');
  49995. directionalLight.setAttribute('type', 'directional');
  49996. directionalLight.setAttribute('intensity', 0);
  49997. this.el.appendChild(directionalLight);
  49998. this.directionalLight = directionalLight;
  49999. this.ownDirectionalLight = directionalLight;
  50000. }
  50001. if (!this.probeLight) {
  50002. var probeLight = document.createElement('a-light');
  50003. probeLight.setAttribute('type', 'probe');
  50004. probeLight.setAttribute('intensity', 0);
  50005. this.el.appendChild(probeLight);
  50006. this.probeLight = probeLight;
  50007. }
  50008. },
  50009. startLightProbe: function () {
  50010. var data = this.data;
  50011. var scene = this.el.sceneEl.object3D;
  50012. if (data.generateEnvironment) {
  50013. this.needsLightProbeUpdate = true;
  50014. this.needsEnvironmentUpdate = true;
  50015. } else {
  50016. scene.environment = null;
  50017. }
  50018. },
  50019. setupLightProbe: function () {
  50020. var scene = this.el.object3D;
  50021. var renderer = this.el.renderer;
  50022. var xrSession = renderer.xr.getSession();
  50023. var self = this;
  50024. var gl = renderer.getContext();
  50025. this.setupLightsForLightingEstimation();
  50026. this.glBinding = new XRWebGLBinding(xrSession, gl);
  50027. gl.getExtension('EXT_sRGB');
  50028. gl.getExtension('OES_texture_half_float');
  50029. xrSession.requestLightProbe()
  50030. .then(function (lightProbe) {
  50031. scene.environment = self.lightProbeTarget.texture;
  50032. self.xrLightProbe = lightProbe;
  50033. lightProbe.addEventListener('reflectionchange', function onReflectionChanged () {
  50034. self.needsEnvironmentUpdate = true;
  50035. });
  50036. })
  50037. .catch(function (err) {
  50038. console.warn('Lighting estimation not supported: ' + err.message);
  50039. console.warn('Are you missing: webxr="optionalFeatures: light-estimation;" from <a-scene>?');
  50040. });
  50041. },
  50042. update: function () {
  50043. var scene = this.el.sceneEl.object3D;
  50044. var data = this.data;
  50045. var object3D = this.el.object3D;
  50046. if (data.transparent) {
  50047. object3D.background = null;
  50048. } else {
  50049. object3D.background = new THREE.Color(data.color);
  50050. }
  50051. if (data.generateEnvironment) {
  50052. this.needsEnvironmentUpdate = true;
  50053. } else {
  50054. scene.environment = null;
  50055. }
  50056. },
  50057. updateXRCubeMap: function () {
  50058. // Update Cube Map, cubeMap maybe some unavailable on some hardware
  50059. var renderer = this.el.renderer;
  50060. var cubeMap = this.glBinding.getReflectionCubeMap(this.xrLightProbe);
  50061. if (cubeMap) {
  50062. var rendererProps = renderer.properties.get(this.lightProbeTarget.texture);
  50063. rendererProps.__webglTexture = cubeMap;
  50064. }
  50065. },
  50066. tick: function () {
  50067. var scene = this.el.object3D;
  50068. var renderer = this.el.renderer;
  50069. var frame = this.el.sceneEl.frame;
  50070. if (frame && this.xrLightProbe) {
  50071. // light estimate may not yet be available, it takes a few frames to start working
  50072. var estimate = frame.getLightEstimate(this.xrLightProbe);
  50073. if (estimate) {
  50074. updateLights(
  50075. estimate,
  50076. this.probeLight.components.light.light,
  50077. this.directionalLight.components.light.light,
  50078. this.directionalLight.object3D.position
  50079. );
  50080. }
  50081. }
  50082. if (!this.needsEnvironmentUpdate) {
  50083. return;
  50084. }
  50085. if (this.needsLightProbeUpdate) {
  50086. // wait until the XR Session has started before trying to make
  50087. // the light probe
  50088. if (!frame) {
  50089. return;
  50090. }
  50091. this.needsLightProbeUpdate = false;
  50092. this.setupLightProbe();
  50093. }
  50094. if (this.xrLightProbe) {
  50095. this.updateXRCubeMap();
  50096. } else {
  50097. this.cubeCamera.position.set(0, 1.6, 0);
  50098. scene.environment = null;
  50099. this.cubeCamera.update(renderer, scene);
  50100. scene.environment = this.pmremGenerator.fromCubemap(
  50101. this.cubeRenderTarget.texture
  50102. ).texture;
  50103. }
  50104. this.needsEnvironmentUpdate = false;
  50105. },
  50106. remove: function () {
  50107. var data = this.data;
  50108. var object3D = this.el.object3D;
  50109. if (data.transparent) {
  50110. object3D.background = null;
  50111. return;
  50112. }
  50113. this.pmremGenerator.dispose();
  50114. object3D.background = COMPONENTS[this.name].schema.color.default;
  50115. }
  50116. });
  50117. },{"../../core/component":135}],105:[function(require,module,exports){
  50118. var register = require('../../core/component').registerComponent;
  50119. module.exports.Component = register('debug', {
  50120. schema: {default: true}
  50121. });
  50122. },{"../../core/component":135}],106:[function(require,module,exports){
  50123. /* global DeviceOrientationEvent, location */
  50124. var registerComponent = require('../../core/component').registerComponent;
  50125. var utils = require('../../utils/');
  50126. var bind = utils.bind;
  50127. var constants = require('../../constants/');
  50128. var MODAL_CLASS = 'a-modal';
  50129. var DIALOG_CLASS = 'a-dialog';
  50130. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  50131. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  50132. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  50133. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  50134. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  50135. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  50136. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  50137. /**
  50138. * UI for enabling device motion permission
  50139. */
  50140. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  50141. schema: {
  50142. enabled: {default: true},
  50143. deviceMotionMessage: {
  50144. default: 'This immersive website requires access to your device motion sensors.'
  50145. },
  50146. httpsMessage: {
  50147. default: 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.'
  50148. },
  50149. denyButtonText: {default: 'Deny'},
  50150. allowButtonText: {default: 'Allow'},
  50151. cancelButtonText: {default: 'Cancel'}
  50152. },
  50153. init: function () {
  50154. var self = this;
  50155. if (!this.data.enabled) { return; }
  50156. if (location.hostname !== 'localhost' &&
  50157. location.hostname !== '127.0.0.1' &&
  50158. location.protocol === 'http:') {
  50159. this.showHTTPAlert();
  50160. }
  50161. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  50162. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  50163. this.permissionGranted = true;
  50164. return;
  50165. }
  50166. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  50167. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  50168. // Show dialog only if permission has not yet been granted.
  50169. DeviceOrientationEvent.requestPermission().catch(function () {
  50170. self.devicePermissionDialogEl = createPermissionDialog(
  50171. self.data.denyButtonText,
  50172. self.data.allowButtonText,
  50173. self.data.deviceMotionMessage,
  50174. self.onDeviceMotionDialogAllowClicked,
  50175. self.onDeviceMotionDialogDenyClicked);
  50176. self.el.appendChild(self.devicePermissionDialogEl);
  50177. }).then(function () {
  50178. self.el.emit('deviceorientationpermissiongranted');
  50179. self.permissionGranted = true;
  50180. });
  50181. },
  50182. remove: function () {
  50183. // This removes the modal screen
  50184. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  50185. },
  50186. onDeviceMotionDialogDenyClicked: function () {
  50187. this.remove();
  50188. },
  50189. showHTTPAlert: function () {
  50190. var self = this;
  50191. var httpAlertEl = createAlertDialog(
  50192. self.data.cancelButtonText,
  50193. self.data.httpsMessage,
  50194. function () { self.el.removeChild(httpAlertEl); });
  50195. this.el.appendChild(httpAlertEl);
  50196. },
  50197. /**
  50198. * Enable device motion permission when clicked.
  50199. */
  50200. onDeviceMotionDialogAllowClicked: function () {
  50201. var self = this;
  50202. this.el.emit('deviceorientationpermissionrequested');
  50203. DeviceOrientationEvent.requestPermission().then(function (response) {
  50204. if (response === 'granted') {
  50205. self.el.emit('deviceorientationpermissiongranted');
  50206. self.permissionGranted = true;
  50207. } else {
  50208. self.el.emit('deviceorientationpermissionrejected');
  50209. }
  50210. self.remove();
  50211. }).catch(console.error);
  50212. }
  50213. });
  50214. /**
  50215. * Create a modal dialog that request users permission to access the Device Motion API.
  50216. *
  50217. * @param {function} onAllowClicked - click event handler
  50218. * @param {function} onDenyClicked - click event handler
  50219. *
  50220. * @returns {Element} Wrapper <div>.
  50221. */
  50222. function createPermissionDialog (
  50223. denyText, allowText, dialogText, onAllowClicked, onDenyClicked) {
  50224. var buttonsContainer;
  50225. var denyButton;
  50226. var acceptButton;
  50227. buttonsContainer = document.createElement('div');
  50228. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50229. // Buttons
  50230. denyButton = document.createElement('button');
  50231. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  50232. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  50233. denyButton.innerHTML = denyText;
  50234. buttonsContainer.appendChild(denyButton);
  50235. acceptButton = document.createElement('button');
  50236. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  50237. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  50238. acceptButton.innerHTML = allowText;
  50239. buttonsContainer.appendChild(acceptButton);
  50240. // Ask for sensor events to be used
  50241. acceptButton.addEventListener('click', function (evt) {
  50242. evt.stopPropagation();
  50243. onAllowClicked();
  50244. });
  50245. denyButton.addEventListener('click', function (evt) {
  50246. evt.stopPropagation();
  50247. onDenyClicked();
  50248. });
  50249. return createDialog(dialogText, buttonsContainer);
  50250. }
  50251. function createAlertDialog (closeText, dialogText, onOkClicked) {
  50252. var buttonsContainer;
  50253. var okButton;
  50254. buttonsContainer = document.createElement('div');
  50255. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50256. // Buttons
  50257. okButton = document.createElement('button');
  50258. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  50259. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  50260. okButton.innerHTML = closeText;
  50261. buttonsContainer.appendChild(okButton);
  50262. // Ask for sensor events to be used
  50263. okButton.addEventListener('click', function (evt) {
  50264. evt.stopPropagation();
  50265. onOkClicked();
  50266. });
  50267. return createDialog(dialogText, buttonsContainer);
  50268. }
  50269. function createDialog (text, buttonsContainerEl) {
  50270. var modalContainer;
  50271. var dialog;
  50272. var dialogTextContainer;
  50273. var dialogText;
  50274. modalContainer = document.createElement('div');
  50275. modalContainer.classList.add(MODAL_CLASS);
  50276. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  50277. dialog = document.createElement('div');
  50278. dialog.className = DIALOG_CLASS;
  50279. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  50280. modalContainer.appendChild(dialog);
  50281. dialogTextContainer = document.createElement('div');
  50282. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  50283. dialog.appendChild(dialogTextContainer);
  50284. dialogText = document.createElement('div');
  50285. dialogText.classList.add(DIALOG_TEXT_CLASS);
  50286. dialogText.innerHTML = text;
  50287. dialogTextContainer.appendChild(dialogText);
  50288. dialog.appendChild(buttonsContainerEl);
  50289. return modalContainer;
  50290. }
  50291. },{"../../constants/":127,"../../core/component":135,"../../utils/":210}],107:[function(require,module,exports){
  50292. var registerComponent = require('../../core/component').registerComponent;
  50293. /**
  50294. * Component to embed an a-frame scene within the layout of a 2D page.
  50295. */
  50296. module.exports.Component = registerComponent('embedded', {
  50297. dependencies: ['vr-mode-ui'],
  50298. schema: {default: true},
  50299. update: function () {
  50300. var sceneEl = this.el;
  50301. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  50302. if (this.data === true) {
  50303. if (enterVREl) { enterVREl.classList.add('embedded'); }
  50304. sceneEl.removeFullScreenStyles();
  50305. } else {
  50306. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  50307. sceneEl.addFullScreenStyles();
  50308. }
  50309. }
  50310. });
  50311. },{"../../core/component":135}],108:[function(require,module,exports){
  50312. var register = require('../../core/component').registerComponent;
  50313. var THREE = require('../../lib/three');
  50314. var debug = require('../../utils/debug');
  50315. var warn = debug('components:fog:warn');
  50316. /**
  50317. * Fog component.
  50318. * Applies only to the scene entity.
  50319. */
  50320. module.exports.Component = register('fog', {
  50321. schema: {
  50322. color: {type: 'color', default: '#000'},
  50323. density: {default: 0.00025},
  50324. far: {default: 1000, min: 0},
  50325. near: {default: 1, min: 0},
  50326. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  50327. },
  50328. update: function () {
  50329. var data = this.data;
  50330. var el = this.el;
  50331. var fog = this.el.object3D.fog;
  50332. if (!el.isScene) {
  50333. warn('Fog component can only be applied to <a-scene>');
  50334. return;
  50335. }
  50336. // (Re)create fog if fog doesn't exist or fog type changed.
  50337. if (!fog || data.type !== fog.name) {
  50338. el.object3D.fog = getFog(data);
  50339. el.systems.material.updateMaterials();
  50340. return;
  50341. }
  50342. // Fog data changed. Update fog.
  50343. Object.keys(this.schema).forEach(function (key) {
  50344. var value = data[key];
  50345. if (key === 'color') { value = new THREE.Color(value); }
  50346. fog[key] = value;
  50347. });
  50348. },
  50349. /**
  50350. * Remove fog on remove (callback).
  50351. */
  50352. remove: function () {
  50353. var fog = this.el.object3D.fog;
  50354. if (!fog) { return; }
  50355. fog.far = 0;
  50356. fog.near = 0.1;
  50357. }
  50358. });
  50359. /**
  50360. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  50361. *
  50362. * @param {object} data - Fog data.
  50363. * @returns {object} fog
  50364. */
  50365. function getFog (data) {
  50366. var fog;
  50367. if (data.type === 'exponential') {
  50368. fog = new THREE.FogExp2(data.color, data.density);
  50369. } else {
  50370. fog = new THREE.Fog(data.color, data.near, data.far);
  50371. }
  50372. fog.name = data.type;
  50373. return fog;
  50374. }
  50375. },{"../../core/component":135,"../../lib/three":183,"../../utils/debug":206}],109:[function(require,module,exports){
  50376. (function (process){
  50377. /* global AFRAME */
  50378. var AFRAME_INJECTED = require('../../constants').AFRAME_INJECTED;
  50379. var pkg = require('../../../package');
  50380. var registerComponent = require('../../core/component').registerComponent;
  50381. var utils = require('../../utils/');
  50382. /**
  50383. * 0.4.2 to 0.4.x
  50384. * Will need to update this when A-Frame goes to 1.x.x.
  50385. */
  50386. function getFuzzyPatchVersion (version) {
  50387. var split = version.split('.');
  50388. split[2] = 'x';
  50389. return split.join('.');
  50390. }
  50391. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  50392. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  50393. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  50394. var LOADING_MESSAGE = 'Loading Inspector';
  50395. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  50396. module.exports.Component = registerComponent('inspector', {
  50397. schema: {
  50398. url: {default: INSPECTOR_URL}
  50399. },
  50400. init: function () {
  50401. this.firstPlay = true;
  50402. this.onKeydown = this.onKeydown.bind(this);
  50403. this.onMessage = this.onMessage.bind(this);
  50404. this.initOverlay();
  50405. window.addEventListener('keydown', this.onKeydown);
  50406. window.addEventListener('message', this.onMessage);
  50407. },
  50408. play: function () {
  50409. var urlParam;
  50410. if (!this.firstPlay) { return; }
  50411. urlParam = utils.getUrlParameter('inspector');
  50412. if (urlParam !== 'false' && !!urlParam) {
  50413. this.openInspector();
  50414. this.firstPlay = false;
  50415. }
  50416. },
  50417. initOverlay: function () {
  50418. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  50419. this.loadingMessageEl = document.createElement('div');
  50420. this.loadingMessageEl.classList.add('a-inspector-loader');
  50421. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  50422. },
  50423. remove: function () {
  50424. this.removeEventListeners();
  50425. },
  50426. /**
  50427. * <ctrl> + <alt> + i keyboard shortcut.
  50428. */
  50429. onKeydown: function (evt) {
  50430. var shortcutPressed = evt.keyCode === 73 && (evt.ctrlKey && evt.altKey || evt.getModifierState('AltGraph'));
  50431. if (!shortcutPressed) { return; }
  50432. this.openInspector();
  50433. },
  50434. showLoader: function () {
  50435. document.body.appendChild(this.loadingMessageEl);
  50436. },
  50437. hideLoader: function () {
  50438. document.body.removeChild(this.loadingMessageEl);
  50439. },
  50440. /**
  50441. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  50442. */
  50443. onMessage: function (evt) {
  50444. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  50445. },
  50446. openInspector: function (focusEl) {
  50447. var self = this;
  50448. var script;
  50449. // Already injected. Open.
  50450. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  50451. AFRAME.INSPECTOR.open(focusEl);
  50452. return;
  50453. }
  50454. this.showLoader();
  50455. // Inject.
  50456. script = document.createElement('script');
  50457. script.src = this.data.url;
  50458. script.setAttribute('data-name', 'aframe-inspector');
  50459. script.setAttribute(AFRAME_INJECTED, '');
  50460. script.onload = function () {
  50461. AFRAME.INSPECTOR.open(focusEl);
  50462. self.hideLoader();
  50463. self.removeEventListeners();
  50464. };
  50465. script.onerror = function () {
  50466. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  50467. };
  50468. document.head.appendChild(script);
  50469. AFRAME.inspectorInjected = true;
  50470. },
  50471. removeEventListeners: function () {
  50472. window.removeEventListener('keydown', this.onKeydown);
  50473. window.removeEventListener('message', this.onMessage);
  50474. }
  50475. });
  50476. }).call(this,require('_process'))
  50477. },{"../../../package":74,"../../constants":127,"../../core/component":135,"../../utils/":210,"_process":49}],110:[function(require,module,exports){
  50478. var registerComponent = require('../../core/component').registerComponent;
  50479. var shouldCaptureKeyEvent = require('../../utils/').shouldCaptureKeyEvent;
  50480. module.exports.Component = registerComponent('keyboard-shortcuts', {
  50481. schema: {
  50482. enterVR: {default: true},
  50483. exitVR: {default: true}
  50484. },
  50485. init: function () {
  50486. this.onKeyup = this.onKeyup.bind(this);
  50487. },
  50488. update: function (oldData) {
  50489. var data = this.data;
  50490. this.enterVREnabled = data.enterVR;
  50491. },
  50492. play: function () {
  50493. window.addEventListener('keyup', this.onKeyup, false);
  50494. },
  50495. pause: function () {
  50496. window.removeEventListener('keyup', this.onKeyup);
  50497. },
  50498. onKeyup: function (evt) {
  50499. var scene = this.el;
  50500. if (!shouldCaptureKeyEvent(evt)) { return; }
  50501. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  50502. scene.enterVR();
  50503. }
  50504. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  50505. scene.exitVR();
  50506. }
  50507. }
  50508. });
  50509. },{"../../core/component":135,"../../utils/":210}],111:[function(require,module,exports){
  50510. var debug = require('../../utils/debug');
  50511. var registerComponent = require('../../core/component').registerComponent;
  50512. var warn = debug('components:pool:warn');
  50513. /**
  50514. * Pool component to reuse entities.
  50515. * Avoids creating and destroying the same kind of entities.
  50516. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  50517. *
  50518. * @member {array} availableEls - Available entities in the pool.
  50519. * @member {array} usedEls - Entities of the pool in use.
  50520. */
  50521. module.exports.Component = registerComponent('pool', {
  50522. schema: {
  50523. container: {default: ''},
  50524. mixin: {default: ''},
  50525. size: {default: 0},
  50526. dynamic: {default: false}
  50527. },
  50528. multiple: true,
  50529. initPool: function () {
  50530. var i;
  50531. this.availableEls = [];
  50532. this.usedEls = [];
  50533. if (!this.data.mixin) {
  50534. warn('No mixin provided for pool component.');
  50535. }
  50536. if (this.data.container) {
  50537. this.container = document.querySelector(this.data.container);
  50538. if (!this.container) {
  50539. warn('Container ' + this.data.container + ' not found.');
  50540. }
  50541. }
  50542. this.container = this.container || this.el;
  50543. for (i = 0; i < this.data.size; ++i) {
  50544. this.createEntity();
  50545. }
  50546. },
  50547. update: function (oldData) {
  50548. var data = this.data;
  50549. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  50550. this.initPool();
  50551. }
  50552. },
  50553. /**
  50554. * Add a new entity to the list of available entities.
  50555. */
  50556. createEntity: function () {
  50557. var el;
  50558. el = document.createElement('a-entity');
  50559. el.play = this.wrapPlay(el.play);
  50560. el.setAttribute('mixin', this.data.mixin);
  50561. el.object3D.visible = false;
  50562. el.pause();
  50563. this.container.appendChild(el);
  50564. this.availableEls.push(el);
  50565. },
  50566. /**
  50567. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  50568. * entities that are not in use.
  50569. */
  50570. wrapPlay: function (playMethod) {
  50571. var usedEls = this.usedEls;
  50572. return function () {
  50573. if (usedEls.indexOf(this) === -1) { return; }
  50574. playMethod.call(this);
  50575. };
  50576. },
  50577. /**
  50578. * Used to request one of the available entities of the pool.
  50579. */
  50580. requestEntity: function () {
  50581. var el;
  50582. if (this.availableEls.length === 0) {
  50583. if (this.data.dynamic === false) {
  50584. warn('Requested entity from empty pool: ' + this.attrName);
  50585. return;
  50586. } else {
  50587. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  50588. 'automatically. You might want to increase its initial size: ' + this.attrName);
  50589. }
  50590. this.createEntity();
  50591. }
  50592. el = this.availableEls.shift();
  50593. this.usedEls.push(el);
  50594. el.object3D.visible = true;
  50595. return el;
  50596. },
  50597. /**
  50598. * Used to return a used entity to the pool.
  50599. */
  50600. returnEntity: function (el) {
  50601. var index = this.usedEls.indexOf(el);
  50602. if (index === -1) {
  50603. warn('The returned entity was not previously pooled from ' + this.attrName);
  50604. return;
  50605. }
  50606. this.usedEls.splice(index, 1);
  50607. this.availableEls.push(el);
  50608. el.object3D.visible = false;
  50609. el.pause();
  50610. return el;
  50611. }
  50612. });
  50613. },{"../../core/component":135,"../../utils/debug":206}],112:[function(require,module,exports){
  50614. /* global ImageData, URL */
  50615. var registerComponent = require('../../core/component').registerComponent;
  50616. var THREE = require('../../lib/three');
  50617. var VERTEX_SHADER = [
  50618. 'attribute vec3 position;',
  50619. 'attribute vec2 uv;',
  50620. 'uniform mat4 projectionMatrix;',
  50621. 'uniform mat4 modelViewMatrix;',
  50622. 'varying vec2 vUv;',
  50623. 'void main() {',
  50624. ' vUv = vec2( 1.- uv.x, uv.y );',
  50625. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  50626. '}'
  50627. ].join('\n');
  50628. var FRAGMENT_SHADER = [
  50629. 'precision mediump float;',
  50630. 'uniform samplerCube map;',
  50631. 'varying vec2 vUv;',
  50632. '#define M_PI 3.141592653589793238462643383279',
  50633. 'void main() {',
  50634. ' vec2 uv = vUv;',
  50635. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  50636. ' float latitude = uv.y * M_PI;',
  50637. ' vec3 dir = vec3(',
  50638. ' - sin( longitude ) * sin( latitude ),',
  50639. ' cos( latitude ),',
  50640. ' - cos( longitude ) * sin( latitude )',
  50641. ' );',
  50642. ' normalize( dir );',
  50643. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  50644. '}'
  50645. ].join('\n');
  50646. /**
  50647. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  50648. * It can be configured to either take 360&deg; captures (`equirectangular`)
  50649. * or regular screenshots (`projection`)
  50650. *
  50651. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  50652. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  50653. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  50654. * WebGLRenderTarget with an ortographic camera.
  50655. */
  50656. module.exports.Component = registerComponent('screenshot', {
  50657. schema: {
  50658. width: {default: 4096},
  50659. height: {default: 2048},
  50660. camera: {type: 'selector'}
  50661. },
  50662. init: function () {
  50663. var el = this.el;
  50664. var self = this;
  50665. if (el.renderer) {
  50666. setup();
  50667. } else {
  50668. el.addEventListener('render-target-loaded', setup);
  50669. }
  50670. function setup () {
  50671. var gl = el.renderer.getContext();
  50672. if (!gl) { return; }
  50673. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  50674. self.material = new THREE.RawShaderMaterial({
  50675. uniforms: {map: {type: 't', value: null}},
  50676. vertexShader: VERTEX_SHADER,
  50677. fragmentShader: FRAGMENT_SHADER,
  50678. side: THREE.DoubleSide
  50679. });
  50680. self.quad = new THREE.Mesh(
  50681. new THREE.PlaneBufferGeometry(1, 1),
  50682. self.material
  50683. );
  50684. self.quad.visible = false;
  50685. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  50686. self.canvas = document.createElement('canvas');
  50687. self.ctx = self.canvas.getContext('2d');
  50688. el.object3D.add(self.quad);
  50689. self.onKeyDown = self.onKeyDown.bind(self);
  50690. }
  50691. },
  50692. getRenderTarget: function (width, height) {
  50693. return new THREE.WebGLRenderTarget(width, height, {
  50694. encoding: THREE.sRGBEncoding,
  50695. minFilter: THREE.LinearFilter,
  50696. magFilter: THREE.LinearFilter,
  50697. wrapS: THREE.ClampToEdgeWrapping,
  50698. wrapT: THREE.ClampToEdgeWrapping,
  50699. format: THREE.RGBAFormat,
  50700. type: THREE.UnsignedByteType
  50701. });
  50702. },
  50703. resize: function (width, height) {
  50704. // Resize quad.
  50705. this.quad.scale.set(width, height, 1);
  50706. // Resize camera.
  50707. this.camera.left = -1 * width / 2;
  50708. this.camera.right = width / 2;
  50709. this.camera.top = height / 2;
  50710. this.camera.bottom = -1 * height / 2;
  50711. this.camera.updateProjectionMatrix();
  50712. // Resize canvas.
  50713. this.canvas.width = width;
  50714. this.canvas.height = height;
  50715. },
  50716. play: function () {
  50717. window.addEventListener('keydown', this.onKeyDown);
  50718. },
  50719. /**
  50720. * <ctrl> + <alt> + s = Regular screenshot.
  50721. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  50722. */
  50723. onKeyDown: function (evt) {
  50724. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  50725. if (!this.data || !shortcutPressed) { return; }
  50726. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  50727. this.capture(projection);
  50728. },
  50729. /**
  50730. * Capture a screenshot of the scene.
  50731. *
  50732. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  50733. */
  50734. setCapture: function (projection) {
  50735. var el = this.el;
  50736. var size;
  50737. var camera;
  50738. var cubeCamera;
  50739. var cubeRenderTarget;
  50740. // Configure camera.
  50741. if (projection === 'perspective') {
  50742. // Quad is only used in equirectangular mode. Hide it in this case.
  50743. this.quad.visible = false;
  50744. // Use scene camera.
  50745. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  50746. size = {width: this.data.width, height: this.data.height};
  50747. } else {
  50748. // Use ortho camera.
  50749. camera = this.camera;
  50750. cubeRenderTarget = new THREE.WebGLCubeRenderTarget(
  50751. Math.min(this.cubeMapSize, 2048),
  50752. {
  50753. format: THREE.RGBFormat,
  50754. generateMipmaps: true,
  50755. minFilter: THREE.LinearMipmapLinearFilter,
  50756. encoding: THREE.sRGBEncoding
  50757. });
  50758. // Create cube camera and copy position from scene camera.
  50759. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, cubeRenderTarget);
  50760. // Copy camera position into cube camera;
  50761. el.camera.getWorldPosition(cubeCamera.position);
  50762. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  50763. // Render scene with cube camera.
  50764. cubeCamera.update(el.renderer, el.object3D);
  50765. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  50766. size = {width: this.data.width, height: this.data.height};
  50767. // Use quad to project image taken by the cube camera.
  50768. this.quad.visible = true;
  50769. }
  50770. return {
  50771. camera: camera,
  50772. size: size,
  50773. projection: projection
  50774. };
  50775. },
  50776. /**
  50777. * Maintained for backwards compatibility.
  50778. */
  50779. capture: function (projection) {
  50780. var isVREnabled = this.el.renderer.xr.enabled;
  50781. var renderer = this.el.renderer;
  50782. var params;
  50783. // Disable VR.
  50784. renderer.xr.enabled = false;
  50785. params = this.setCapture(projection);
  50786. this.renderCapture(params.camera, params.size, params.projection);
  50787. // Trigger file download.
  50788. this.saveCapture();
  50789. // Restore VR.
  50790. renderer.xr.enabled = isVREnabled;
  50791. },
  50792. /**
  50793. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  50794. */
  50795. getCanvas: function (projection) {
  50796. var isVREnabled = this.el.renderer.xr.enabled;
  50797. var renderer = this.el.renderer;
  50798. // Disable VR.
  50799. var params = this.setCapture(projection);
  50800. renderer.xr.enabled = false;
  50801. this.renderCapture(params.camera, params.size, params.projection);
  50802. // Restore VR.
  50803. renderer.xr.enabled = isVREnabled;
  50804. return this.canvas;
  50805. },
  50806. renderCapture: function (camera, size, projection) {
  50807. var autoClear = this.el.renderer.autoClear;
  50808. var el = this.el;
  50809. var imageData;
  50810. var output;
  50811. var pixels;
  50812. var renderer = el.renderer;
  50813. // Create rendering target and buffer to store the read pixels.
  50814. output = this.getRenderTarget(size.width, size.height);
  50815. pixels = new Uint8Array(4 * size.width * size.height);
  50816. // Resize quad, camera, and canvas.
  50817. this.resize(size.width, size.height);
  50818. // Render scene to render target.
  50819. renderer.autoClear = true;
  50820. renderer.clear();
  50821. renderer.setRenderTarget(output);
  50822. renderer.render(el.object3D, camera);
  50823. renderer.autoClear = autoClear;
  50824. // Read image pizels back.
  50825. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  50826. renderer.setRenderTarget(null);
  50827. if (projection === 'perspective') {
  50828. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  50829. }
  50830. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  50831. // Hide quad after projecting the image.
  50832. this.quad.visible = false;
  50833. // Copy pixels into canvas.
  50834. this.ctx.putImageData(imageData, 0, 0);
  50835. },
  50836. flipPixelsVertically: function (pixels, width, height) {
  50837. var flippedPixels = pixels.slice(0);
  50838. for (var x = 0; x < width; ++x) {
  50839. for (var y = 0; y < height; ++y) {
  50840. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  50841. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  50842. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  50843. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  50844. }
  50845. }
  50846. return flippedPixels;
  50847. },
  50848. /**
  50849. * Download capture to file.
  50850. */
  50851. saveCapture: function () {
  50852. this.canvas.toBlob(function (blob) {
  50853. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  50854. var linkEl = document.createElement('a');
  50855. var url = URL.createObjectURL(blob);
  50856. linkEl.href = url;
  50857. linkEl.setAttribute('download', fileName);
  50858. linkEl.innerHTML = 'downloading...';
  50859. linkEl.style.display = 'none';
  50860. document.body.appendChild(linkEl);
  50861. setTimeout(function () {
  50862. linkEl.click();
  50863. document.body.removeChild(linkEl);
  50864. }, 1);
  50865. }, 'image/png');
  50866. }
  50867. });
  50868. },{"../../core/component":135,"../../lib/three":183}],113:[function(require,module,exports){
  50869. var registerComponent = require('../../core/component').registerComponent;
  50870. var RStats = require('../../../vendor/rStats');
  50871. var utils = require('../../utils');
  50872. require('../../../vendor/rStats.extras');
  50873. require('../../lib/rStatsAframe');
  50874. var AFrameStats = window.aframeStats;
  50875. var bind = utils.bind;
  50876. var HIDDEN_CLASS = 'a-hidden';
  50877. var ThreeStats = window.threeStats;
  50878. /**
  50879. * Stats appended to document.body by RStats.
  50880. */
  50881. module.exports.Component = registerComponent('stats', {
  50882. schema: {default: true},
  50883. init: function () {
  50884. var scene = this.el;
  50885. if (utils.getUrlParameter('stats') === 'false') { return; }
  50886. this.stats = createStats(scene);
  50887. this.statsEl = document.querySelector('.rs-base');
  50888. this.hideBound = bind(this.hide, this);
  50889. this.showBound = bind(this.show, this);
  50890. scene.addEventListener('enter-vr', this.hideBound);
  50891. scene.addEventListener('exit-vr', this.showBound);
  50892. },
  50893. update: function () {
  50894. if (!this.stats) { return; }
  50895. return (!this.data) ? this.hide() : this.show();
  50896. },
  50897. remove: function () {
  50898. this.el.removeEventListener('enter-vr', this.hideBound);
  50899. this.el.removeEventListener('exit-vr', this.showBound);
  50900. if (!this.statsEl) { return; } // Scene detached.
  50901. this.statsEl.parentNode.removeChild(this.statsEl);
  50902. },
  50903. tick: function () {
  50904. var stats = this.stats;
  50905. if (!stats) { return; }
  50906. stats('rAF').tick();
  50907. stats('FPS').frame();
  50908. stats().update();
  50909. },
  50910. hide: function () {
  50911. this.statsEl.classList.add(HIDDEN_CLASS);
  50912. },
  50913. show: function () {
  50914. this.statsEl.classList.remove(HIDDEN_CLASS);
  50915. }
  50916. });
  50917. function createStats (scene) {
  50918. var threeStats = new ThreeStats(scene.renderer);
  50919. var aframeStats = new AFrameStats(scene);
  50920. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  50921. return new RStats({
  50922. css: [], // Our stylesheet is injected from `src/index.js`.
  50923. values: {
  50924. fps: {caption: 'fps', below: 30}
  50925. },
  50926. groups: [
  50927. {caption: 'Framerate', values: ['fps', 'raf']}
  50928. ],
  50929. plugins: plugins
  50930. });
  50931. }
  50932. },{"../../../vendor/rStats":222,"../../../vendor/rStats.extras":221,"../../core/component":135,"../../lib/rStatsAframe":182,"../../utils":210}],114:[function(require,module,exports){
  50933. var registerComponent = require('../../core/component').registerComponent;
  50934. var constants = require('../../constants/');
  50935. var utils = require('../../utils/');
  50936. var bind = utils.bind;
  50937. var ENTER_VR_CLASS = 'a-enter-vr';
  50938. var ENTER_AR_CLASS = 'a-enter-ar';
  50939. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  50940. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  50941. var HIDDEN_CLASS = 'a-hidden';
  50942. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  50943. /**
  50944. * UI for entering VR mode.
  50945. */
  50946. module.exports.Component = registerComponent('vr-mode-ui', {
  50947. dependencies: ['canvas'],
  50948. schema: {
  50949. enabled: {default: true},
  50950. enterVRButton: {default: ''},
  50951. enterARButton: {default: ''}
  50952. },
  50953. init: function () {
  50954. var self = this;
  50955. var sceneEl = this.el;
  50956. if (utils.getUrlParameter('ui') === 'false') { return; }
  50957. this.insideLoader = false;
  50958. this.enterVREl = null;
  50959. this.enterAREl = null;
  50960. this.orientationModalEl = null;
  50961. this.bindMethods();
  50962. // Hide/show VR UI when entering/exiting VR mode.
  50963. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  50964. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  50965. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  50966. window.addEventListener('message', function (event) {
  50967. if (event.data.type === 'loaderReady') {
  50968. self.insideLoader = true;
  50969. self.remove();
  50970. }
  50971. });
  50972. // Modal that tells the user to change orientation if in portrait.
  50973. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  50974. },
  50975. bindMethods: function () {
  50976. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  50977. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  50978. this.onModalClick = bind(this.onModalClick, this);
  50979. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  50980. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  50981. },
  50982. /**
  50983. * Exit VR when modal clicked.
  50984. */
  50985. onModalClick: function () {
  50986. this.el.exitVR();
  50987. },
  50988. /**
  50989. * Enter VR when clicked.
  50990. */
  50991. onEnterVRButtonClick: function () {
  50992. this.el.enterVR();
  50993. },
  50994. /**
  50995. * Enter AR when clicked.
  50996. */
  50997. onEnterARButtonClick: function () {
  50998. this.el.enterAR();
  50999. },
  51000. update: function () {
  51001. var data = this.data;
  51002. var sceneEl = this.el;
  51003. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  51004. return this.remove();
  51005. }
  51006. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  51007. // Add UI if enabled and not already present.
  51008. if (data.enterVRButton) {
  51009. // Custom button.
  51010. this.enterVREl = document.querySelector(data.enterVRButton);
  51011. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  51012. } else {
  51013. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  51014. sceneEl.appendChild(this.enterVREl);
  51015. }
  51016. if (data.enterARButton) {
  51017. // Custom button.
  51018. this.enterAREl = document.querySelector(data.enterARButton);
  51019. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  51020. } else {
  51021. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  51022. sceneEl.appendChild(this.enterAREl);
  51023. }
  51024. this.orientationModalEl = createOrientationModal(this.onModalClick);
  51025. sceneEl.appendChild(this.orientationModalEl);
  51026. this.updateEnterInterfaces();
  51027. },
  51028. remove: function () {
  51029. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  51030. if (uiElement && uiElement.parentNode) {
  51031. uiElement.parentNode.removeChild(uiElement);
  51032. }
  51033. });
  51034. this.enterVREl = undefined;
  51035. this.enterAREl = undefined;
  51036. this.orientationModalEl = undefined;
  51037. },
  51038. updateEnterInterfaces: function () {
  51039. this.toggleEnterVRButtonIfNeeded();
  51040. this.toggleEnterARButtonIfNeeded();
  51041. this.toggleOrientationModalIfNeeded();
  51042. },
  51043. toggleEnterVRButtonIfNeeded: function () {
  51044. var sceneEl = this.el;
  51045. if (!this.enterVREl) { return; }
  51046. if (sceneEl.is('vr-mode')) {
  51047. this.enterVREl.classList.add(HIDDEN_CLASS);
  51048. } else {
  51049. this.enterVREl.classList.remove(HIDDEN_CLASS);
  51050. }
  51051. },
  51052. toggleEnterARButtonIfNeeded: function () {
  51053. var sceneEl = this.el;
  51054. if (!this.enterAREl) { return; }
  51055. // Hide the button while in a session, or if AR is not supported.
  51056. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  51057. this.enterAREl.classList.add(HIDDEN_CLASS);
  51058. } else {
  51059. this.enterAREl.classList.remove(HIDDEN_CLASS);
  51060. }
  51061. },
  51062. toggleOrientationModalIfNeeded: function () {
  51063. var sceneEl = this.el;
  51064. var orientationModalEl = this.orientationModalEl;
  51065. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  51066. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  51067. // Show if in VR mode on portrait.
  51068. orientationModalEl.classList.remove(HIDDEN_CLASS);
  51069. } else {
  51070. orientationModalEl.classList.add(HIDDEN_CLASS);
  51071. }
  51072. }
  51073. });
  51074. /**
  51075. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  51076. *
  51077. * Structure: <div><button></div>
  51078. *
  51079. * @param {function} onClick - click event handler
  51080. * @returns {Element} Wrapper <div>.
  51081. */
  51082. function createEnterVRButton (onClick) {
  51083. var vrButton;
  51084. var wrapper;
  51085. // Create elements.
  51086. wrapper = document.createElement('div');
  51087. wrapper.classList.add(ENTER_VR_CLASS);
  51088. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51089. vrButton = document.createElement('button');
  51090. vrButton.className = ENTER_VR_BTN_CLASS;
  51091. vrButton.setAttribute('title',
  51092. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  51093. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51094. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  51095. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  51096. // Insert elements.
  51097. wrapper.appendChild(vrButton);
  51098. vrButton.addEventListener('click', function (evt) {
  51099. onClick();
  51100. evt.stopPropagation();
  51101. });
  51102. return wrapper;
  51103. }
  51104. /**
  51105. * Create a button that when clicked will enter into AR mode
  51106. *
  51107. * Structure: <div><button></div>
  51108. *
  51109. * @param {function} onClick - click event handler
  51110. * @returns {Element} Wrapper <div>.
  51111. */
  51112. function createEnterARButton (onClick) {
  51113. var arButton;
  51114. var wrapper;
  51115. // Create elements.
  51116. wrapper = document.createElement('div');
  51117. wrapper.classList.add(ENTER_AR_CLASS);
  51118. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51119. arButton = document.createElement('button');
  51120. arButton.className = ENTER_AR_BTN_CLASS;
  51121. arButton.setAttribute('title',
  51122. 'Enter AR mode with a headset or handheld device. ' +
  51123. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51124. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  51125. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  51126. // Insert elements.
  51127. wrapper.appendChild(arButton);
  51128. arButton.addEventListener('click', function (evt) {
  51129. onClick();
  51130. evt.stopPropagation();
  51131. });
  51132. return wrapper;
  51133. }
  51134. /**
  51135. * Creates a modal dialog to request the user to switch to landscape orientation.
  51136. *
  51137. * @param {function} onClick - click event handler
  51138. * @returns {Element} Wrapper <div>.
  51139. */
  51140. function createOrientationModal (onClick) {
  51141. var modal = document.createElement('div');
  51142. modal.className = ORIENTATION_MODAL_CLASS;
  51143. modal.classList.add(HIDDEN_CLASS);
  51144. modal.setAttribute(constants.AFRAME_INJECTED, '');
  51145. var exit = document.createElement('button');
  51146. exit.setAttribute(constants.AFRAME_INJECTED, '');
  51147. exit.innerHTML = 'Exit VR';
  51148. // Exit VR on close.
  51149. exit.addEventListener('click', onClick);
  51150. modal.appendChild(exit);
  51151. return modal;
  51152. }
  51153. /**
  51154. * CSS hover state is sticky in iOS (as in 12/18/2019)
  51155. * They are not removed on mouseleave and this function applies a class
  51156. * to resets the style.
  51157. *
  51158. * @param {function} buttonEl - Button element
  51159. */
  51160. function applyStickyHoverFix (buttonEl) {
  51161. buttonEl.addEventListener('touchstart', function () {
  51162. buttonEl.classList.remove('resethover');
  51163. });
  51164. buttonEl.addEventListener('touchend', function () {
  51165. buttonEl.classList.add('resethover');
  51166. });
  51167. }
  51168. },{"../../constants/":127,"../../core/component":135,"../../utils/":210}],115:[function(require,module,exports){
  51169. var component = require('../core/component');
  51170. var THREE = require('../lib/three');
  51171. var bind = require('../utils/bind');
  51172. var registerComponent = component.registerComponent;
  51173. /**
  51174. * Shadow component.
  51175. *
  51176. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  51177. * shadows as specified by the `cast` and `receive` properties.
  51178. */
  51179. module.exports.Component = registerComponent('shadow', {
  51180. schema: {
  51181. cast: {default: true},
  51182. receive: {default: true}
  51183. },
  51184. init: function () {
  51185. this.onMeshChanged = bind(this.update, this);
  51186. this.el.addEventListener('object3dset', this.onMeshChanged);
  51187. this.system.setShadowMapEnabled(true);
  51188. },
  51189. update: function () {
  51190. var data = this.data;
  51191. this.updateDescendants(data.cast, data.receive);
  51192. },
  51193. remove: function () {
  51194. var el = this.el;
  51195. el.removeEventListener('object3dset', this.onMeshChanged);
  51196. this.updateDescendants(false, false);
  51197. },
  51198. updateDescendants: function (cast, receive) {
  51199. var sceneEl = this.el.sceneEl;
  51200. this.el.object3D.traverse(function (node) {
  51201. if (!(node instanceof THREE.Mesh)) { return; }
  51202. node.castShadow = cast;
  51203. node.receiveShadow = receive;
  51204. // If scene has already rendered, materials must be updated.
  51205. if (sceneEl.hasLoaded && node.material) {
  51206. var materials = Array.isArray(node.material) ? node.material : [node.material];
  51207. for (var i = 0; i < materials.length; i++) {
  51208. materials[i].needsUpdate = true;
  51209. }
  51210. }
  51211. });
  51212. }
  51213. });
  51214. },{"../core/component":135,"../lib/three":183,"../utils/bind":204}],116:[function(require,module,exports){
  51215. var registerComponent = require('../core/component').registerComponent;
  51216. var debug = require('../utils/debug');
  51217. var THREE = require('../lib/three');
  51218. var warn = debug('components:sound:warn');
  51219. /**
  51220. * Sound component.
  51221. */
  51222. module.exports.Component = registerComponent('sound', {
  51223. schema: {
  51224. autoplay: {default: false},
  51225. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  51226. loop: {default: false},
  51227. maxDistance: {default: 10000},
  51228. on: {default: ''},
  51229. poolSize: {default: 1},
  51230. positional: {default: true},
  51231. refDistance: {default: 1},
  51232. rolloffFactor: {default: 1},
  51233. src: {type: 'audio'},
  51234. volume: {default: 1}
  51235. },
  51236. multiple: true,
  51237. init: function () {
  51238. var self = this;
  51239. this.listener = null;
  51240. this.audioLoader = new THREE.AudioLoader();
  51241. this.pool = new THREE.Group();
  51242. this.loaded = false;
  51243. this.mustPlay = false;
  51244. // Don't pass evt because playSound takes a function as parameter.
  51245. this.playSoundBound = function () { self.playSound(); };
  51246. },
  51247. update: function (oldData) {
  51248. var data = this.data;
  51249. var i;
  51250. var sound;
  51251. var srcChanged = data.src !== oldData.src;
  51252. // Create new sound if not yet created or changing `src`.
  51253. if (srcChanged) {
  51254. if (!data.src) { return; }
  51255. this.setupSound();
  51256. }
  51257. for (i = 0; i < this.pool.children.length; i++) {
  51258. sound = this.pool.children[i];
  51259. if (data.positional) {
  51260. sound.setDistanceModel(data.distanceModel);
  51261. sound.setMaxDistance(data.maxDistance);
  51262. sound.setRefDistance(data.refDistance);
  51263. sound.setRolloffFactor(data.rolloffFactor);
  51264. }
  51265. sound.setLoop(data.loop);
  51266. sound.setVolume(data.volume);
  51267. sound.isPaused = false;
  51268. }
  51269. if (data.on !== oldData.on) {
  51270. this.updateEventListener(oldData.on);
  51271. }
  51272. // All sound values set. Load in `src`.
  51273. if (srcChanged) {
  51274. var self = this;
  51275. this.loaded = false;
  51276. this.audioLoader.load(data.src, function (buffer) {
  51277. for (i = 0; i < self.pool.children.length; i++) {
  51278. sound = self.pool.children[i];
  51279. sound.setBuffer(buffer);
  51280. }
  51281. self.loaded = true;
  51282. // Remove this key from cache, otherwise we can't play it again
  51283. THREE.Cache.remove(data.src);
  51284. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  51285. self.el.emit('sound-loaded', self.evtDetail, false);
  51286. });
  51287. }
  51288. },
  51289. pause: function () {
  51290. this.stopSound();
  51291. this.removeEventListener();
  51292. },
  51293. play: function () {
  51294. if (this.data.autoplay) { this.playSound(); }
  51295. this.updateEventListener();
  51296. },
  51297. remove: function () {
  51298. var i;
  51299. var sound;
  51300. this.removeEventListener();
  51301. if (this.el.getObject3D(this.attrName)) {
  51302. this.el.removeObject3D(this.attrName);
  51303. }
  51304. try {
  51305. for (i = 0; i < this.pool.children.length; i++) {
  51306. sound = this.pool.children[i];
  51307. sound.disconnect();
  51308. }
  51309. } catch (e) {
  51310. // disconnect() will throw if it was never connected initially.
  51311. warn('Audio source not properly disconnected');
  51312. }
  51313. },
  51314. /**
  51315. * Update listener attached to the user defined on event.
  51316. */
  51317. updateEventListener: function (oldEvt) {
  51318. var el = this.el;
  51319. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  51320. el.addEventListener(this.data.on, this.playSoundBound);
  51321. },
  51322. removeEventListener: function () {
  51323. this.el.removeEventListener(this.data.on, this.playSoundBound);
  51324. },
  51325. /**
  51326. * Removes current sound object, creates new sound object, adds to entity.
  51327. *
  51328. * @returns {object} sound
  51329. */
  51330. setupSound: function () {
  51331. var el = this.el;
  51332. var i;
  51333. var sceneEl = el.sceneEl;
  51334. var self = this;
  51335. var sound;
  51336. if (this.pool.children.length > 0) {
  51337. this.stopSound();
  51338. el.removeObject3D('sound');
  51339. }
  51340. // Only want one AudioListener. Cache it on the scene.
  51341. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  51342. sceneEl.audioListener = listener;
  51343. if (sceneEl.camera) {
  51344. sceneEl.camera.add(listener);
  51345. }
  51346. // Wait for camera if necessary.
  51347. sceneEl.addEventListener('camera-set-active', function (evt) {
  51348. evt.detail.cameraEl.getObject3D('camera').add(listener);
  51349. });
  51350. // Create [poolSize] audio instances and attach them to pool
  51351. this.pool = new THREE.Group();
  51352. for (i = 0; i < this.data.poolSize; i++) {
  51353. sound = this.data.positional
  51354. ? new THREE.PositionalAudio(listener)
  51355. : new THREE.Audio(listener);
  51356. this.pool.add(sound);
  51357. }
  51358. el.setObject3D(this.attrName, this.pool);
  51359. for (i = 0; i < this.pool.children.length; i++) {
  51360. sound = this.pool.children[i];
  51361. sound.onEnded = function () {
  51362. this.isPlaying = false;
  51363. self.el.emit('sound-ended', self.evtDetail, false);
  51364. };
  51365. }
  51366. },
  51367. /**
  51368. * Pause all the sounds in the pool.
  51369. */
  51370. pauseSound: function () {
  51371. var i;
  51372. var sound;
  51373. this.isPlaying = false;
  51374. for (i = 0; i < this.pool.children.length; i++) {
  51375. sound = this.pool.children[i];
  51376. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  51377. continue;
  51378. }
  51379. sound.isPaused = true;
  51380. sound.pause();
  51381. }
  51382. },
  51383. /**
  51384. * Look for an unused sound in the pool and play it if found.
  51385. */
  51386. playSound: function (processSound) {
  51387. var found;
  51388. var i;
  51389. var sound;
  51390. if (!this.loaded) {
  51391. warn('Sound not loaded yet. It will be played once it finished loading');
  51392. this.mustPlay = true;
  51393. return;
  51394. }
  51395. found = false;
  51396. this.isPlaying = true;
  51397. for (i = 0; i < this.pool.children.length; i++) {
  51398. sound = this.pool.children[i];
  51399. if (!sound.isPlaying && sound.buffer && !found) {
  51400. if (processSound) { processSound(sound); }
  51401. sound.play();
  51402. sound.isPaused = false;
  51403. found = true;
  51404. continue;
  51405. }
  51406. }
  51407. if (!found) {
  51408. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  51409. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  51410. return;
  51411. }
  51412. this.mustPlay = false;
  51413. },
  51414. /**
  51415. * Stop all the sounds in the pool.
  51416. */
  51417. stopSound: function () {
  51418. var i;
  51419. var sound;
  51420. this.isPlaying = false;
  51421. for (i = 0; i < this.pool.children.length; i++) {
  51422. sound = this.pool.children[i];
  51423. if (!sound.source || !sound.source.buffer) { return; }
  51424. sound.stop();
  51425. }
  51426. }
  51427. });
  51428. },{"../core/component":135,"../lib/three":183,"../utils/debug":206}],117:[function(require,module,exports){
  51429. var createTextGeometry = require('three-bmfont-text');
  51430. var loadBMFont = require('load-bmfont');
  51431. var registerComponent = require('../core/component').registerComponent;
  51432. var coreShader = require('../core/shader');
  51433. var THREE = require('../lib/three');
  51434. var utils = require('../utils/');
  51435. var error = utils.debug('components:text:error');
  51436. var shaders = coreShader.shaders;
  51437. var warn = utils.debug('components:text:warn');
  51438. // 1 to match other A-Frame default widths.
  51439. var DEFAULT_WIDTH = 1;
  51440. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  51441. var MAX_ANISOTROPY = 16;
  51442. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  51443. var FONTS = {
  51444. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  51445. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  51446. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  51447. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  51448. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  51449. monoid: FONT_BASE_URL + 'Monoid.fnt',
  51450. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  51451. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  51452. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  51453. };
  51454. var MSDF_FONTS = ['roboto'];
  51455. var DEFAULT_FONT = 'roboto';
  51456. module.exports.FONTS = FONTS;
  51457. var cache = new PromiseCache();
  51458. var fontWidthFactors = {};
  51459. var textures = {};
  51460. // Regular expression for detecting a URLs with a protocol prefix.
  51461. var protocolRe = /^\w+:/;
  51462. /**
  51463. * SDF-based text component.
  51464. * Based on https://github.com/Jam3/three-bmfont-text.
  51465. *
  51466. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  51467. * original `sdf` shader.
  51468. */
  51469. module.exports.Component = registerComponent('text', {
  51470. multiple: true,
  51471. schema: {
  51472. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  51473. alphaTest: {default: 0.5},
  51474. // `anchor` defaults to center to match geometries.
  51475. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  51476. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  51477. color: {type: 'color', default: '#FFF'},
  51478. font: {type: 'string', default: DEFAULT_FONT},
  51479. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  51480. fontImage: {type: 'string'},
  51481. // `height` has no default, will be populated at layout.
  51482. height: {type: 'number'},
  51483. letterSpacing: {type: 'number', default: 0},
  51484. // `lineHeight` defaults to font's `lineHeight` value.
  51485. lineHeight: {type: 'number'},
  51486. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  51487. negate: {type: 'boolean', default: true},
  51488. opacity: {type: 'number', default: 1.0},
  51489. shader: {default: 'sdf', oneOf: shaders},
  51490. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  51491. tabSize: {default: 4},
  51492. transparent: {default: true},
  51493. value: {type: 'string'},
  51494. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  51495. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  51496. width: {type: 'number'},
  51497. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  51498. wrapCount: {type: 'number', default: 40},
  51499. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  51500. wrapPixels: {type: 'number'},
  51501. // `xOffset` to add padding.
  51502. xOffset: {type: 'number', default: 0},
  51503. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  51504. yOffset: {type: 'number', default: 0},
  51505. // `zOffset` will provide a small z offset to avoid z-fighting.
  51506. zOffset: {type: 'number', default: 0.001}
  51507. },
  51508. init: function () {
  51509. this.shaderData = {};
  51510. this.geometry = createTextGeometry();
  51511. this.createOrUpdateMaterial();
  51512. },
  51513. update: function (oldData) {
  51514. var data = this.data;
  51515. var font = this.currentFont;
  51516. if (textures[data.font]) {
  51517. this.texture = textures[data.font];
  51518. } else {
  51519. // Create texture per font.
  51520. this.texture = textures[data.font] = new THREE.Texture();
  51521. this.texture.anisotropy = MAX_ANISOTROPY;
  51522. }
  51523. // Update material.
  51524. this.createOrUpdateMaterial();
  51525. // New font. `updateFont` will later change data and layout.
  51526. if (oldData.font !== data.font) {
  51527. this.updateFont();
  51528. return;
  51529. }
  51530. // Update geometry and layout.
  51531. if (font) {
  51532. this.updateGeometry(this.geometry, font);
  51533. this.updateLayout();
  51534. }
  51535. },
  51536. /**
  51537. * Clean up geometry, material, texture, mesh, objects.
  51538. */
  51539. remove: function () {
  51540. this.geometry.dispose();
  51541. this.geometry = null;
  51542. this.el.removeObject3D(this.attrName);
  51543. this.material.dispose();
  51544. this.material = null;
  51545. this.texture.dispose();
  51546. this.texture = null;
  51547. if (this.shaderObject) { delete this.shaderObject; }
  51548. },
  51549. /**
  51550. * Update the shader of the material.
  51551. */
  51552. createOrUpdateMaterial: function () {
  51553. var data = this.data;
  51554. var hasChangedShader;
  51555. var material = this.material;
  51556. var NewShader;
  51557. var shaderData = this.shaderData;
  51558. var shaderName;
  51559. // Infer shader if using a stock font (or from `-msdf` filename convention).
  51560. shaderName = data.shader;
  51561. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  51562. shaderName = 'msdf';
  51563. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  51564. shaderName = 'sdf';
  51565. }
  51566. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  51567. shaderData.alphaTest = data.alphaTest;
  51568. shaderData.color = data.color;
  51569. shaderData.map = this.texture;
  51570. shaderData.opacity = data.opacity;
  51571. shaderData.side = parseSide(data.side);
  51572. shaderData.transparent = data.transparent;
  51573. shaderData.negate = data.negate;
  51574. // Shader has not changed, do an update.
  51575. if (!hasChangedShader) {
  51576. // Update shader material.
  51577. this.shaderObject.update(shaderData);
  51578. // Apparently, was not set on `init` nor `update`.
  51579. material.transparent = shaderData.transparent;
  51580. material.side = shaderData.side;
  51581. return;
  51582. }
  51583. // Shader has changed. Create a shader material.
  51584. NewShader = createShader(this.el, shaderName, shaderData);
  51585. this.material = NewShader.material;
  51586. this.shaderObject = NewShader.shader;
  51587. // Set new shader material.
  51588. this.material.side = shaderData.side;
  51589. if (this.mesh) { this.mesh.material = this.material; }
  51590. },
  51591. /**
  51592. * Load font for geometry, load font image for material, and apply.
  51593. */
  51594. updateFont: function () {
  51595. var data = this.data;
  51596. var el = this.el;
  51597. var fontSrc;
  51598. var geometry = this.geometry;
  51599. var self = this;
  51600. if (!data.font) { warn('No font specified. Using the default font.'); }
  51601. // Make invisible during font swap.
  51602. if (this.mesh) { this.mesh.visible = false; }
  51603. // Look up font URL to use, and perform cached load.
  51604. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  51605. cache.get(fontSrc, function doLoadFont () {
  51606. return loadFont(fontSrc, data.yOffset);
  51607. }).then(function setFont (font) {
  51608. var fontImgSrc;
  51609. if (font.pages.length !== 1) {
  51610. throw new Error('Currently only single-page bitmap fonts are supported.');
  51611. }
  51612. if (!fontWidthFactors[fontSrc]) {
  51613. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  51614. }
  51615. self.currentFont = font;
  51616. // Look up font image URL to use, and perform cached load.
  51617. fontImgSrc = self.getFontImageSrc();
  51618. cache.get(fontImgSrc, function () {
  51619. return loadTexture(fontImgSrc);
  51620. }).then(function (image) {
  51621. // Make mesh visible and apply font image as texture.
  51622. var texture = self.texture;
  51623. texture.image = image;
  51624. texture.needsUpdate = true;
  51625. textures[data.font] = texture;
  51626. self.texture = texture;
  51627. self.initMesh();
  51628. self.currentFont = font;
  51629. // Update geometry given font metrics.
  51630. self.updateGeometry(geometry, font);
  51631. self.updateLayout();
  51632. self.mesh.visible = true;
  51633. el.emit('textfontset', {font: data.font, fontObj: font});
  51634. }).catch(function (err) {
  51635. error(err.message);
  51636. error(err.stack);
  51637. });
  51638. }).catch(function (err) {
  51639. error(err.message);
  51640. error(err.stack);
  51641. });
  51642. },
  51643. initMesh: function () {
  51644. if (this.mesh) { return; }
  51645. this.mesh = new THREE.Mesh(this.geometry, this.material);
  51646. this.el.setObject3D(this.attrName, this.mesh);
  51647. },
  51648. getFontImageSrc: function () {
  51649. if (this.data.fontImage) { return this.data.fontImage; }
  51650. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  51651. var imageSrc = this.currentFont.pages[0];
  51652. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  51653. // path on disk and try to infer the path from the font source instead.
  51654. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  51655. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  51656. }
  51657. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  51658. },
  51659. /**
  51660. * Update layout with anchor, alignment, baseline, and considering any meshes.
  51661. */
  51662. updateLayout: function () {
  51663. var anchor;
  51664. var baseline;
  51665. var el = this.el;
  51666. var data = this.data;
  51667. var geometry = this.geometry;
  51668. var geometryComponent;
  51669. var height;
  51670. var layout;
  51671. var mesh = this.mesh;
  51672. var textRenderWidth;
  51673. var textScale;
  51674. var width;
  51675. var x;
  51676. var y;
  51677. if (!mesh || !geometry.layout) { return; }
  51678. // Determine width to use (defined width, geometry's width, or default width).
  51679. geometryComponent = el.getAttribute('geometry');
  51680. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  51681. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  51682. // Note that experimental factor will never be correct for variable width fonts.
  51683. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  51684. this.currentFont.widthFactor);
  51685. textScale = width / textRenderWidth;
  51686. // Determine height to use.
  51687. layout = geometry.layout;
  51688. height = textScale * (layout.height + layout.descender);
  51689. // Update geometry dimensions to match text layout if width and height are set to 0.
  51690. // For example, scales a plane to fit text.
  51691. if (geometryComponent && geometryComponent.primitive === 'plane') {
  51692. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  51693. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  51694. }
  51695. // Calculate X position to anchor text left, center, or right.
  51696. anchor = data.anchor === 'align' ? data.align : data.anchor;
  51697. if (anchor === 'left') {
  51698. x = 0;
  51699. } else if (anchor === 'right') {
  51700. x = -1 * layout.width;
  51701. } else if (anchor === 'center') {
  51702. x = -1 * layout.width / 2;
  51703. } else {
  51704. throw new TypeError('Invalid text.anchor property value', anchor);
  51705. }
  51706. // Calculate Y position to anchor text top, center, or bottom.
  51707. baseline = data.baseline;
  51708. if (baseline === 'bottom') {
  51709. y = 0;
  51710. } else if (baseline === 'top') {
  51711. y = -1 * layout.height + layout.ascender;
  51712. } else if (baseline === 'center') {
  51713. y = -1 * layout.height / 2;
  51714. } else {
  51715. throw new TypeError('Invalid text.baseline property value', baseline);
  51716. }
  51717. // Position and scale mesh to apply layout.
  51718. mesh.position.x = x * textScale + data.xOffset;
  51719. mesh.position.y = y * textScale;
  51720. // Place text slightly in front to avoid Z-fighting.
  51721. mesh.position.z = data.zOffset;
  51722. mesh.scale.set(textScale, -1 * textScale, textScale);
  51723. },
  51724. /**
  51725. * Grab font from the constant.
  51726. * Set as a method for test stubbing purposes.
  51727. */
  51728. lookupFont: function (key) {
  51729. return FONTS[key];
  51730. },
  51731. /**
  51732. * Update the text geometry using `three-bmfont-text.update`.
  51733. */
  51734. updateGeometry: (function () {
  51735. var geometryUpdateBase = {};
  51736. var geometryUpdateData = {};
  51737. var newLineRegex = /\\n/g;
  51738. var tabRegex = /\\t/g;
  51739. return function (geometry, font) {
  51740. var data = this.data;
  51741. geometryUpdateData.font = font;
  51742. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  51743. ? data.lineHeight
  51744. : font.common.lineHeight;
  51745. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  51746. .replace(tabRegex, '\t');
  51747. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  51748. font.widthFactor);
  51749. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  51750. };
  51751. })()
  51752. });
  51753. /**
  51754. * Due to using negative scale, we return the opposite side specified.
  51755. * https://github.com/mrdoob/three.js/pull/12787/
  51756. */
  51757. function parseSide (side) {
  51758. switch (side) {
  51759. case 'back': {
  51760. return THREE.FrontSide;
  51761. }
  51762. case 'double': {
  51763. return THREE.DoubleSide;
  51764. }
  51765. default: {
  51766. return THREE.BackSide;
  51767. }
  51768. }
  51769. }
  51770. /**
  51771. * @returns {Promise}
  51772. */
  51773. function loadFont (src, yOffset) {
  51774. return new Promise(function (resolve, reject) {
  51775. loadBMFont(src, function (err, font) {
  51776. if (err) {
  51777. error('Error loading font', src);
  51778. reject(err);
  51779. return;
  51780. }
  51781. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  51782. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  51783. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  51784. resolve(font);
  51785. });
  51786. });
  51787. }
  51788. /**
  51789. * @returns {Promise}
  51790. */
  51791. function loadTexture (src) {
  51792. return new Promise(function (resolve, reject) {
  51793. new THREE.ImageLoader().load(src, function (image) {
  51794. resolve(image);
  51795. }, undefined, function () {
  51796. error('Error loading font image', src);
  51797. reject(null);
  51798. });
  51799. });
  51800. }
  51801. function createShader (el, shaderName, data) {
  51802. var shader;
  51803. var shaderObject;
  51804. // Set up Shader.
  51805. shaderObject = new shaders[shaderName].Shader();
  51806. shaderObject.el = el;
  51807. shaderObject.init(data);
  51808. shaderObject.update(data);
  51809. // Get material.
  51810. shader = shaderObject.material;
  51811. // Apparently, was not set on `init` nor `update`.
  51812. shader.transparent = data.transparent;
  51813. return {
  51814. material: shader,
  51815. shader: shaderObject
  51816. };
  51817. }
  51818. /**
  51819. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  51820. * Note that experimental factor will never be correct for variable width fonts.
  51821. */
  51822. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  51823. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  51824. }
  51825. /**
  51826. * Compute default font width factor to use.
  51827. */
  51828. function computeFontWidthFactor (font) {
  51829. var sum = 0;
  51830. var digitsum = 0;
  51831. var digits = 0;
  51832. font.chars.map(function (ch) {
  51833. sum += ch.xadvance;
  51834. if (ch.id >= 48 && ch.id <= 57) {
  51835. digits++;
  51836. digitsum += ch.xadvance;
  51837. }
  51838. });
  51839. return digits ? digitsum / digits : sum / font.chars.length;
  51840. }
  51841. /**
  51842. * Get or create a promise given a key and promise generator.
  51843. * @todo Move to a utility and use in other parts of A-Frame.
  51844. */
  51845. function PromiseCache () {
  51846. var cache = this.cache = {};
  51847. this.get = function (key, promiseGenerator) {
  51848. if (key in cache) {
  51849. return cache[key];
  51850. }
  51851. cache[key] = promiseGenerator();
  51852. return cache[key];
  51853. };
  51854. }
  51855. },{"../core/component":135,"../core/shader":145,"../lib/three":183,"../utils/":210,"load-bmfont":37,"three-bmfont-text":64}],118:[function(require,module,exports){
  51856. var registerComponent = require('../core/component').registerComponent;
  51857. var controllerUtils = require('../utils/tracked-controls');
  51858. var DEFAULT_CAMERA_HEIGHT = require('../constants').DEFAULT_CAMERA_HEIGHT;
  51859. var THREE = require('../lib/three');
  51860. var DEFAULT_HANDEDNESS = require('../constants').DEFAULT_HANDEDNESS;
  51861. // Vector from eyes to elbow (divided by user height).
  51862. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  51863. // Vector from eyes to elbow (divided by user height).
  51864. var FOREARM = {x: 0, y: 0, z: -0.175};
  51865. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  51866. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  51867. var EVENTS = {
  51868. AXISMOVE: 'axismove',
  51869. BUTTONCHANGED: 'buttonchanged',
  51870. BUTTONDOWN: 'buttondown',
  51871. BUTTONUP: 'buttonup',
  51872. TOUCHSTART: 'touchstart',
  51873. TOUCHEND: 'touchend'
  51874. };
  51875. /**
  51876. * Tracked controls component.
  51877. * Wrap the gamepad API for pose and button states.
  51878. * Select the appropriate controller and apply pose to the entity.
  51879. * Observe button states and emit appropriate events.
  51880. *
  51881. * @property {number} controller - Index of controller in array returned by Gamepad API.
  51882. * Only used if hand property is not set.
  51883. * @property {string} id - Selected controller among those returned by Gamepad API.
  51884. * @property {number} hand - If multiple controllers found with id, choose the one with the
  51885. * given value for hand. If set, we ignore 'controller' property
  51886. */
  51887. module.exports.Component = registerComponent('tracked-controls-webvr', {
  51888. schema: {
  51889. autoHide: {default: true},
  51890. controller: {default: 0},
  51891. id: {type: 'string', default: ''},
  51892. hand: {type: 'string', default: ''},
  51893. idPrefix: {type: 'string', default: ''},
  51894. orientationOffset: {type: 'vec3'},
  51895. // Arm model parameters when not 6DoF.
  51896. armModel: {default: false},
  51897. headElement: {type: 'selector'}
  51898. },
  51899. init: function () {
  51900. // Copy variables back to tracked-controls for backwards compatibility.
  51901. // Some 3rd components rely on them.
  51902. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  51903. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  51904. this.changedAxes = [];
  51905. this.targetControllerNumber = this.data.controller;
  51906. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  51907. this.deltaControllerPosition = new THREE.Vector3();
  51908. this.controllerQuaternion = new THREE.Quaternion();
  51909. this.controllerEuler = new THREE.Euler();
  51910. this.updateGamepad();
  51911. this.buttonEventDetails = {};
  51912. },
  51913. tick: function (time, delta) {
  51914. var mesh = this.el.getObject3D('mesh');
  51915. // Update mesh animations.
  51916. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  51917. this.updateGamepad();
  51918. this.updatePose();
  51919. this.updateButtons();
  51920. },
  51921. /**
  51922. * Return default user height to use for non-6DOF arm model.
  51923. */
  51924. defaultUserHeight: function () {
  51925. return DEFAULT_CAMERA_HEIGHT;
  51926. },
  51927. /**
  51928. * Return head element to use for non-6DOF arm model.
  51929. */
  51930. getHeadElement: function () {
  51931. return this.data.headElement || this.el.sceneEl.camera.el;
  51932. },
  51933. /**
  51934. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  51935. */
  51936. updateGamepad: function () {
  51937. var data = this.data;
  51938. var controller = controllerUtils.findMatchingControllerWebVR(
  51939. this.system.controllers,
  51940. data.id,
  51941. data.idPrefix,
  51942. data.hand,
  51943. data.controller
  51944. );
  51945. this.controller = controller;
  51946. // Legacy handle to the controller for old components.
  51947. this.el.components['tracked-controls'].controller = controller;
  51948. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  51949. },
  51950. /**
  51951. * Applies an artificial arm model to simulate elbow to wrist positioning
  51952. * based on the orientation of the controller.
  51953. *
  51954. * @param {object} controllerPosition - Existing vector to update with controller position.
  51955. */
  51956. applyArmModel: function (controllerPosition) {
  51957. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  51958. var controller = this.controller;
  51959. var controllerEuler = this.controllerEuler;
  51960. var controllerQuaternion = this.controllerQuaternion;
  51961. var deltaControllerPosition = this.deltaControllerPosition;
  51962. var hand;
  51963. var headEl;
  51964. var headObject3D;
  51965. var pose;
  51966. var userHeight;
  51967. headEl = this.getHeadElement();
  51968. headObject3D = headEl.object3D;
  51969. userHeight = this.defaultUserHeight();
  51970. pose = controller.pose;
  51971. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  51972. // Use camera position as head position.
  51973. controllerPosition.copy(headObject3D.position);
  51974. // Set offset for degenerate "arm model" to elbow.
  51975. deltaControllerPosition.set(
  51976. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  51977. EYES_TO_ELBOW.y, // Lower than our eyes.
  51978. EYES_TO_ELBOW.z); // Slightly out in front.
  51979. // Scale offset by user height.
  51980. deltaControllerPosition.multiplyScalar(userHeight);
  51981. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  51982. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  51983. // Apply rotated offset to position.
  51984. controllerPosition.add(deltaControllerPosition);
  51985. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  51986. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  51987. // Scale offset by user height.
  51988. deltaControllerPosition.multiplyScalar(userHeight);
  51989. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  51990. if (pose.orientation) {
  51991. controllerQuaternion.fromArray(pose.orientation);
  51992. } else {
  51993. controllerQuaternion.copy(headObject3D.quaternion);
  51994. }
  51995. controllerEuler.setFromQuaternion(controllerQuaternion);
  51996. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  51997. deltaControllerPosition.applyEuler(controllerEuler);
  51998. // Apply rotated offset to position.
  51999. controllerPosition.add(deltaControllerPosition);
  52000. },
  52001. /**
  52002. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  52003. */
  52004. updatePose: function () {
  52005. var controller = this.controller;
  52006. var data = this.data;
  52007. var object3D = this.el.object3D;
  52008. var pose;
  52009. var vrDisplay = this.system.vrDisplay;
  52010. var standingMatrix;
  52011. if (!controller) { return; }
  52012. // Compose pose from Gamepad.
  52013. pose = controller.pose;
  52014. if (pose.position) {
  52015. object3D.position.fromArray(pose.position);
  52016. } else {
  52017. // Controller not 6DOF, apply arm model.
  52018. if (data.armModel) { this.applyArmModel(object3D.position); }
  52019. }
  52020. if (pose.orientation) {
  52021. object3D.quaternion.fromArray(pose.orientation);
  52022. }
  52023. // Apply transforms, if 6DOF and in VR.
  52024. if (vrDisplay && pose.position) {
  52025. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  52026. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  52027. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  52028. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  52029. }
  52030. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  52031. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  52032. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  52033. },
  52034. /**
  52035. * Handle button changes including axes, presses, touches, values.
  52036. */
  52037. updateButtons: function () {
  52038. var buttonState;
  52039. var controller = this.controller;
  52040. var id;
  52041. if (!controller) { return; }
  52042. // Check every button.
  52043. for (id = 0; id < controller.buttons.length; ++id) {
  52044. // Initialize button state.
  52045. if (!this.buttonStates[id]) {
  52046. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52047. }
  52048. if (!this.buttonEventDetails[id]) {
  52049. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52050. }
  52051. buttonState = controller.buttons[id];
  52052. this.handleButton(id, buttonState);
  52053. }
  52054. // Check axes.
  52055. this.handleAxes();
  52056. },
  52057. /**
  52058. * Handle presses and touches for a single button.
  52059. *
  52060. * @param {number} id - Index of button in Gamepad button array.
  52061. * @param {number} buttonState - Value of button state from 0 to 1.
  52062. * @returns {boolean} Whether button has changed in any way.
  52063. */
  52064. handleButton: function (id, buttonState) {
  52065. var changed;
  52066. changed = this.handlePress(id, buttonState) |
  52067. this.handleTouch(id, buttonState) |
  52068. this.handleValue(id, buttonState);
  52069. if (!changed) { return false; }
  52070. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52071. return true;
  52072. },
  52073. /**
  52074. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52075. * Compare each component of the axis to the previous value to determine change.
  52076. *
  52077. * @returns {boolean} Whether axes changed.
  52078. */
  52079. handleAxes: function () {
  52080. var changed = false;
  52081. var controllerAxes = this.controller.axes;
  52082. var i;
  52083. var previousAxis = this.axis;
  52084. var changedAxes = this.changedAxes;
  52085. // Check if axis changed.
  52086. this.changedAxes.splice(0, this.changedAxes.length);
  52087. for (i = 0; i < controllerAxes.length; ++i) {
  52088. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52089. if (changedAxes[i]) { changed = true; }
  52090. }
  52091. if (!changed) { return false; }
  52092. this.axis.splice(0, this.axis.length);
  52093. for (i = 0; i < controllerAxes.length; i++) {
  52094. this.axis.push(controllerAxes[i]);
  52095. }
  52096. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52097. return true;
  52098. },
  52099. /**
  52100. * Determine whether a button press has occured and emit events as appropriate.
  52101. *
  52102. * @param {string} id - ID of the button to check.
  52103. * @param {object} buttonState - State of the button to check.
  52104. * @returns {boolean} Whether button press state changed.
  52105. */
  52106. handlePress: function (id, buttonState) {
  52107. var evtName;
  52108. var previousButtonState = this.buttonStates[id];
  52109. // Not changed.
  52110. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52111. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52112. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52113. previousButtonState.pressed = buttonState.pressed;
  52114. return true;
  52115. },
  52116. /**
  52117. * Determine whether a button touch has occured and emit events as appropriate.
  52118. *
  52119. * @param {string} id - ID of the button to check.
  52120. * @param {object} buttonState - State of the button to check.
  52121. * @returns {boolean} Whether button touch state changed.
  52122. */
  52123. handleTouch: function (id, buttonState) {
  52124. var evtName;
  52125. var previousButtonState = this.buttonStates[id];
  52126. // Not changed.
  52127. if (buttonState.touched === previousButtonState.touched) { return false; }
  52128. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52129. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  52130. previousButtonState.touched = buttonState.touched;
  52131. return true;
  52132. },
  52133. /**
  52134. * Determine whether a button value has changed.
  52135. *
  52136. * @param {string} id - Id of the button to check.
  52137. * @param {object} buttonState - State of the button to check.
  52138. * @returns {boolean} Whether button value changed.
  52139. */
  52140. handleValue: function (id, buttonState) {
  52141. var previousButtonState = this.buttonStates[id];
  52142. // Not changed.
  52143. if (buttonState.value === previousButtonState.value) { return false; }
  52144. previousButtonState.value = buttonState.value;
  52145. return true;
  52146. }
  52147. });
  52148. },{"../constants":127,"../core/component":135,"../lib/three":183,"../utils/tracked-controls":219}],119:[function(require,module,exports){
  52149. var controllerUtils = require('../utils/tracked-controls');
  52150. var registerComponent = require('../core/component').registerComponent;
  52151. var EVENTS = {
  52152. AXISMOVE: 'axismove',
  52153. BUTTONCHANGED: 'buttonchanged',
  52154. BUTTONDOWN: 'buttondown',
  52155. BUTTONUP: 'buttonup',
  52156. TOUCHSTART: 'touchstart',
  52157. TOUCHEND: 'touchend'
  52158. };
  52159. module.exports.Component = registerComponent('tracked-controls-webxr', {
  52160. schema: {
  52161. id: {type: 'string', default: ''},
  52162. hand: {type: 'string', default: ''},
  52163. handTrackingEnabled: {default: false},
  52164. index: {type: 'int', default: -1},
  52165. iterateControllerProfiles: {default: false}
  52166. },
  52167. init: function () {
  52168. this.updateController = this.updateController.bind(this);
  52169. this.buttonEventDetails = {};
  52170. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52171. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52172. this.changedAxes = [];
  52173. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52174. },
  52175. update: function () {
  52176. this.updateController();
  52177. },
  52178. play: function () {
  52179. var sceneEl = this.el.sceneEl;
  52180. this.updateController();
  52181. sceneEl.addEventListener('controllersupdated', this.updateController);
  52182. },
  52183. pause: function () {
  52184. var sceneEl = this.el.sceneEl;
  52185. sceneEl.removeEventListener('controllersupdated', this.updateController);
  52186. },
  52187. isControllerPresent: function (evt) {
  52188. if (!this.controller || this.controller.gamepad) { return false; }
  52189. if (evt.inputSource.handedness !== 'none' &&
  52190. evt.inputSource.handedness !== this.data.hand) {
  52191. return false;
  52192. }
  52193. return true;
  52194. },
  52195. /**
  52196. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52197. */
  52198. updateController: function () {
  52199. this.controller = controllerUtils.findMatchingControllerWebXR(
  52200. this.system.controllers,
  52201. this.data.id,
  52202. this.data.hand,
  52203. this.data.index,
  52204. this.data.iterateControllerProfiles,
  52205. this.data.handTrackingEnabled
  52206. );
  52207. // Legacy handle to the controller for old components.
  52208. this.el.components['tracked-controls'].controller = this.controller;
  52209. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52210. },
  52211. tick: function () {
  52212. var sceneEl = this.el.sceneEl;
  52213. var controller = this.controller;
  52214. var frame = sceneEl.frame;
  52215. if (!controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  52216. if (!controller.hand) {
  52217. this.pose = frame.getPose(controller.targetRaySpace, this.system.referenceSpace);
  52218. this.updatePose();
  52219. this.updateButtons();
  52220. }
  52221. },
  52222. updatePose: function () {
  52223. var object3D = this.el.object3D;
  52224. var pose = this.pose;
  52225. if (!pose) { return; }
  52226. object3D.matrix.elements = pose.transform.matrix;
  52227. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  52228. },
  52229. /**
  52230. * Handle button changes including axes, presses, touches, values.
  52231. */
  52232. updateButtons: function () {
  52233. var buttonState;
  52234. var id;
  52235. var controller = this.controller;
  52236. var gamepad;
  52237. if (!controller || !controller.gamepad) { return; }
  52238. gamepad = controller.gamepad;
  52239. // Check every button.
  52240. for (id = 0; id < gamepad.buttons.length; ++id) {
  52241. // Initialize button state.
  52242. if (!this.buttonStates[id]) {
  52243. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52244. }
  52245. if (!this.buttonEventDetails[id]) {
  52246. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52247. }
  52248. buttonState = gamepad.buttons[id];
  52249. this.handleButton(id, buttonState);
  52250. }
  52251. // Check axes.
  52252. this.handleAxes();
  52253. },
  52254. /**
  52255. * Handle presses and touches for a single button.
  52256. *
  52257. * @param {number} id - Index of button in Gamepad button array.
  52258. * @param {number} buttonState - Value of button state from 0 to 1.
  52259. * @returns {boolean} Whether button has changed in any way.
  52260. */
  52261. handleButton: function (id, buttonState) {
  52262. var changed;
  52263. changed = this.handlePress(id, buttonState) |
  52264. this.handleTouch(id, buttonState) |
  52265. this.handleValue(id, buttonState);
  52266. if (!changed) { return false; }
  52267. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52268. return true;
  52269. },
  52270. /**
  52271. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52272. * Compare each component of the axis to the previous value to determine change.
  52273. *
  52274. * @returns {boolean} Whether axes changed.
  52275. */
  52276. handleAxes: function () {
  52277. var changed = false;
  52278. var controllerAxes = this.controller.gamepad.axes;
  52279. var i;
  52280. var previousAxis = this.axis;
  52281. var changedAxes = this.changedAxes;
  52282. // Check if axis changed.
  52283. this.changedAxes.splice(0, this.changedAxes.length);
  52284. for (i = 0; i < controllerAxes.length; ++i) {
  52285. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52286. if (changedAxes[i]) { changed = true; }
  52287. }
  52288. if (!changed) { return false; }
  52289. this.axis.splice(0, this.axis.length);
  52290. for (i = 0; i < controllerAxes.length; i++) {
  52291. this.axis.push(controllerAxes[i]);
  52292. }
  52293. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52294. return true;
  52295. },
  52296. /**
  52297. * Determine whether a button press has occured and emit events as appropriate.
  52298. *
  52299. * @param {string} id - ID of the button to check.
  52300. * @param {object} buttonState - State of the button to check.
  52301. * @returns {boolean} Whether button press state changed.
  52302. */
  52303. handlePress: function (id, buttonState) {
  52304. var evtName;
  52305. var previousButtonState = this.buttonStates[id];
  52306. // Not changed.
  52307. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52308. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52309. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52310. previousButtonState.pressed = buttonState.pressed;
  52311. return true;
  52312. },
  52313. /**
  52314. * Determine whether a button touch has occured and emit events as appropriate.
  52315. *
  52316. * @param {string} id - ID of the button to check.
  52317. * @param {object} buttonState - State of the button to check.
  52318. * @returns {boolean} Whether button touch state changed.
  52319. */
  52320. handleTouch: function (id, buttonState) {
  52321. var evtName;
  52322. var previousButtonState = this.buttonStates[id];
  52323. // Not changed.
  52324. if (buttonState.touched === previousButtonState.touched) { return false; }
  52325. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52326. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52327. previousButtonState.touched = buttonState.touched;
  52328. return true;
  52329. },
  52330. /**
  52331. * Determine whether a button value has changed.
  52332. *
  52333. * @param {string} id - Id of the button to check.
  52334. * @param {object} buttonState - State of the button to check.
  52335. * @returns {boolean} Whether button value changed.
  52336. */
  52337. handleValue: function (id, buttonState) {
  52338. var previousButtonState = this.buttonStates[id];
  52339. // Not changed.
  52340. if (buttonState.value === previousButtonState.value) { return false; }
  52341. previousButtonState.value = buttonState.value;
  52342. return true;
  52343. }
  52344. });
  52345. },{"../core/component":135,"../utils/tracked-controls":219}],120:[function(require,module,exports){
  52346. var registerComponent = require('../core/component').registerComponent;
  52347. /**
  52348. * Tracked controls.
  52349. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  52350. *
  52351. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52352. * Only used if hand property is not set.
  52353. * @property {string} id - Selected controller among those returned by Gamepad API.
  52354. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52355. * given value for hand. If set, we ignore 'controller' property
  52356. */
  52357. module.exports.Component = registerComponent('tracked-controls', {
  52358. schema: {
  52359. autoHide: {default: true},
  52360. controller: {default: -1},
  52361. id: {type: 'string', default: ''},
  52362. hand: {type: 'string', default: ''},
  52363. idPrefix: {type: 'string', default: ''},
  52364. handTrackingEnabled: {default: false},
  52365. orientationOffset: {type: 'vec3'},
  52366. // Arm model parameters when not 6DoF.
  52367. armModel: {default: false},
  52368. headElement: {type: 'selector'},
  52369. iterateControllerProfiles: {default: false}
  52370. },
  52371. update: function () {
  52372. var data = this.data;
  52373. var el = this.el;
  52374. if (el.sceneEl.hasWebXR) {
  52375. el.setAttribute('tracked-controls-webxr', {
  52376. id: data.id,
  52377. hand: data.hand,
  52378. index: data.controller,
  52379. iterateControllerProfiles: data.iterateControllerProfiles,
  52380. handTrackingEnabled: data.handTrackingEnabled
  52381. });
  52382. } else {
  52383. el.setAttribute('tracked-controls-webvr', data);
  52384. }
  52385. }
  52386. });
  52387. },{"../core/component":135}],121:[function(require,module,exports){
  52388. var registerComponent = require('../core/component').registerComponent;
  52389. var bind = require('../utils/bind');
  52390. var THREE = require('../lib/three');
  52391. var trackedControlsUtils = require('../utils/tracked-controls');
  52392. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52393. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52394. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52395. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve-index-';
  52396. var INDEX_CONTROLLER_MODEL_URL = {
  52397. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.glb',
  52398. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.glb'
  52399. };
  52400. var GAMEPAD_ID_PREFIX = 'valve';
  52401. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  52402. var INDEX_CONTROLLER_POSITION_OFFSET_WEBVR = {
  52403. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  52404. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  52405. };
  52406. var INDEX_CONTROLLER_POSITION_OFFSET_WEBXR = {
  52407. left: {x: 0, y: -0.05, z: 0.06},
  52408. right: {x: 0, y: -0.05, z: 0.06}
  52409. };
  52410. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR = {
  52411. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  52412. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  52413. };
  52414. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR = {
  52415. left: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'},
  52416. right: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'}
  52417. };
  52418. var INDEX_CONTROLLER_ROTATION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR : INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR;
  52419. var INDEX_CONTROLLER_POSITION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_POSITION_OFFSET_WEBXR : INDEX_CONTROLLER_POSITION_OFFSET_WEBVR;
  52420. /**
  52421. * Vive controls.
  52422. * Interface with Vive controllers and map Gamepad events to controller buttons:
  52423. * trackpad, trigger, grip, menu, system
  52424. * Load a controller model and highlight the pressed buttons.
  52425. */
  52426. module.exports.Component = registerComponent('valve-index-controls', {
  52427. schema: {
  52428. hand: {default: 'left'},
  52429. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  52430. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  52431. model: {default: true},
  52432. orientationOffset: {type: 'vec3'}
  52433. },
  52434. mapping: {
  52435. axes: {
  52436. trackpad: [0, 1],
  52437. thumbstick: [2, 3]
  52438. },
  52439. buttons: ['trigger', 'grip', 'trackpad', 'thumbstick', 'abutton']
  52440. },
  52441. init: function () {
  52442. var self = this;
  52443. this.controllerPresent = false;
  52444. this.lastControllerCheck = 0;
  52445. this.onButtonChanged = bind(this.onButtonChanged, this);
  52446. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52447. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52448. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52449. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52450. this.previousButtonValues = {};
  52451. this.rendererSystem = this.el.sceneEl.systems.renderer;
  52452. this.bindMethods();
  52453. },
  52454. play: function () {
  52455. this.checkIfControllerPresent();
  52456. this.addControllersUpdateListener();
  52457. },
  52458. pause: function () {
  52459. this.removeEventListeners();
  52460. this.removeControllersUpdateListener();
  52461. },
  52462. bindMethods: function () {
  52463. this.onModelLoaded = bind(this.onModelLoaded, this);
  52464. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52465. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52466. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  52467. this.onAxisMoved = bind(this.onAxisMoved, this);
  52468. },
  52469. addEventListeners: function () {
  52470. var el = this.el;
  52471. el.addEventListener('buttonchanged', this.onButtonChanged);
  52472. el.addEventListener('buttondown', this.onButtonDown);
  52473. el.addEventListener('buttonup', this.onButtonUp);
  52474. el.addEventListener('touchend', this.onButtonTouchEnd);
  52475. el.addEventListener('touchstart', this.onButtonTouchStart);
  52476. el.addEventListener('model-loaded', this.onModelLoaded);
  52477. el.addEventListener('axismove', this.onAxisMoved);
  52478. this.controllerEventsActive = true;
  52479. },
  52480. removeEventListeners: function () {
  52481. var el = this.el;
  52482. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52483. el.removeEventListener('buttondown', this.onButtonDown);
  52484. el.removeEventListener('buttonup', this.onButtonUp);
  52485. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52486. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52487. el.removeEventListener('model-loaded', this.onModelLoaded);
  52488. el.removeEventListener('axismove', this.onAxisMoved);
  52489. this.controllerEventsActive = false;
  52490. },
  52491. /**
  52492. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  52493. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  52494. { hand: data.hand });
  52495. * Until then, use hardcoded index.
  52496. */
  52497. checkIfControllerPresent: function () {
  52498. var data = this.data;
  52499. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  52500. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  52501. },
  52502. injectTrackedControls: function () {
  52503. var el = this.el;
  52504. var data = this.data;
  52505. // If we have an OpenVR Gamepad, use the fixed mapping.
  52506. el.setAttribute('tracked-controls', {
  52507. idPrefix: GAMEPAD_ID_PREFIX,
  52508. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  52509. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  52510. hand: data.hand,
  52511. orientationOffset: data.orientationOffset
  52512. });
  52513. this.loadModel();
  52514. },
  52515. loadModel: function () {
  52516. var data = this.data;
  52517. if (!data.model) { return; }
  52518. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  52519. },
  52520. addControllersUpdateListener: function () {
  52521. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52522. },
  52523. removeControllersUpdateListener: function () {
  52524. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52525. },
  52526. onControllersUpdate: function () {
  52527. this.checkIfControllerPresent();
  52528. },
  52529. /**
  52530. * Rotate the trigger button based on how hard the trigger is pressed.
  52531. */
  52532. onButtonChanged: function (evt) {
  52533. var button = this.mapping.buttons[evt.detail.id];
  52534. var buttonMeshes = this.buttonMeshes;
  52535. var analogValue;
  52536. if (!button) { return; }
  52537. if (button === 'trigger') {
  52538. analogValue = evt.detail.state.value;
  52539. // Update trigger rotation depending on button value.
  52540. if (buttonMeshes && buttonMeshes.trigger) {
  52541. buttonMeshes.trigger.rotation.x = this.triggerOriginalRotationX - analogValue * (Math.PI / 40);
  52542. }
  52543. }
  52544. // Pass along changed event with button state, using button mapping for convenience.
  52545. this.el.emit(button + 'changed', evt.detail.state);
  52546. },
  52547. onModelLoaded: function (evt) {
  52548. var buttonMeshes;
  52549. var controllerObject3D = evt.detail.model;
  52550. var self = this;
  52551. if (!this.data.model) { return; }
  52552. // Store button meshes object to be able to change their colors.
  52553. buttonMeshes = this.buttonMeshes = {};
  52554. buttonMeshes.grip = {
  52555. left: controllerObject3D.getObjectByName('leftgrip'),
  52556. right: controllerObject3D.getObjectByName('rightgrip')
  52557. };
  52558. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  52559. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  52560. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  52561. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  52562. this.triggerOriginalRotationX = buttonMeshes.trigger.rotation.x;
  52563. // Set default colors.
  52564. Object.keys(buttonMeshes).forEach(function (buttonName) {
  52565. self.setButtonColor(buttonName, self.data.buttonColor);
  52566. });
  52567. // Offset pivot point.
  52568. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  52569. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  52570. this.el.emit('controllermodelready', {
  52571. name: 'valve-index-controlls',
  52572. model: this.data.model,
  52573. rayOrigin: new THREE.Vector3(0, 0, 0)
  52574. });
  52575. },
  52576. onAxisMoved: function (evt) {
  52577. emitIfAxesChanged(this, this.mapping.axes, evt);
  52578. },
  52579. updateModel: function (buttonName, evtName) {
  52580. var color;
  52581. var isTouch;
  52582. if (!this.data.model) { return; }
  52583. isTouch = evtName.indexOf('touch') !== -1;
  52584. // Don't change color for trackpad touch.
  52585. if (isTouch) { return; }
  52586. // Update colors.
  52587. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  52588. this.setButtonColor(buttonName, color);
  52589. },
  52590. setButtonColor: function (buttonName, color) {
  52591. // TODO: The meshes aren't set up correctly now, skipping for the moment
  52592. return;
  52593. }
  52594. });
  52595. },{"../core/component":135,"../lib/three":183,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],122:[function(require,module,exports){
  52596. var registerComponent = require('../core/component').registerComponent;
  52597. /**
  52598. * Visibility component.
  52599. */
  52600. module.exports.Component = registerComponent('visible', {
  52601. schema: {default: true},
  52602. update: function () {
  52603. this.el.object3D.visible = this.data;
  52604. }
  52605. });
  52606. },{"../core/component":135}],123:[function(require,module,exports){
  52607. var registerComponent = require('../core/component').registerComponent;
  52608. var bind = require('../utils/bind');
  52609. var trackedControlsUtils = require('../utils/tracked-controls');
  52610. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52611. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52612. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52613. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  52614. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  52615. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  52616. var GAMEPAD_ID_WEBXR = 'htc-vive';
  52617. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  52618. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  52619. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  52620. /**
  52621. * Button IDs:
  52622. * 0 - trackpad
  52623. * 1 - trigger (intensity value from 0.5 to 1)
  52624. * 2 - grip
  52625. * 3 - menu (dispatch but better for menu options)
  52626. * 4 - system (never dispatched on this layer)
  52627. */
  52628. var INPUT_MAPPING_WEBVR = {
  52629. axes: {trackpad: [0, 1]},
  52630. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  52631. };
  52632. /**
  52633. * Button IDs:
  52634. * 0 - trigger
  52635. * 1 - squeeze
  52636. * 2 - touchpad
  52637. * 3 - none (dispatch but better for menu options)
  52638. * 4 - menu (never dispatched on this layer)
  52639. *
  52640. * Axis:
  52641. * 0 - touchpad x axis
  52642. * 1 - touchpad y axis
  52643. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  52644. */
  52645. var INPUT_MAPPING_WEBXR = {
  52646. axes: {thumbstick: [0, 1]},
  52647. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  52648. };
  52649. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  52650. /**
  52651. * Vive controls.
  52652. * Interface with Vive controllers and map Gamepad events to controller buttons:
  52653. * trackpad, trigger, grip, menu, system
  52654. * Load a controller model and highlight the pressed buttons.
  52655. */
  52656. module.exports.Component = registerComponent('vive-controls', {
  52657. schema: {
  52658. hand: {default: 'left'},
  52659. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  52660. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  52661. model: {default: true},
  52662. orientationOffset: {type: 'vec3'}
  52663. },
  52664. mapping: INPUT_MAPPING,
  52665. init: function () {
  52666. var self = this;
  52667. this.controllerPresent = false;
  52668. this.lastControllerCheck = 0;
  52669. this.onButtonChanged = bind(this.onButtonChanged, this);
  52670. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52671. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52672. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52673. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52674. this.previousButtonValues = {};
  52675. this.rendererSystem = this.el.sceneEl.systems.renderer;
  52676. this.bindMethods();
  52677. },
  52678. update: function () {
  52679. var data = this.data;
  52680. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  52681. },
  52682. play: function () {
  52683. this.checkIfControllerPresent();
  52684. this.addControllersUpdateListener();
  52685. },
  52686. pause: function () {
  52687. this.removeEventListeners();
  52688. this.removeControllersUpdateListener();
  52689. },
  52690. bindMethods: function () {
  52691. this.onModelLoaded = bind(this.onModelLoaded, this);
  52692. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52693. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52694. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  52695. this.onAxisMoved = bind(this.onAxisMoved, this);
  52696. },
  52697. addEventListeners: function () {
  52698. var el = this.el;
  52699. el.addEventListener('buttonchanged', this.onButtonChanged);
  52700. el.addEventListener('buttondown', this.onButtonDown);
  52701. el.addEventListener('buttonup', this.onButtonUp);
  52702. el.addEventListener('touchend', this.onButtonTouchEnd);
  52703. el.addEventListener('touchstart', this.onButtonTouchStart);
  52704. el.addEventListener('model-loaded', this.onModelLoaded);
  52705. el.addEventListener('axismove', this.onAxisMoved);
  52706. this.controllerEventsActive = true;
  52707. },
  52708. removeEventListeners: function () {
  52709. var el = this.el;
  52710. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52711. el.removeEventListener('buttondown', this.onButtonDown);
  52712. el.removeEventListener('buttonup', this.onButtonUp);
  52713. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52714. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52715. el.removeEventListener('model-loaded', this.onModelLoaded);
  52716. el.removeEventListener('axismove', this.onAxisMoved);
  52717. this.controllerEventsActive = false;
  52718. },
  52719. /**
  52720. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  52721. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  52722. { hand: data.hand });
  52723. * Until then, use hardcoded index.
  52724. */
  52725. checkIfControllerPresent: function () {
  52726. var data = this.data;
  52727. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  52728. },
  52729. injectTrackedControls: function () {
  52730. var el = this.el;
  52731. var data = this.data;
  52732. // If we have an OpenVR Gamepad, use the fixed mapping.
  52733. el.setAttribute('tracked-controls', {
  52734. idPrefix: GAMEPAD_ID_PREFIX,
  52735. hand: data.hand,
  52736. controller: this.controllerIndex,
  52737. orientationOffset: data.orientationOffset
  52738. });
  52739. // Load model.
  52740. if (!this.data.model) { return; }
  52741. this.el.setAttribute('obj-model', {
  52742. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  52743. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  52744. });
  52745. },
  52746. addControllersUpdateListener: function () {
  52747. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52748. },
  52749. removeControllersUpdateListener: function () {
  52750. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52751. },
  52752. onControllersUpdate: function () {
  52753. this.checkIfControllerPresent();
  52754. },
  52755. /**
  52756. * Rotate the trigger button based on how hard the trigger is pressed.
  52757. */
  52758. onButtonChanged: function (evt) {
  52759. var button = this.mapping.buttons[evt.detail.id];
  52760. var buttonMeshes = this.buttonMeshes;
  52761. var analogValue;
  52762. if (!button) { return; }
  52763. if (button === 'trigger') {
  52764. analogValue = evt.detail.state.value;
  52765. // Update trigger rotation depending on button value.
  52766. if (buttonMeshes && buttonMeshes.trigger) {
  52767. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  52768. }
  52769. }
  52770. // Pass along changed event with button state, using button mapping for convenience.
  52771. this.el.emit(button + 'changed', evt.detail.state);
  52772. },
  52773. onModelLoaded: function (evt) {
  52774. var buttonMeshes;
  52775. var controllerObject3D = evt.detail.model;
  52776. var self = this;
  52777. if (!this.data.model) { return; }
  52778. // Store button meshes object to be able to change their colors.
  52779. buttonMeshes = this.buttonMeshes = {};
  52780. buttonMeshes.grip = {
  52781. left: controllerObject3D.getObjectByName('leftgrip'),
  52782. right: controllerObject3D.getObjectByName('rightgrip')
  52783. };
  52784. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  52785. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  52786. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  52787. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  52788. // Set default colors.
  52789. Object.keys(buttonMeshes).forEach(function (buttonName) {
  52790. self.setButtonColor(buttonName, self.data.buttonColor);
  52791. });
  52792. // Offset pivot point.
  52793. controllerObject3D.position.set(0, -0.015, 0.04);
  52794. },
  52795. onAxisMoved: function (evt) {
  52796. emitIfAxesChanged(this, this.mapping.axes, evt);
  52797. },
  52798. updateModel: function (buttonName, evtName) {
  52799. var color;
  52800. var isTouch;
  52801. if (!this.data.model) { return; }
  52802. isTouch = evtName.indexOf('touch') !== -1;
  52803. // Don't change color for trackpad touch.
  52804. if (isTouch) { return; }
  52805. // Update colors.
  52806. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  52807. this.setButtonColor(buttonName, color);
  52808. },
  52809. setButtonColor: function (buttonName, color) {
  52810. var buttonMeshes = this.buttonMeshes;
  52811. var rendererSystem = this.rendererSystem;
  52812. if (!buttonMeshes) { return; }
  52813. // Need to do both left and right sides for grip.
  52814. if (buttonName === 'grip') {
  52815. buttonMeshes.grip.left.material.color.set(color);
  52816. buttonMeshes.grip.right.material.color.set(color);
  52817. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  52818. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  52819. return;
  52820. }
  52821. buttonMeshes[buttonName].material.color.set(color);
  52822. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  52823. }
  52824. });
  52825. },{"../core/component":135,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],124:[function(require,module,exports){
  52826. var registerComponent = require('../core/component').registerComponent;
  52827. var bind = require('../utils/bind');
  52828. var trackedControlsUtils = require('../utils/tracked-controls');
  52829. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52830. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52831. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52832. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  52833. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  52834. /**
  52835. * Vive Focus controls.
  52836. * Interface with Vive Focus controller and map Gamepad events to
  52837. * controller buttons: trackpad, trigger
  52838. * Load a controller model and highlight the pressed buttons.
  52839. */
  52840. module.exports.Component = registerComponent('vive-focus-controls', {
  52841. schema: {
  52842. hand: {default: ''}, // This informs the degenerate arm model.
  52843. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  52844. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  52845. model: {default: true},
  52846. orientationOffset: {type: 'vec3'},
  52847. armModel: {default: true}
  52848. },
  52849. /**
  52850. * Button IDs:
  52851. * 0 - trackpad
  52852. * 1 - trigger
  52853. */
  52854. mapping: {
  52855. axes: {trackpad: [0, 1]},
  52856. buttons: ['trackpad', 'trigger']
  52857. },
  52858. bindMethods: function () {
  52859. this.onModelLoaded = bind(this.onModelLoaded, this);
  52860. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52861. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52862. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  52863. this.onAxisMoved = bind(this.onAxisMoved, this);
  52864. },
  52865. init: function () {
  52866. var self = this;
  52867. this.onButtonChanged = bind(this.onButtonChanged, this);
  52868. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52869. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52870. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52871. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52872. this.controllerPresent = false;
  52873. this.lastControllerCheck = 0;
  52874. this.bindMethods();
  52875. },
  52876. addEventListeners: function () {
  52877. var el = this.el;
  52878. el.addEventListener('buttonchanged', this.onButtonChanged);
  52879. el.addEventListener('buttondown', this.onButtonDown);
  52880. el.addEventListener('buttonup', this.onButtonUp);
  52881. el.addEventListener('touchstart', this.onButtonTouchStart);
  52882. el.addEventListener('touchend', this.onButtonTouchEnd);
  52883. el.addEventListener('model-loaded', this.onModelLoaded);
  52884. el.addEventListener('axismove', this.onAxisMoved);
  52885. this.controllerEventsActive = true;
  52886. this.addControllersUpdateListener();
  52887. },
  52888. removeEventListeners: function () {
  52889. var el = this.el;
  52890. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52891. el.removeEventListener('buttondown', this.onButtonDown);
  52892. el.removeEventListener('buttonup', this.onButtonUp);
  52893. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52894. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52895. el.removeEventListener('model-loaded', this.onModelLoaded);
  52896. el.removeEventListener('axismove', this.onAxisMoved);
  52897. this.controllerEventsActive = false;
  52898. this.removeControllersUpdateListener();
  52899. },
  52900. checkIfControllerPresent: function () {
  52901. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  52902. this.data.hand ? {hand: this.data.hand} : {});
  52903. },
  52904. play: function () {
  52905. this.checkIfControllerPresent();
  52906. this.addControllersUpdateListener();
  52907. },
  52908. pause: function () {
  52909. this.removeEventListeners();
  52910. this.removeControllersUpdateListener();
  52911. },
  52912. injectTrackedControls: function () {
  52913. var el = this.el;
  52914. var data = this.data;
  52915. el.setAttribute('tracked-controls', {
  52916. armModel: data.armModel,
  52917. idPrefix: GAMEPAD_ID_PREFIX,
  52918. orientationOffset: data.orientationOffset
  52919. });
  52920. if (!this.data.model) { return; }
  52921. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  52922. },
  52923. addControllersUpdateListener: function () {
  52924. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52925. },
  52926. removeControllersUpdateListener: function () {
  52927. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52928. },
  52929. onControllersUpdate: function () {
  52930. this.checkIfControllerPresent();
  52931. },
  52932. onModelLoaded: function (evt) {
  52933. var controllerObject3D = evt.detail.model;
  52934. var buttonMeshes;
  52935. if (!this.data.model) { return; }
  52936. buttonMeshes = this.buttonMeshes = {};
  52937. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  52938. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  52939. if (buttonMeshes.triggerPressed) {
  52940. buttonMeshes.triggerPressed.visible = false;
  52941. }
  52942. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  52943. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  52944. if (buttonMeshes.trackpadPressed) {
  52945. buttonMeshes.trackpadPressed.visible = false;
  52946. }
  52947. },
  52948. // No analog buttons, only emits 0/1 values
  52949. onButtonChanged: function (evt) {
  52950. var button = this.mapping.buttons[evt.detail.id];
  52951. if (!button) return;
  52952. // Pass along changed event with button state, using button mapping for convenience.
  52953. this.el.emit(button + 'changed', evt.detail.state);
  52954. },
  52955. onAxisMoved: function (evt) {
  52956. emitIfAxesChanged(this, this.mapping.axes, evt);
  52957. },
  52958. updateModel: function (buttonName, evtName) {
  52959. if (!this.data.model) { return; }
  52960. this.updateButtonModel(buttonName, evtName);
  52961. },
  52962. updateButtonModel: function (buttonName, state) {
  52963. var buttonMeshes = this.buttonMeshes;
  52964. var pressedName = buttonName + 'Pressed';
  52965. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  52966. return;
  52967. }
  52968. var color;
  52969. switch (state) {
  52970. case 'down':
  52971. color = this.data.buttonHighlightColor;
  52972. break;
  52973. case 'touchstart':
  52974. color = this.data.buttonTouchedColor;
  52975. break;
  52976. }
  52977. if (color) {
  52978. buttonMeshes[pressedName].material.color.set(color);
  52979. }
  52980. buttonMeshes[pressedName].visible = !!color;
  52981. buttonMeshes[buttonName].visible = !color;
  52982. }
  52983. });
  52984. },{"../core/component":135,"../utils/bind":204,"../utils/tracked-controls":219}],125:[function(require,module,exports){
  52985. var KEYCODE_TO_CODE = require('../constants').keyboardevent.KEYCODE_TO_CODE;
  52986. var registerComponent = require('../core/component').registerComponent;
  52987. var THREE = require('../lib/three');
  52988. var utils = require('../utils/');
  52989. var bind = utils.bind;
  52990. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  52991. var CLAMP_VELOCITY = 0.00001;
  52992. var MAX_DELTA = 0.2;
  52993. var KEYS = [
  52994. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  52995. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  52996. ];
  52997. /**
  52998. * WASD component to control entities using WASD keys.
  52999. */
  53000. module.exports.Component = registerComponent('wasd-controls', {
  53001. schema: {
  53002. acceleration: {default: 65},
  53003. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  53004. adEnabled: {default: true},
  53005. adInverted: {default: false},
  53006. enabled: {default: true},
  53007. fly: {default: false},
  53008. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  53009. wsEnabled: {default: true},
  53010. wsInverted: {default: false}
  53011. },
  53012. init: function () {
  53013. // To keep track of the pressed keys.
  53014. this.keys = {};
  53015. this.easing = 1.1;
  53016. this.velocity = new THREE.Vector3();
  53017. // Bind methods and add event listeners.
  53018. this.onBlur = bind(this.onBlur, this);
  53019. this.onContextMenu = bind(this.onContextMenu, this);
  53020. this.onFocus = bind(this.onFocus, this);
  53021. this.onKeyDown = bind(this.onKeyDown, this);
  53022. this.onKeyUp = bind(this.onKeyUp, this);
  53023. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  53024. this.attachVisibilityEventListeners();
  53025. },
  53026. tick: function (time, delta) {
  53027. var data = this.data;
  53028. var el = this.el;
  53029. var velocity = this.velocity;
  53030. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  53031. isEmptyObject(this.keys)) { return; }
  53032. // Update velocity.
  53033. delta = delta / 1000;
  53034. this.updateVelocity(delta);
  53035. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  53036. // Get movement vector and translate position.
  53037. el.object3D.position.add(this.getMovementVector(delta));
  53038. },
  53039. remove: function () {
  53040. this.removeKeyEventListeners();
  53041. this.removeVisibilityEventListeners();
  53042. },
  53043. play: function () {
  53044. this.attachKeyEventListeners();
  53045. },
  53046. pause: function () {
  53047. this.keys = {};
  53048. this.removeKeyEventListeners();
  53049. },
  53050. updateVelocity: function (delta) {
  53051. var acceleration;
  53052. var adAxis;
  53053. var adSign;
  53054. var data = this.data;
  53055. var keys = this.keys;
  53056. var velocity = this.velocity;
  53057. var wsAxis;
  53058. var wsSign;
  53059. adAxis = data.adAxis;
  53060. wsAxis = data.wsAxis;
  53061. // If FPS too low, reset velocity.
  53062. if (delta > MAX_DELTA) {
  53063. velocity[adAxis] = 0;
  53064. velocity[wsAxis] = 0;
  53065. return;
  53066. }
  53067. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  53068. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  53069. // Velocity Easing.
  53070. if (velocity[adAxis] !== 0) {
  53071. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  53072. }
  53073. if (velocity[wsAxis] !== 0) {
  53074. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  53075. }
  53076. // Clamp velocity easing.
  53077. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  53078. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  53079. if (!data.enabled) { return; }
  53080. // Update velocity using keys pressed.
  53081. acceleration = data.acceleration;
  53082. if (data.adEnabled) {
  53083. adSign = data.adInverted ? -1 : 1;
  53084. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  53085. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  53086. }
  53087. if (data.wsEnabled) {
  53088. wsSign = data.wsInverted ? -1 : 1;
  53089. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  53090. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  53091. }
  53092. },
  53093. getMovementVector: (function () {
  53094. var directionVector = new THREE.Vector3(0, 0, 0);
  53095. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  53096. return function (delta) {
  53097. var rotation = this.el.getAttribute('rotation');
  53098. var velocity = this.velocity;
  53099. var xRotation;
  53100. directionVector.copy(velocity);
  53101. directionVector.multiplyScalar(delta);
  53102. // Absolute.
  53103. if (!rotation) { return directionVector; }
  53104. xRotation = this.data.fly ? rotation.x : 0;
  53105. // Transform direction relative to heading.
  53106. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  53107. directionVector.applyEuler(rotationEuler);
  53108. return directionVector;
  53109. };
  53110. })(),
  53111. attachVisibilityEventListeners: function () {
  53112. window.oncontextmenu = this.onContextMenu;
  53113. window.addEventListener('blur', this.onBlur);
  53114. window.addEventListener('focus', this.onFocus);
  53115. document.addEventListener('visibilitychange', this.onVisibilityChange);
  53116. },
  53117. removeVisibilityEventListeners: function () {
  53118. window.removeEventListener('blur', this.onBlur);
  53119. window.removeEventListener('focus', this.onFocus);
  53120. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  53121. },
  53122. attachKeyEventListeners: function () {
  53123. window.addEventListener('keydown', this.onKeyDown);
  53124. window.addEventListener('keyup', this.onKeyUp);
  53125. },
  53126. removeKeyEventListeners: function () {
  53127. window.removeEventListener('keydown', this.onKeyDown);
  53128. window.removeEventListener('keyup', this.onKeyUp);
  53129. },
  53130. onContextMenu: function () {
  53131. var keys = Object.keys(this.keys);
  53132. for (var i = 0; i < keys.length; i++) {
  53133. delete this.keys[keys[i]];
  53134. }
  53135. },
  53136. onBlur: function () {
  53137. this.pause();
  53138. },
  53139. onFocus: function () {
  53140. this.play();
  53141. },
  53142. onVisibilityChange: function () {
  53143. if (document.hidden) {
  53144. this.onBlur();
  53145. } else {
  53146. this.onFocus();
  53147. }
  53148. },
  53149. onKeyDown: function (event) {
  53150. var code;
  53151. if (!shouldCaptureKeyEvent(event)) { return; }
  53152. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53153. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  53154. },
  53155. onKeyUp: function (event) {
  53156. var code;
  53157. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53158. delete this.keys[code];
  53159. }
  53160. });
  53161. function isEmptyObject (keys) {
  53162. var key;
  53163. for (key in keys) { return false; }
  53164. return true;
  53165. }
  53166. },{"../constants":127,"../core/component":135,"../lib/three":183,"../utils/":210}],126:[function(require,module,exports){
  53167. /* global THREE */
  53168. var registerComponent = require('../core/component').registerComponent;
  53169. var bind = require('../utils/bind');
  53170. var trackedControlsUtils = require('../utils/tracked-controls');
  53171. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53172. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53173. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53174. var utils = require('../utils/');
  53175. var debug = utils.debug('components:windows-motion-controls:debug');
  53176. var warn = utils.debug('components:windows-motion-controls:warn');
  53177. var DEFAULT_HANDEDNESS = require('../constants').DEFAULT_HANDEDNESS;
  53178. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  53179. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  53180. var isWebXRAvailable = require('../utils/').device.isWebXRAvailable;
  53181. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  53182. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  53183. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  53184. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53185. var INPUT_MAPPING_WEBVR = {
  53186. // A-Frame specific semantic axis names
  53187. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  53188. // A-Frame specific semantic button names
  53189. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  53190. // A mapping of the semantic name to node name in the glTF model file,
  53191. // that should be transformed by axis value.
  53192. // This array mirrors the browser Gamepad.axes array, such that
  53193. // the mesh corresponding to axis 0 is in this array index 0.
  53194. axisMeshNames: [
  53195. 'THUMBSTICK_X',
  53196. 'THUMBSTICK_Y',
  53197. 'TOUCHPAD_TOUCH_X',
  53198. 'TOUCHPAD_TOUCH_Y'
  53199. ],
  53200. // A mapping of the semantic name to button node name in the glTF model file,
  53201. // that should be transformed by button value.
  53202. buttonMeshNames: {
  53203. 'trigger': 'SELECT',
  53204. 'menu': 'MENU',
  53205. 'grip': 'GRASP',
  53206. 'thumbstick': 'THUMBSTICK_PRESS',
  53207. 'trackpad': 'TOUCHPAD_PRESS'
  53208. },
  53209. pointingPoseMeshName: 'POINTING_POSE'
  53210. };
  53211. var INPUT_MAPPING_WEBXR = {
  53212. // A-Frame specific semantic axis names
  53213. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  53214. // A-Frame specific semantic button names
  53215. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  53216. // A mapping of the semantic name to node name in the glTF model file,
  53217. // that should be transformed by axis value.
  53218. // This array mirrors the browser Gamepad.axes array, such that
  53219. // the mesh corresponding to axis 0 is in this array index 0.
  53220. axisMeshNames: [
  53221. 'TOUCHPAD_TOUCH_X',
  53222. 'TOUCHPAD_TOUCH_X',
  53223. 'THUMBSTICK_X',
  53224. 'THUMBSTICK_Y'
  53225. ],
  53226. // A mapping of the semantic name to button node name in the glTF model file,
  53227. // that should be transformed by button value.
  53228. buttonMeshNames: {
  53229. 'trigger': 'SELECT',
  53230. 'menu': 'MENU',
  53231. 'squeeze': 'GRASP',
  53232. 'thumbstick': 'THUMBSTICK_PRESS',
  53233. 'touchpad': 'TOUCHPAD_PRESS'
  53234. },
  53235. pointingPoseMeshName: 'POINTING_POSE'
  53236. };
  53237. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53238. /**
  53239. * Windows Motion Controller controls.
  53240. * Interface with Windows Motion Controller controllers and map Gamepad events to
  53241. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  53242. * Load a controller model and transform the pressed buttons.
  53243. */
  53244. module.exports.Component = registerComponent('windows-motion-controls', {
  53245. schema: {
  53246. hand: {default: DEFAULT_HANDEDNESS},
  53247. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  53248. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  53249. pair: {default: 0},
  53250. // If true, loads the controller glTF asset.
  53251. model: {default: true},
  53252. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  53253. hideDisconnected: {default: true}
  53254. },
  53255. mapping: INPUT_MAPPING,
  53256. bindMethods: function () {
  53257. this.onModelError = bind(this.onModelError, this);
  53258. this.onModelLoaded = bind(this.onModelLoaded, this);
  53259. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53260. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53261. this.onAxisMoved = bind(this.onAxisMoved, this);
  53262. },
  53263. init: function () {
  53264. var self = this;
  53265. var el = this.el;
  53266. this.onButtonChanged = bind(this.onButtonChanged, this);
  53267. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53268. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53269. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53270. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53271. this.onControllerConnected = function () { self.setModelVisibility(true); };
  53272. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  53273. this.controllerPresent = false;
  53274. this.lastControllerCheck = 0;
  53275. this.previousButtonValues = {};
  53276. this.bindMethods();
  53277. // Cache for submeshes that we have looked up by name.
  53278. this.loadedMeshInfo = {
  53279. buttonMeshes: null,
  53280. axisMeshes: null
  53281. };
  53282. // Pointing poses
  53283. this.rayOrigin = {
  53284. origin: new THREE.Vector3(),
  53285. direction: new THREE.Vector3(0, 0, -1),
  53286. createdFromMesh: false
  53287. };
  53288. el.addEventListener('controllerconnected', this.onControllerConnected);
  53289. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  53290. },
  53291. addEventListeners: function () {
  53292. var el = this.el;
  53293. el.addEventListener('buttonchanged', this.onButtonChanged);
  53294. el.addEventListener('buttondown', this.onButtonDown);
  53295. el.addEventListener('buttonup', this.onButtonUp);
  53296. el.addEventListener('touchstart', this.onButtonTouchStart);
  53297. el.addEventListener('touchend', this.onButtonTouchEnd);
  53298. el.addEventListener('axismove', this.onAxisMoved);
  53299. el.addEventListener('model-error', this.onModelError);
  53300. el.addEventListener('model-loaded', this.onModelLoaded);
  53301. this.controllerEventsActive = true;
  53302. },
  53303. removeEventListeners: function () {
  53304. var el = this.el;
  53305. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53306. el.removeEventListener('buttondown', this.onButtonDown);
  53307. el.removeEventListener('buttonup', this.onButtonUp);
  53308. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53309. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53310. el.removeEventListener('axismove', this.onAxisMoved);
  53311. el.removeEventListener('model-error', this.onModelError);
  53312. el.removeEventListener('model-loaded', this.onModelLoaded);
  53313. this.controllerEventsActive = false;
  53314. },
  53315. checkIfControllerPresent: function () {
  53316. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  53317. hand: this.data.hand,
  53318. index: this.data.pair,
  53319. iterateControllerProfiles: true
  53320. });
  53321. },
  53322. play: function () {
  53323. this.checkIfControllerPresent();
  53324. this.addControllersUpdateListener();
  53325. },
  53326. pause: function () {
  53327. this.removeEventListeners();
  53328. this.removeControllersUpdateListener();
  53329. },
  53330. updateControllerModel: function () {
  53331. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  53332. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  53333. this.modelReady();
  53334. return;
  53335. }
  53336. var sourceUrl = this.createControllerModelUrl();
  53337. this.loadModel(sourceUrl);
  53338. },
  53339. /**
  53340. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  53341. * art assets.
  53342. */
  53343. createControllerModelUrl: function (forceDefault) {
  53344. // Determine the device specific folder based on the ID suffix
  53345. var trackedControlsComponent = this.el.components['tracked-controls'];
  53346. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  53347. var device = 'default';
  53348. var hand = this.data.hand;
  53349. var filename;
  53350. if (controller && !window.hasNativeWebXRImplementation) {
  53351. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  53352. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  53353. // In this case, we want to load the universal model, so need to get the '' from the controller.
  53354. hand = controller.hand;
  53355. if (!forceDefault) {
  53356. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  53357. device = ((match && match[0]) || device);
  53358. }
  53359. }
  53360. // Hand
  53361. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  53362. // Final url
  53363. return MODEL_BASE_URL + device + '/' + filename;
  53364. },
  53365. injectTrackedControls: function () {
  53366. var data = this.data;
  53367. this.el.setAttribute('tracked-controls', {
  53368. idPrefix: GAMEPAD_ID_PREFIX,
  53369. controller: data.pair,
  53370. hand: data.hand,
  53371. armModel: false
  53372. });
  53373. this.updateControllerModel();
  53374. },
  53375. addControllersUpdateListener: function () {
  53376. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53377. },
  53378. removeControllersUpdateListener: function () {
  53379. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53380. },
  53381. onControllersUpdate: function () {
  53382. this.checkIfControllerPresent();
  53383. },
  53384. onModelError: function (evt) {
  53385. var defaultUrl = this.createControllerModelUrl(true);
  53386. if (evt.detail.src !== defaultUrl) {
  53387. warn('Failed to load controller model for device, attempting to load default.');
  53388. this.loadModel(defaultUrl);
  53389. } else {
  53390. warn('Failed to load default controller model.');
  53391. }
  53392. },
  53393. loadModel: function (url) {
  53394. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  53395. // removed and re-loaded if the given url changes.
  53396. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  53397. },
  53398. onModelLoaded: function (evt) {
  53399. var rootNode = this.controllerModel = evt.detail.model;
  53400. var loadedMeshInfo = this.loadedMeshInfo;
  53401. var i;
  53402. var meshName;
  53403. var mesh;
  53404. var meshInfo;
  53405. debug('Processing model');
  53406. // Reset the caches
  53407. loadedMeshInfo.buttonMeshes = {};
  53408. loadedMeshInfo.axisMeshes = {};
  53409. // Cache our meshes so we aren't traversing the hierarchy per frame
  53410. if (rootNode) {
  53411. // Button Meshes
  53412. for (i = 0; i < this.mapping.buttons.length; i++) {
  53413. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  53414. if (!meshName) {
  53415. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  53416. continue;
  53417. }
  53418. mesh = rootNode.getObjectByName(meshName);
  53419. if (!mesh) {
  53420. warn('Missing button mesh with name: ' + meshName);
  53421. continue;
  53422. }
  53423. meshInfo = {
  53424. index: i,
  53425. value: getImmediateChildByName(mesh, 'VALUE'),
  53426. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  53427. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  53428. };
  53429. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  53430. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  53431. } else {
  53432. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  53433. warn('Missing button submesh under mesh with name: ' + meshName +
  53434. '(VALUE: ' + !!meshInfo.value +
  53435. ', PRESSED: ' + !!meshInfo.pressed +
  53436. ', UNPRESSED:' + !!meshInfo.unpressed +
  53437. ')');
  53438. }
  53439. }
  53440. // Axis Meshes
  53441. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  53442. meshName = this.mapping.axisMeshNames[i];
  53443. if (!meshName) {
  53444. debug('Skipping unknown axis at index: ' + i);
  53445. continue;
  53446. }
  53447. mesh = rootNode.getObjectByName(meshName);
  53448. if (!mesh) {
  53449. warn('Missing axis mesh with name: ' + meshName);
  53450. continue;
  53451. }
  53452. meshInfo = {
  53453. index: i,
  53454. value: getImmediateChildByName(mesh, 'VALUE'),
  53455. min: getImmediateChildByName(mesh, 'MIN'),
  53456. max: getImmediateChildByName(mesh, 'MAX')
  53457. };
  53458. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  53459. loadedMeshInfo.axisMeshes[i] = meshInfo;
  53460. } else {
  53461. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  53462. warn('Missing axis submesh under mesh with name: ' + meshName +
  53463. '(VALUE: ' + !!meshInfo.value +
  53464. ', MIN: ' + !!meshInfo.min +
  53465. ', MAX:' + !!meshInfo.max +
  53466. ')');
  53467. }
  53468. }
  53469. this.calculateRayOriginFromMesh(rootNode);
  53470. // Determine if the model has to be visible or not.
  53471. this.setModelVisibility();
  53472. }
  53473. debug('Model load complete.');
  53474. // Look through only immediate children. This will return null if no mesh exists with the given name.
  53475. function getImmediateChildByName (object3d, value) {
  53476. for (var i = 0, l = object3d.children.length; i < l; i++) {
  53477. var obj = object3d.children[i];
  53478. if (obj && obj['name'] === value) {
  53479. return obj;
  53480. }
  53481. }
  53482. return undefined;
  53483. }
  53484. },
  53485. calculateRayOriginFromMesh: (function () {
  53486. var quaternion = new THREE.Quaternion();
  53487. return function (rootNode) {
  53488. var mesh;
  53489. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  53490. // in the glTF (assumes that root node is at world origin)
  53491. this.rayOrigin.origin.set(0, 0, 0);
  53492. this.rayOrigin.direction.set(0, 0, -1);
  53493. this.rayOrigin.createdFromMesh = true;
  53494. // Try to read Pointing pose from the source model
  53495. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  53496. if (mesh) {
  53497. var parent = rootNode.parent;
  53498. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  53499. if (parent) {
  53500. rootNode.parent = null;
  53501. rootNode.updateMatrixWorld(true);
  53502. rootNode.parent = parent;
  53503. }
  53504. mesh.getWorldPosition(this.rayOrigin.origin);
  53505. mesh.getWorldQuaternion(quaternion);
  53506. this.rayOrigin.direction.applyQuaternion(quaternion);
  53507. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  53508. if (parent) {
  53509. rootNode.updateMatrixWorld(true);
  53510. }
  53511. } else {
  53512. debug('Mesh does not contain pointing origin data, defaulting to none.');
  53513. }
  53514. // Emit event stating that our pointing ray is now accurate.
  53515. this.modelReady();
  53516. };
  53517. })(),
  53518. lerpAxisTransform: (function () {
  53519. var quaternion = new THREE.Quaternion();
  53520. return function (axis, axisValue) {
  53521. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  53522. if (!axisMeshInfo) return;
  53523. var min = axisMeshInfo.min;
  53524. var max = axisMeshInfo.max;
  53525. var target = axisMeshInfo.value;
  53526. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  53527. var lerpValue = axisValue * 0.5 + 0.5;
  53528. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  53529. target.position.lerpVectors(min.position, max.position, lerpValue);
  53530. };
  53531. })(),
  53532. lerpButtonTransform: (function () {
  53533. var quaternion = new THREE.Quaternion();
  53534. return function (buttonName, buttonValue) {
  53535. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  53536. if (!buttonMeshInfo) return;
  53537. var min = buttonMeshInfo.unpressed;
  53538. var max = buttonMeshInfo.pressed;
  53539. var target = buttonMeshInfo.value;
  53540. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  53541. target.position.lerpVectors(min.position, max.position, buttonValue);
  53542. };
  53543. })(),
  53544. modelReady: function () {
  53545. this.el.emit('controllermodelready', {
  53546. name: 'windows-motion-controls',
  53547. model: this.data.model,
  53548. rayOrigin: this.rayOrigin
  53549. });
  53550. },
  53551. onButtonChanged: function (evt) {
  53552. var buttonName = this.mapping.buttons[evt.detail.id];
  53553. if (buttonName) {
  53554. // Update the button mesh transform
  53555. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  53556. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  53557. }
  53558. // Only emit events for buttons that we know how to map from index to name
  53559. this.el.emit(buttonName + 'changed', evt.detail.state);
  53560. }
  53561. },
  53562. onAxisMoved: function (evt) {
  53563. var numAxes = this.mapping.axisMeshNames.length;
  53564. // Only attempt to update meshes if we have valid data.
  53565. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  53566. for (var axis = 0; axis < numAxes; axis++) {
  53567. // Update the button mesh transform
  53568. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  53569. }
  53570. }
  53571. emitIfAxesChanged(this, this.mapping.axes, evt);
  53572. },
  53573. setModelVisibility: function (visible) {
  53574. var model = this.el.getObject3D('mesh');
  53575. visible = visible !== undefined ? visible : this.modelVisible;
  53576. this.modelVisible = visible;
  53577. if (!model) { return; }
  53578. model.visible = visible;
  53579. }
  53580. });
  53581. },{"../constants":127,"../core/component":135,"../utils/":210,"../utils/bind":204,"../utils/tracked-controls":219}],127:[function(require,module,exports){
  53582. module.exports = {
  53583. AFRAME_INJECTED: 'aframe-injected',
  53584. DEFAULT_CAMERA_HEIGHT: 1.6,
  53585. DEFAULT_HANDEDNESS: 'right',
  53586. keyboardevent: require('./keyboardevent')
  53587. };
  53588. },{"./keyboardevent":128}],128:[function(require,module,exports){
  53589. module.exports = {
  53590. // Tiny KeyboardEvent.code polyfill.
  53591. KEYCODE_TO_CODE: {
  53592. '38': 'ArrowUp',
  53593. '37': 'ArrowLeft',
  53594. '40': 'ArrowDown',
  53595. '39': 'ArrowRight',
  53596. '87': 'KeyW',
  53597. '65': 'KeyA',
  53598. '83': 'KeyS',
  53599. '68': 'KeyD'
  53600. }
  53601. };
  53602. },{}],129:[function(require,module,exports){
  53603. var ANode = require('./a-node');
  53604. var bind = require('../utils/bind');
  53605. var debug = require('../utils/debug');
  53606. var registerElement = require('./a-register-element').registerElement;
  53607. var THREE = require('../lib/three');
  53608. var fileLoader = new THREE.FileLoader();
  53609. var warn = debug('core:a-assets:warn');
  53610. /**
  53611. * Asset management system. Handles blocking on asset loading.
  53612. */
  53613. module.exports = registerElement('a-assets', {
  53614. prototype: Object.create(ANode.prototype, {
  53615. createdCallback: {
  53616. value: function () {
  53617. this.isAssets = true;
  53618. this.fileLoader = fileLoader;
  53619. this.timeout = null;
  53620. }
  53621. },
  53622. attachedCallback: {
  53623. value: function () {
  53624. var self = this;
  53625. var i;
  53626. var loaded = [];
  53627. var mediaEl;
  53628. var mediaEls;
  53629. var imgEl;
  53630. var imgEls;
  53631. var timeout;
  53632. if (!this.parentNode.isScene) {
  53633. throw new Error('<a-assets> must be a child of a <a-scene>.');
  53634. }
  53635. // Wait for <img>s.
  53636. imgEls = this.querySelectorAll('img');
  53637. for (i = 0; i < imgEls.length; i++) {
  53638. imgEl = fixUpMediaElement(imgEls[i]);
  53639. loaded.push(new Promise(function (resolve, reject) {
  53640. // Set in cache because we won't be needing to call three.js loader if we have.
  53641. // a loaded media element.
  53642. THREE.Cache.add(imgEls[i].getAttribute('src'), imgEl);
  53643. imgEl.onload = resolve;
  53644. imgEl.onerror = reject;
  53645. }));
  53646. }
  53647. // Wait for <audio>s and <video>s.
  53648. mediaEls = this.querySelectorAll('audio, video');
  53649. for (i = 0; i < mediaEls.length; i++) {
  53650. mediaEl = fixUpMediaElement(mediaEls[i]);
  53651. if (!mediaEl.src && !mediaEl.srcObject) {
  53652. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  53653. }
  53654. loaded.push(mediaElementLoaded(mediaEl));
  53655. }
  53656. // Trigger loaded for scene to start rendering.
  53657. Promise.all(loaded).then(bind(this.load, this));
  53658. // Timeout to start loading anyways.
  53659. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  53660. this.timeout = setTimeout(function () {
  53661. if (self.hasLoaded) { return; }
  53662. warn('Asset loading timed out in ', timeout, 'ms');
  53663. self.emit('timeout');
  53664. self.load();
  53665. }, timeout);
  53666. }
  53667. },
  53668. detachedCallback: {
  53669. value: function () {
  53670. if (this.timeout) { clearTimeout(this.timeout); }
  53671. }
  53672. },
  53673. load: {
  53674. value: function () {
  53675. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  53676. return el.isAssetItem && el.hasAttribute('src');
  53677. });
  53678. }
  53679. }
  53680. })
  53681. });
  53682. /**
  53683. * Preload using XHRLoader for any type of asset.
  53684. */
  53685. registerElement('a-asset-item', {
  53686. prototype: Object.create(ANode.prototype, {
  53687. createdCallback: {
  53688. value: function () {
  53689. this.data = null;
  53690. this.isAssetItem = true;
  53691. }
  53692. },
  53693. attachedCallback: {
  53694. value: function () {
  53695. var self = this;
  53696. var src = this.getAttribute('src');
  53697. fileLoader.setResponseType(
  53698. this.getAttribute('response-type') || inferResponseType(src));
  53699. fileLoader.load(src, function handleOnLoad (response) {
  53700. self.data = response;
  53701. /*
  53702. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  53703. previous one closes, the second request never finishes.
  53704. setTimeout finishes the first request and lets the logic triggered by load open
  53705. subsequent requests.
  53706. setTimeout can be removed once the fix for the bug below ships:
  53707. 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
  53708. */
  53709. setTimeout(function load () { ANode.prototype.load.call(self); });
  53710. }, function handleOnProgress (xhr) {
  53711. self.emit('progress', {
  53712. loadedBytes: xhr.loaded,
  53713. totalBytes: xhr.total,
  53714. xhr: xhr
  53715. });
  53716. }, function handleOnError (xhr) {
  53717. self.emit('error', {xhr: xhr});
  53718. });
  53719. }
  53720. }
  53721. })
  53722. });
  53723. /**
  53724. * Create a Promise that resolves once the media element has finished buffering.
  53725. *
  53726. * @param {Element} el - HTMLMediaElement.
  53727. * @returns {Promise}
  53728. */
  53729. function mediaElementLoaded (el) {
  53730. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  53731. return;
  53732. }
  53733. // If media specifies autoplay or preload, wait until media is completely buffered.
  53734. return new Promise(function (resolve, reject) {
  53735. if (el.readyState === 4) { return resolve(); } // Already loaded.
  53736. if (el.error) { return reject(); } // Error.
  53737. el.addEventListener('loadeddata', checkProgress, false);
  53738. el.addEventListener('progress', checkProgress, false);
  53739. el.addEventListener('error', reject, false);
  53740. function checkProgress () {
  53741. // Add up the seconds buffered.
  53742. var secondsBuffered = 0;
  53743. for (var i = 0; i < el.buffered.length; i++) {
  53744. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  53745. }
  53746. // Compare seconds buffered to media duration.
  53747. if (secondsBuffered >= el.duration) {
  53748. // Set in cache because we won't be needing to call three.js loader if we have.
  53749. // a loaded media element.
  53750. // Store video elements only. three.js loader is used for audio elements.
  53751. // See assetParse too.
  53752. if (el.tagName === 'VIDEO') {
  53753. THREE.Cache.add(el.getAttribute('src'), el);
  53754. }
  53755. resolve();
  53756. }
  53757. }
  53758. });
  53759. }
  53760. /**
  53761. * Automatically add attributes to media elements where convenient.
  53762. * crossorigin, playsinline.
  53763. */
  53764. function fixUpMediaElement (mediaEl) {
  53765. // Cross-origin.
  53766. var newMediaEl = setCrossOrigin(mediaEl);
  53767. // Plays inline for mobile.
  53768. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  53769. newMediaEl.setAttribute('playsinline', '');
  53770. newMediaEl.setAttribute('webkit-playsinline', '');
  53771. }
  53772. if (newMediaEl !== mediaEl) {
  53773. mediaEl.parentNode.appendChild(newMediaEl);
  53774. mediaEl.parentNode.removeChild(mediaEl);
  53775. }
  53776. return newMediaEl;
  53777. }
  53778. /**
  53779. * Automatically set `crossorigin` if not defined on the media element.
  53780. * If it is not defined, we must create and re-append a new media element <img> and
  53781. * have the browser re-request it with `crossorigin` set.
  53782. *
  53783. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  53784. * @returns {Element} Media element to be used to listen to for loaded events.
  53785. */
  53786. function setCrossOrigin (mediaEl) {
  53787. var newMediaEl;
  53788. var src;
  53789. // Already has crossorigin set.
  53790. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  53791. src = mediaEl.getAttribute('src');
  53792. if (src !== null) {
  53793. // Does not have protocol.
  53794. if (src.indexOf('://') === -1) { return mediaEl; }
  53795. // Determine if cross origin is actually needed.
  53796. if (extractDomain(src) === window.location.host) { return mediaEl; }
  53797. }
  53798. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  53799. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  53800. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  53801. mediaEl.crossOrigin = 'anonymous';
  53802. newMediaEl = mediaEl.cloneNode(true);
  53803. return newMediaEl;
  53804. }
  53805. /**
  53806. * Extract domain out of URL.
  53807. *
  53808. * @param {string} url
  53809. * @returns {string}
  53810. */
  53811. function extractDomain (url) {
  53812. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  53813. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  53814. // Find and remove port number.
  53815. return domain.substring(0, domain.indexOf(':'));
  53816. }
  53817. /**
  53818. * Infer response-type attribute from src.
  53819. * Default is text (default XMLHttpRequest.responseType)
  53820. * and arraybuffer for .glb files.
  53821. *
  53822. * @param {string} src
  53823. * @returns {string}
  53824. */
  53825. function inferResponseType (src) {
  53826. var fileName = getFileNameFromURL(src);
  53827. var dotLastIndex = fileName.lastIndexOf('.');
  53828. if (dotLastIndex >= 0) {
  53829. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  53830. if (extension === '.glb') {
  53831. return 'arraybuffer';
  53832. }
  53833. }
  53834. return 'text';
  53835. }
  53836. module.exports.inferResponseType = inferResponseType;
  53837. /**
  53838. * Extract filename from URL
  53839. *
  53840. * @param {string} url
  53841. * @returns {string}
  53842. */
  53843. function getFileNameFromURL (url) {
  53844. var parser = document.createElement('a');
  53845. parser.href = url;
  53846. var query = parser.search.replace(/^\?/, '');
  53847. var filePath = url.replace(query, '').replace('?', '');
  53848. return filePath.substring(filePath.lastIndexOf('/') + 1);
  53849. }
  53850. module.exports.getFileNameFromURL = getFileNameFromURL;
  53851. },{"../lib/three":183,"../utils/bind":204,"../utils/debug":206,"./a-node":133,"./a-register-element":134}],130:[function(require,module,exports){
  53852. var debug = require('../utils/debug');
  53853. var registerElement = require('./a-register-element').registerElement;
  53854. var warn = debug('core:cubemap:warn');
  53855. /**
  53856. * Cubemap element that handles validation and exposes list of URLs.
  53857. * Does not listen to updates.
  53858. */
  53859. module.exports = registerElement('a-cubemap', {
  53860. prototype: Object.create(window.HTMLElement.prototype, {
  53861. /**
  53862. * Calculates this.srcs.
  53863. */
  53864. attachedCallback: {
  53865. value: function () {
  53866. this.srcs = this.validate();
  53867. },
  53868. writable: window.debug
  53869. },
  53870. /**
  53871. * Checks for exactly six elements with [src].
  53872. * Does not check explicitly for <img>s in case user does not want
  53873. * prefetching.
  53874. *
  53875. * @returns {Array|null} - six URLs if valid, else null.
  53876. */
  53877. validate: {
  53878. value: function () {
  53879. var elements = this.querySelectorAll('[src]');
  53880. var i;
  53881. var srcs = [];
  53882. if (elements.length === 6) {
  53883. for (i = 0; i < elements.length; i++) {
  53884. srcs.push(elements[i].getAttribute('src'));
  53885. }
  53886. return srcs;
  53887. }
  53888. // Else if there are not six elements, throw a warning.
  53889. warn(
  53890. '<a-cubemap> did not contain exactly six elements each with a ' +
  53891. '`src` attribute.');
  53892. },
  53893. writable: window.debug
  53894. }
  53895. })
  53896. });
  53897. },{"../utils/debug":206,"./a-register-element":134}],131:[function(require,module,exports){
  53898. var ANode = require('./a-node');
  53899. var COMPONENTS = require('./component').components;
  53900. var registerElement = require('./a-register-element').registerElement;
  53901. var THREE = require('../lib/three');
  53902. var utils = require('../utils/');
  53903. var AEntity;
  53904. var debug = utils.debug('core:a-entity:debug');
  53905. var warn = utils.debug('core:a-entity:warn');
  53906. var MULTIPLE_COMPONENT_DELIMITER = '__';
  53907. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  53908. var ONCE = {once: true};
  53909. /**
  53910. * Entity is a container object that components are plugged into to comprise everything in
  53911. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  53912. *
  53913. * To be able to take components, the scene element inherits from the entity definition.
  53914. *
  53915. * @member {object} components - entity's currently initialized components.
  53916. * @member {object} object3D - three.js object.
  53917. * @member {array} states
  53918. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  53919. */
  53920. var proto = Object.create(ANode.prototype, {
  53921. createdCallback: {
  53922. value: function () {
  53923. this.components = {};
  53924. // To avoid double initializations and infinite loops.
  53925. this.initializingComponents = {};
  53926. this.componentsToUpdate = {};
  53927. this.isEntity = true;
  53928. this.isPlaying = false;
  53929. this.object3D = new THREE.Group();
  53930. this.object3D.el = this;
  53931. this.object3DMap = {};
  53932. this.parentEl = null;
  53933. this.rotationObj = {};
  53934. this.states = [];
  53935. }
  53936. },
  53937. /**
  53938. * Handle changes coming from the browser DOM inspector.
  53939. */
  53940. attributeChangedCallback: {
  53941. value: function (attr, oldVal, newVal) {
  53942. var component = this.components[attr];
  53943. // If the empty string is passed by the component initialization
  53944. // logic we ignore the component update.
  53945. if (component && component.justInitialized && newVal === '') {
  53946. delete component.justInitialized;
  53947. return;
  53948. }
  53949. // When a component is removed after calling el.removeAttribute('material')
  53950. if (!component && newVal === null) { return; }
  53951. this.setEntityAttribute(attr, oldVal, newVal);
  53952. }
  53953. },
  53954. /**
  53955. * Add to parent, load, play.
  53956. */
  53957. attachedCallback: {
  53958. value: function () {
  53959. var assetsEl; // Asset management system element.
  53960. var sceneEl = this.sceneEl;
  53961. var self = this; // Component.
  53962. this.addToParent();
  53963. // Don't .load() scene on attachedCallback.
  53964. if (this.isScene) { return; }
  53965. // Gracefully not error when outside of <a-scene> (e.g., tests).
  53966. if (!sceneEl) {
  53967. this.load();
  53968. return;
  53969. }
  53970. // Wait for asset management system to finish before loading.
  53971. assetsEl = sceneEl.querySelector('a-assets');
  53972. if (assetsEl && !assetsEl.hasLoaded) {
  53973. assetsEl.addEventListener('loaded', function () { self.load(); });
  53974. return;
  53975. }
  53976. this.load();
  53977. }
  53978. },
  53979. /**
  53980. * Tell parent to remove this element's object3D from its object3D.
  53981. * Do not call on scene element because that will cause a call to document.body.remove().
  53982. */
  53983. detachedCallback: {
  53984. value: function () {
  53985. var componentName;
  53986. if (!this.parentEl) { return; }
  53987. // Remove components.
  53988. for (componentName in this.components) {
  53989. this.removeComponent(componentName, false);
  53990. }
  53991. if (this.isScene) { return; }
  53992. this.removeFromParent();
  53993. ANode.prototype.detachedCallback.call(this);
  53994. // Remove cyclic reference.
  53995. this.object3D.el = null;
  53996. }
  53997. },
  53998. getObject3D: {
  53999. value: function (type) {
  54000. return this.object3DMap[type];
  54001. }
  54002. },
  54003. /**
  54004. * Set a THREE.Object3D into the map.
  54005. *
  54006. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  54007. * @param {object} obj - A THREE.Object3D.
  54008. */
  54009. setObject3D: {
  54010. value: function (type, obj) {
  54011. var oldObj;
  54012. var self = this;
  54013. if (!(obj instanceof THREE.Object3D)) {
  54014. throw new Error(
  54015. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  54016. 'THREE.Object3D.'
  54017. );
  54018. }
  54019. // Remove existing object of the type.
  54020. oldObj = this.getObject3D(type);
  54021. if (oldObj) { this.object3D.remove(oldObj); }
  54022. // Set references to A-Frame entity.
  54023. obj.el = this;
  54024. if (obj.children.length) {
  54025. obj.traverse(function bindEl (child) {
  54026. child.el = self;
  54027. });
  54028. }
  54029. // Add.
  54030. this.object3D.add(obj);
  54031. this.object3DMap[type] = obj;
  54032. this.emit('object3dset', {object: obj, type: type});
  54033. }
  54034. },
  54035. /**
  54036. * Remove object from scene and entity object3D map.
  54037. */
  54038. removeObject3D: {
  54039. value: function (type) {
  54040. var obj = this.getObject3D(type);
  54041. if (!obj) {
  54042. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  54043. return;
  54044. }
  54045. this.object3D.remove(obj);
  54046. delete this.object3DMap[type];
  54047. this.emit('object3dremove', {type: type});
  54048. }
  54049. },
  54050. /**
  54051. * Gets or creates an object3D of a given type.
  54052. *
  54053. * @param {string} type - Type of the object3D.
  54054. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  54055. * @returns {object}
  54056. */
  54057. getOrCreateObject3D: {
  54058. value: function (type, Constructor) {
  54059. var object3D = this.getObject3D(type);
  54060. if (!object3D && Constructor) {
  54061. object3D = new Constructor();
  54062. this.setObject3D(type, object3D);
  54063. }
  54064. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  54065. 'and `object3dset` event instead.');
  54066. return object3D;
  54067. }
  54068. },
  54069. /**
  54070. * Add child entity.
  54071. *
  54072. * @param {Element} el - Child entity.
  54073. */
  54074. add: {
  54075. value: function (el) {
  54076. if (!el.object3D) {
  54077. throw new Error("Trying to add an element that doesn't have an `object3D`");
  54078. }
  54079. this.object3D.add(el.object3D);
  54080. this.emit('child-attached', {el: el});
  54081. }
  54082. },
  54083. /**
  54084. * Tell parentNode to add this entity to itself.
  54085. */
  54086. addToParent: {
  54087. value: function () {
  54088. var parentNode = this.parentEl = this.parentNode;
  54089. // `!parentNode` check primarily for unit tests.
  54090. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  54091. parentNode.add(this);
  54092. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  54093. }
  54094. },
  54095. /**
  54096. * Tell parentNode to remove this entity from itself.
  54097. */
  54098. removeFromParent: {
  54099. value: function () {
  54100. var parentEl = this.parentEl;
  54101. this.parentEl.remove(this);
  54102. this.attachedToParent = false;
  54103. this.parentEl = null;
  54104. parentEl.emit('child-detached', {el: this});
  54105. }
  54106. },
  54107. load: {
  54108. value: function () {
  54109. var self = this;
  54110. if (this.hasLoaded || !this.parentEl) { return; }
  54111. ANode.prototype.load.call(this, function entityLoadCallback () {
  54112. // Check if entity was detached while it was waiting to load.
  54113. if (!self.parentEl) { return; }
  54114. self.updateComponents();
  54115. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  54116. });
  54117. },
  54118. writable: window.debug
  54119. },
  54120. /**
  54121. * Remove child entity.
  54122. *
  54123. * @param {Element} el - Child entity.
  54124. */
  54125. remove: {
  54126. value: function (el) {
  54127. if (el) {
  54128. this.object3D.remove(el.object3D);
  54129. } else {
  54130. this.parentNode.removeChild(this);
  54131. }
  54132. }
  54133. },
  54134. /**
  54135. * @returns {array} Direct children that are entities.
  54136. */
  54137. getChildEntities: {
  54138. value: function () {
  54139. var children = this.children;
  54140. var childEntities = [];
  54141. for (var i = 0; i < children.length; i++) {
  54142. var child = children[i];
  54143. if (child instanceof AEntity) {
  54144. childEntities.push(child);
  54145. }
  54146. }
  54147. return childEntities;
  54148. }
  54149. },
  54150. /**
  54151. * Initialize component.
  54152. *
  54153. * @param {string} attrName - Attribute name asociated to the component.
  54154. * @param {object} data - Component data
  54155. * @param {boolean} isDependency - True if the component is a dependency.
  54156. */
  54157. initComponent: {
  54158. value: function (attrName, data, isDependency) {
  54159. var component;
  54160. var componentId;
  54161. var componentInfo;
  54162. var componentName;
  54163. var isComponentDefined;
  54164. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  54165. componentName = componentInfo[0];
  54166. componentId = componentInfo.length > 2
  54167. ? componentInfo.slice(1).join('__')
  54168. : componentInfo[1];
  54169. // Not a registered component.
  54170. if (!COMPONENTS[componentName]) { return; }
  54171. // Component is not a dependency and is undefined.
  54172. // If a component is a dependency, then it is okay to have no data.
  54173. isComponentDefined = checkComponentDefined(this, attrName) ||
  54174. data !== undefined;
  54175. if (!isComponentDefined && !isDependency) { return; }
  54176. // Component already initialized.
  54177. if (attrName in this.components) { return; }
  54178. // Initialize dependencies first
  54179. this.initComponentDependencies(componentName);
  54180. // If component name has an id we check component type multiplic
  54181. if (componentId && !COMPONENTS[componentName].multiple) {
  54182. throw new Error('Trying to initialize multiple ' +
  54183. 'components of type `' + componentName +
  54184. '`. There can only be one component of this type per entity.');
  54185. }
  54186. component = new COMPONENTS[componentName].Component(this, data, componentId);
  54187. if (this.isPlaying) { component.play(); }
  54188. // Components are reflected in the DOM as attributes but the state is not shown
  54189. // hence we set the attribute to empty string.
  54190. // The flag justInitialized is for attributeChangedCallback to not overwrite
  54191. // the component with the empty string.
  54192. if (!this.hasAttribute(attrName)) {
  54193. component.justInitialized = true;
  54194. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  54195. }
  54196. debug('Component initialized: %s', attrName);
  54197. },
  54198. writable: window.debug
  54199. },
  54200. /**
  54201. * Initialize dependencies of a component.
  54202. *
  54203. * @param {string} name - Root component name.
  54204. */
  54205. initComponentDependencies: {
  54206. value: function (name) {
  54207. var self = this;
  54208. var component = COMPONENTS[name];
  54209. var dependencies;
  54210. var i;
  54211. // Not a component.
  54212. if (!component) { return; }
  54213. // No dependencies.
  54214. dependencies = COMPONENTS[name].dependencies;
  54215. if (!dependencies) { return; }
  54216. // Initialize dependencies.
  54217. for (i = 0; i < dependencies.length; i++) {
  54218. // Call getAttribute to initialize the data from the DOM.
  54219. self.initComponent(
  54220. dependencies[i],
  54221. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  54222. true
  54223. );
  54224. }
  54225. }
  54226. },
  54227. removeComponent: {
  54228. value: function (name, destroy) {
  54229. var component;
  54230. component = this.components[name];
  54231. if (!component) { return; }
  54232. // Wait for component to initialize.
  54233. if (!component.initialized) {
  54234. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  54235. if (evt.detail.name !== name) { return; }
  54236. this.removeComponent(name, destroy);
  54237. this.removeEventListener('componentinitialized', tryRemoveLater);
  54238. });
  54239. return;
  54240. }
  54241. component.pause();
  54242. component.remove();
  54243. // Keep component attached to entity in case of just full entity detach.
  54244. if (destroy) {
  54245. component.destroy();
  54246. delete this.components[name];
  54247. }
  54248. this.emit('componentremoved', component.evtDetail, false);
  54249. },
  54250. writable: window.debug
  54251. },
  54252. /**
  54253. * Initialize or update all components.
  54254. * Build data using initial components, defined attributes, mixins, and defaults.
  54255. * Update default components before the rest.
  54256. *
  54257. * @member {function} getExtraComponents - Can be implemented to include component data
  54258. * from other sources (e.g., implemented by primitives).
  54259. */
  54260. updateComponents: {
  54261. value: function () {
  54262. var data;
  54263. var extraComponents;
  54264. var i;
  54265. var name;
  54266. var componentsToUpdate = this.componentsToUpdate;
  54267. if (!this.hasLoaded) { return; }
  54268. // Gather mixin-defined components.
  54269. for (i = 0; i < this.mixinEls.length; i++) {
  54270. for (name in this.mixinEls[i].componentCache) {
  54271. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54272. }
  54273. }
  54274. // Gather from extra initial component data if defined (e.g., primitives).
  54275. if (this.getExtraComponents) {
  54276. extraComponents = this.getExtraComponents();
  54277. for (name in extraComponents) {
  54278. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54279. }
  54280. }
  54281. // Gather entity-defined components.
  54282. for (i = 0; i < this.attributes.length; ++i) {
  54283. name = this.attributes[i].name;
  54284. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  54285. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54286. }
  54287. // object3D components first (position, rotation, scale, visible).
  54288. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  54289. name = OBJECT3D_COMPONENTS[i];
  54290. if (!this.hasAttribute(name)) { continue; }
  54291. this.updateComponent(name, this.getDOMAttribute(name));
  54292. }
  54293. // Initialize or update rest of components.
  54294. for (name in componentsToUpdate) {
  54295. data = mergeComponentData(this.getDOMAttribute(name),
  54296. extraComponents && extraComponents[name]);
  54297. this.updateComponent(name, data);
  54298. delete componentsToUpdate[name];
  54299. }
  54300. },
  54301. writable: window.debug
  54302. },
  54303. /**
  54304. * Initialize, update, or remove a single component.
  54305. *
  54306. * When initializing, we set the component on `this.components`.
  54307. *
  54308. * @param {string} attr - Component name.
  54309. * @param {object} attrValue - Value of the DOM attribute.
  54310. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  54311. */
  54312. updateComponent: {
  54313. value: function (attr, attrValue, clobber) {
  54314. var component = this.components[attr];
  54315. if (component) {
  54316. // Remove component.
  54317. if (attrValue === null && !checkComponentDefined(this, attr)) {
  54318. this.removeComponent(attr, true);
  54319. return;
  54320. }
  54321. // Component already initialized. Update component.
  54322. component.updateProperties(attrValue, clobber);
  54323. return;
  54324. }
  54325. // Component not yet initialized. Initialize component.
  54326. this.initComponent(attr, attrValue, false);
  54327. }
  54328. },
  54329. /**
  54330. * If `attr` is a component name, detach the component from the entity.
  54331. *
  54332. * If `propertyName` is given, reset the component property value to its default.
  54333. *
  54334. * @param {string} attr - Attribute name, which could also be a component name.
  54335. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  54336. */
  54337. removeAttribute: {
  54338. value: function (attr, propertyName) {
  54339. var component = this.components[attr];
  54340. // Remove component.
  54341. if (component && propertyName === undefined) {
  54342. this.removeComponent(attr, true);
  54343. }
  54344. // Reset component property value.
  54345. if (component && propertyName !== undefined) {
  54346. component.resetProperty(propertyName);
  54347. return;
  54348. }
  54349. // Remove mixins.
  54350. if (attr === 'mixin') {
  54351. this.mixinUpdate('');
  54352. }
  54353. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  54354. }
  54355. },
  54356. /**
  54357. * Start dynamic behavior associated with entity such as dynamic components and animations.
  54358. * Tell all children entities to also play.
  54359. */
  54360. play: {
  54361. value: function () {
  54362. var entities;
  54363. var i;
  54364. var key;
  54365. // Already playing.
  54366. if (this.isPlaying || !this.hasLoaded) { return; }
  54367. this.isPlaying = true;
  54368. // Wake up all components.
  54369. for (key in this.components) { this.components[key].play(); }
  54370. // Tell all child entities to play.
  54371. entities = this.getChildEntities();
  54372. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  54373. this.emit('play');
  54374. },
  54375. writable: true
  54376. },
  54377. /**
  54378. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  54379. * Tell all children entities to also pause.
  54380. */
  54381. pause: {
  54382. value: function () {
  54383. var entities;
  54384. var i;
  54385. var key;
  54386. if (!this.isPlaying) { return; }
  54387. this.isPlaying = false;
  54388. // Sleep all components.
  54389. for (key in this.components) { this.components[key].pause(); }
  54390. // Tell all child entities to pause.
  54391. entities = this.getChildEntities();
  54392. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  54393. this.emit('pause');
  54394. },
  54395. writable: true
  54396. },
  54397. /**
  54398. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  54399. *
  54400. * @param {string} attr
  54401. * @param {string} oldVal
  54402. * @param {string|object} newVal
  54403. */
  54404. setEntityAttribute: {
  54405. value: function (attr, oldVal, newVal) {
  54406. if (COMPONENTS[attr] || this.components[attr]) {
  54407. this.updateComponent(attr, newVal);
  54408. return;
  54409. }
  54410. if (attr === 'mixin') {
  54411. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  54412. if (newVal === this.computedMixinStr) { return; }
  54413. this.mixinUpdate(newVal, oldVal);
  54414. }
  54415. }
  54416. },
  54417. /**
  54418. * When mixins updated, trigger init or optimized-update of relevant components.
  54419. */
  54420. mixinUpdate: {
  54421. value: (function () {
  54422. var componentsUpdated = [];
  54423. return function (newMixins, oldMixins) {
  54424. var component;
  54425. var mixinEl;
  54426. var mixinIds;
  54427. var i;
  54428. var self = this;
  54429. if (!this.hasLoaded) {
  54430. this.addEventListener('loaded', function () {
  54431. self.mixinUpdate(newMixins, oldMixins);
  54432. }, ONCE);
  54433. return;
  54434. }
  54435. oldMixins = oldMixins || this.getAttribute('mixin');
  54436. mixinIds = this.updateMixins(newMixins, oldMixins);
  54437. // Loop over current mixins.
  54438. componentsUpdated.length = 0;
  54439. for (i = 0; i < this.mixinEls.length; i++) {
  54440. for (component in this.mixinEls[i].componentCache) {
  54441. if (componentsUpdated.indexOf(component) === -1) {
  54442. if (this.components[component]) {
  54443. // Update. Just rebuild data.
  54444. this.components[component].handleMixinUpdate();
  54445. } else {
  54446. // Init. buildData will gather mixin values.
  54447. this.initComponent(component, null);
  54448. }
  54449. componentsUpdated.push(component);
  54450. }
  54451. }
  54452. }
  54453. // Loop over old mixins to call for data rebuild.
  54454. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  54455. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  54456. if (!mixinEl) { continue; }
  54457. for (component in mixinEl.componentCache) {
  54458. if (componentsUpdated.indexOf(component) === -1) {
  54459. if (this.components[component]) {
  54460. if (this.getDOMAttribute(component)) {
  54461. // Update component if explicitly defined.
  54462. this.components[component].handleMixinUpdate();
  54463. } else {
  54464. // Remove component if not explicitly defined.
  54465. this.removeComponent(component, true);
  54466. }
  54467. }
  54468. }
  54469. }
  54470. }
  54471. };
  54472. })()
  54473. },
  54474. /**
  54475. * setAttribute can:
  54476. *
  54477. * 1. Set a single property of a multi-property component.
  54478. * 2. Set multiple properties of a multi-property component.
  54479. * 3. Replace properties of a multi-property component.
  54480. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  54481. *
  54482. * @param {string} attrName - Component or attribute name.
  54483. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  54484. * object of properties.
  54485. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  54486. * it is a boolean indicating whether to clobber previous values (defaults to false).
  54487. */
  54488. setAttribute: {
  54489. value: (function () {
  54490. var singlePropUpdate = {};
  54491. return function (attrName, arg1, arg2) {
  54492. var newAttrValue;
  54493. var clobber;
  54494. var componentName;
  54495. var delimiterIndex;
  54496. var isDebugMode;
  54497. var key;
  54498. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  54499. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  54500. // Not a component. Normal set attribute.
  54501. if (!COMPONENTS[componentName]) {
  54502. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  54503. ANode.prototype.setAttribute.call(this, attrName, arg1);
  54504. return;
  54505. }
  54506. // Initialize component first if not yet initialized.
  54507. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  54508. this.updateComponent(
  54509. attrName,
  54510. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  54511. }
  54512. // Determine new attributes from the arguments
  54513. if (typeof arg2 !== 'undefined' &&
  54514. typeof arg1 === 'string' &&
  54515. arg1.length > 0 &&
  54516. typeof utils.styleParser.parse(arg1) === 'string') {
  54517. // Update a single property of a multi-property component
  54518. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  54519. newAttrValue = singlePropUpdate;
  54520. newAttrValue[arg1] = arg2;
  54521. clobber = false;
  54522. } else {
  54523. // Update with a value, object, or CSS-style property string, with the possiblity
  54524. // of clobbering previous values.
  54525. newAttrValue = arg1;
  54526. clobber = (arg2 === true);
  54527. }
  54528. // Update component
  54529. this.updateComponent(attrName, newAttrValue, clobber);
  54530. // In debug mode, write component data up to the DOM.
  54531. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  54532. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  54533. };
  54534. })(),
  54535. writable: window.debug
  54536. },
  54537. /**
  54538. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  54539. *
  54540. * @param {bool} recursive - Also flushToDOM on the children.
  54541. **/
  54542. flushToDOM: {
  54543. value: function (recursive) {
  54544. var components = this.components;
  54545. var child;
  54546. var children = this.children;
  54547. var i;
  54548. var key;
  54549. // Flush entity's components to DOM.
  54550. for (key in components) {
  54551. components[key].flushToDOM();
  54552. }
  54553. // Recurse.
  54554. if (!recursive) { return; }
  54555. for (i = 0; i < children.length; ++i) {
  54556. child = children[i];
  54557. if (!child.flushToDOM) { continue; }
  54558. child.flushToDOM(recursive);
  54559. }
  54560. }
  54561. },
  54562. /**
  54563. * If `attr` is a component, returns ALL component data including applied mixins and
  54564. * defaults.
  54565. *
  54566. * If `attr` is not a component, fall back to HTML getAttribute.
  54567. *
  54568. * @param {string} attr
  54569. * @returns {object|string} Object if component, else string.
  54570. */
  54571. getAttribute: {
  54572. value: function (attr) {
  54573. // If component, return component data.
  54574. var component;
  54575. if (attr === 'position') { return this.object3D.position; }
  54576. if (attr === 'rotation') { return getRotation(this); }
  54577. if (attr === 'scale') { return this.object3D.scale; }
  54578. if (attr === 'visible') { return this.object3D.visible; }
  54579. component = this.components[attr];
  54580. if (component) { return component.data; }
  54581. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54582. },
  54583. writable: window.debug
  54584. },
  54585. /**
  54586. * If `attr` is a component, returns JUST the component data defined on the entity.
  54587. * Like a partial version of `getComputedAttribute` as returned component data
  54588. * does not include applied mixins or defaults.
  54589. *
  54590. * If `attr` is not a component, fall back to HTML getAttribute.
  54591. *
  54592. * @param {string} attr
  54593. * @returns {object|string} Object if component, else string.
  54594. */
  54595. getDOMAttribute: {
  54596. value: function (attr) {
  54597. // If cached value exists, return partial component data.
  54598. var component = this.components[attr];
  54599. if (component) { return component.attrValue; }
  54600. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54601. },
  54602. writable: window.debug
  54603. },
  54604. addState: {
  54605. value: function (state) {
  54606. if (this.is(state)) { return; }
  54607. this.states.push(state);
  54608. this.emit('stateadded', state);
  54609. }
  54610. },
  54611. removeState: {
  54612. value: function (state) {
  54613. var stateIndex = this.states.indexOf(state);
  54614. if (stateIndex === -1) { return; }
  54615. this.states.splice(stateIndex, 1);
  54616. this.emit('stateremoved', state);
  54617. }
  54618. },
  54619. /**
  54620. * Checks if the element is in a given state. e.g. el.is('alive');
  54621. * @type {string} state - Name of the state we want to check
  54622. */
  54623. is: {
  54624. value: function (state) {
  54625. return this.states.indexOf(state) !== -1;
  54626. }
  54627. },
  54628. /**
  54629. * Open Inspector to this entity.
  54630. */
  54631. inspect: {
  54632. value: function () {
  54633. this.sceneEl.components.inspector.openInspector(this);
  54634. }
  54635. },
  54636. /**
  54637. * Clean up memory and return memory to object pools.
  54638. */
  54639. destroy: {
  54640. value: function () {
  54641. var key;
  54642. if (this.parentNode) {
  54643. warn('Entity can only be destroyed if detached from scenegraph.');
  54644. return;
  54645. }
  54646. for (key in this.components) {
  54647. this.components[key].destroy();
  54648. }
  54649. }
  54650. }
  54651. });
  54652. /**
  54653. * Check if a component is *defined* for an entity, including defaults and mixins.
  54654. * Does not check whether the component has been *initialized* for an entity.
  54655. *
  54656. * @param {string} el - Entity.
  54657. * @param {string} name - Component name.
  54658. * @returns {boolean}
  54659. */
  54660. function checkComponentDefined (el, name) {
  54661. // Check if element contains the component.
  54662. if (el.components[name] && el.components[name].attrValue) { return true; }
  54663. return isComponentMixedIn(name, el.mixinEls);
  54664. }
  54665. /**
  54666. * Check if any mixins contains a component.
  54667. *
  54668. * @param {string} name - Component name.
  54669. * @param {array} mixinEls - Array of <a-mixin>s.
  54670. */
  54671. function isComponentMixedIn (name, mixinEls) {
  54672. var i;
  54673. var inMixin = false;
  54674. for (i = 0; i < mixinEls.length; ++i) {
  54675. inMixin = mixinEls[i].hasAttribute(name);
  54676. if (inMixin) { break; }
  54677. }
  54678. return inMixin;
  54679. }
  54680. /**
  54681. * Given entity defined value, merge in extra data if necessary.
  54682. * Handle both single and multi-property components.
  54683. *
  54684. * @param {string} attrValue - Entity data.
  54685. * @param extraData - Entity data from another source to merge in.
  54686. */
  54687. function mergeComponentData (attrValue, extraData) {
  54688. // Extra data not defined, just return attrValue.
  54689. if (!extraData) { return attrValue; }
  54690. // Merge multi-property data.
  54691. if (extraData.constructor === Object) {
  54692. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  54693. }
  54694. // Return data, precendence to the defined value.
  54695. return attrValue || extraData;
  54696. }
  54697. function isComponent (componentName) {
  54698. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  54699. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  54700. }
  54701. if (!COMPONENTS[componentName]) { return false; }
  54702. return true;
  54703. }
  54704. function getRotation (entityEl) {
  54705. var radToDeg = THREE.Math.radToDeg;
  54706. var rotation = entityEl.object3D.rotation;
  54707. var rotationObj = entityEl.rotationObj;
  54708. rotationObj.x = radToDeg(rotation.x);
  54709. rotationObj.y = radToDeg(rotation.y);
  54710. rotationObj.z = radToDeg(rotation.z);
  54711. return rotationObj;
  54712. }
  54713. AEntity = registerElement('a-entity', {prototype: proto});
  54714. module.exports = AEntity;
  54715. },{"../lib/three":183,"../utils/":210,"./a-node":133,"./a-register-element":134,"./component":135}],132:[function(require,module,exports){
  54716. var ANode = require('./a-node');
  54717. var registerElement = require('./a-register-element').registerElement;
  54718. var components = require('./component').components;
  54719. var utils = require('../utils');
  54720. var MULTIPLE_COMPONENT_DELIMITER = '__';
  54721. /**
  54722. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  54723. * are component names and the values are already parsed by the component.
  54724. */
  54725. module.exports = registerElement('a-mixin', {
  54726. prototype: Object.create(ANode.prototype, {
  54727. createdCallback: {
  54728. value: function () {
  54729. this.componentCache = {};
  54730. this.id = this.getAttribute('id');
  54731. this.isMixin = true;
  54732. }
  54733. },
  54734. attributeChangedCallback: {
  54735. value: function (attr, oldVal, newVal) {
  54736. this.cacheAttribute(attr, newVal);
  54737. this.updateEntities();
  54738. }
  54739. },
  54740. attachedCallback: {
  54741. value: function () {
  54742. this.sceneEl = this.closestScene();
  54743. this.cacheAttributes();
  54744. this.updateEntities();
  54745. this.load();
  54746. }
  54747. },
  54748. /**
  54749. * setAttribute that parses and caches component values.
  54750. */
  54751. setAttribute: {
  54752. value: function (attr, value) {
  54753. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  54754. this.cacheAttribute(attr, value);
  54755. }
  54756. },
  54757. /**
  54758. * If `attr` is a component, then parse the value using the schema and store it.
  54759. */
  54760. cacheAttribute: {
  54761. value: function (attr, value) {
  54762. var component;
  54763. var componentName;
  54764. // Get component data.
  54765. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  54766. component = components[componentName];
  54767. if (!component) { return; }
  54768. if (value === undefined) {
  54769. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  54770. }
  54771. this.componentCache[attr] = component.parseAttrValueForCache(value);
  54772. }
  54773. },
  54774. /**
  54775. * If `attr` is a component, then grab pre-parsed value from the cache.
  54776. * Else do a normal getAttribute.
  54777. */
  54778. getAttribute: {
  54779. value: function (attr) {
  54780. return this.componentCache[attr] ||
  54781. window.HTMLElement.prototype.getAttribute.call(this, attr);
  54782. }
  54783. },
  54784. /**
  54785. * Parse and cache every component defined on the mixin.
  54786. */
  54787. cacheAttributes: {
  54788. value: function () {
  54789. var attributes = this.attributes;
  54790. var attrName;
  54791. var i;
  54792. for (i = 0; i < attributes.length; i++) {
  54793. attrName = attributes[i].name;
  54794. this.cacheAttribute(attrName);
  54795. }
  54796. }
  54797. },
  54798. /**
  54799. * For entities that already have been loaded by the time the mixin was attached, tell
  54800. * those entities to register the mixin and refresh their component data.
  54801. */
  54802. updateEntities: {
  54803. value: function () {
  54804. var entity;
  54805. var entities;
  54806. var i;
  54807. if (!this.sceneEl) { return; }
  54808. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  54809. for (i = 0; i < entities.length; i++) {
  54810. entity = entities[i];
  54811. if (!entity.hasLoaded || entity.isMixin) { continue; }
  54812. entity.mixinUpdate(this.id);
  54813. }
  54814. }
  54815. }
  54816. })
  54817. });
  54818. },{"../utils":210,"./a-node":133,"./a-register-element":134,"./component":135}],133:[function(require,module,exports){
  54819. /* global CustomEvent */
  54820. var registerElement = require('./a-register-element').registerElement;
  54821. var isNode = require('./a-register-element').isNode;
  54822. var utils = require('../utils/');
  54823. var warn = utils.debug('core:a-node:warn');
  54824. var error = utils.debug('core:a-node:error');
  54825. /**
  54826. * Base class for A-Frame that manages loading of objects.
  54827. *
  54828. * Nodes can be modified using mixins.
  54829. * Nodes emit a `loaded` event when they and their children have initialized.
  54830. */
  54831. module.exports = registerElement('a-node', {
  54832. prototype: Object.create(window.HTMLElement.prototype, {
  54833. createdCallback: {
  54834. value: function () {
  54835. this.computedMixinStr = '';
  54836. this.hasLoaded = false;
  54837. this.isNode = true;
  54838. this.mixinEls = [];
  54839. },
  54840. writable: window.debug
  54841. },
  54842. attachedCallback: {
  54843. value: function () {
  54844. var mixins;
  54845. this.sceneEl = this.closestScene();
  54846. if (!this.sceneEl) {
  54847. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  54848. 'scene. Append this element to `<a-scene>` instead.');
  54849. }
  54850. this.hasLoaded = false;
  54851. this.emit('nodeready', undefined, false);
  54852. if (!this.isMixin) {
  54853. mixins = this.getAttribute('mixin');
  54854. if (mixins) { this.updateMixins(mixins); }
  54855. }
  54856. },
  54857. writable: window.debug
  54858. },
  54859. /**
  54860. * Handle mixin.
  54861. */
  54862. attributeChangedCallback: {
  54863. value: function (attr, oldVal, newVal) {
  54864. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  54865. if (newVal === this.computedMixinStr) { return; }
  54866. if (attr === 'mixin' && !this.isMixin) {
  54867. this.updateMixins(newVal, oldVal);
  54868. }
  54869. }
  54870. },
  54871. /**
  54872. * Returns the first scene by traversing up the tree starting from and
  54873. * including receiver element.
  54874. */
  54875. closestScene: {
  54876. value: function closest () {
  54877. var element = this;
  54878. while (element) {
  54879. if (element.isScene) { break; }
  54880. element = element.parentElement;
  54881. }
  54882. return element;
  54883. }
  54884. },
  54885. /**
  54886. * Returns first element matching a selector by traversing up the tree starting
  54887. * from and including receiver element.
  54888. *
  54889. * @param {string} selector - Selector of element to find.
  54890. */
  54891. closest: {
  54892. value: function closest (selector) {
  54893. var matches = this.matches || this.mozMatchesSelector ||
  54894. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  54895. var element = this;
  54896. while (element) {
  54897. if (matches.call(element, selector)) { break; }
  54898. element = element.parentElement;
  54899. }
  54900. return element;
  54901. }
  54902. },
  54903. detachedCallback: {
  54904. value: function () {
  54905. this.hasLoaded = false;
  54906. }
  54907. },
  54908. /**
  54909. * Wait for children to load, if any.
  54910. * Then emit `loaded` event and set `hasLoaded`.
  54911. */
  54912. load: {
  54913. value: function (cb, childFilter) {
  54914. var children;
  54915. var childrenLoaded;
  54916. var self = this;
  54917. if (this.hasLoaded) { return; }
  54918. // Default to waiting for all nodes.
  54919. childFilter = childFilter || isNode;
  54920. // Wait for children to load (if any), then load.
  54921. children = this.getChildren();
  54922. childrenLoaded = children.filter(childFilter).map(function (child) {
  54923. return new Promise(function waitForLoaded (resolve) {
  54924. if (child.hasLoaded) { return resolve(); }
  54925. child.addEventListener('loaded', resolve);
  54926. });
  54927. });
  54928. Promise.all(childrenLoaded).then(function emitLoaded () {
  54929. self.hasLoaded = true;
  54930. if (cb) { cb(); }
  54931. self.emit('loaded', undefined, false);
  54932. }).catch(function (err) {
  54933. error('Failure loading node: ', err);
  54934. });
  54935. },
  54936. writable: true
  54937. },
  54938. getChildren: {
  54939. value: function () {
  54940. return Array.prototype.slice.call(this.children, 0);
  54941. }
  54942. },
  54943. /**
  54944. * Unregister old mixins and listeners.
  54945. * Register new mixins and listeners.
  54946. * Registering means to update `this.mixinEls` with listeners.
  54947. */
  54948. updateMixins: {
  54949. value: (function () {
  54950. var newMixinIdArray = [];
  54951. var oldMixinIdArray = [];
  54952. var mixinIds = {};
  54953. return function (newMixins, oldMixins) {
  54954. var i;
  54955. var newMixinIds;
  54956. var oldMixinIds;
  54957. newMixinIdArray.length = 0;
  54958. oldMixinIdArray.length = 0;
  54959. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  54960. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  54961. mixinIds.newMixinIds = newMixinIds;
  54962. mixinIds.oldMixinIds = oldMixinIds;
  54963. // Unregister old mixins.
  54964. for (i = 0; i < oldMixinIds.length; i++) {
  54965. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  54966. this.unregisterMixin(oldMixinIds[i]);
  54967. }
  54968. }
  54969. // Register new mixins.
  54970. this.computedMixinStr = '';
  54971. this.mixinEls.length = 0;
  54972. for (i = 0; i < newMixinIds.length; i++) {
  54973. this.registerMixin(document.getElementById(newMixinIds[i]));
  54974. }
  54975. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  54976. // update.
  54977. if (this.computedMixinStr) {
  54978. this.computedMixinStr = this.computedMixinStr.trim();
  54979. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  54980. this.computedMixinStr);
  54981. }
  54982. return mixinIds;
  54983. };
  54984. })()
  54985. },
  54986. /**
  54987. * From mixin ID, add mixin element to `mixinEls`.
  54988. *
  54989. * @param {Element} mixinEl
  54990. */
  54991. registerMixin: {
  54992. value: function (mixinEl) {
  54993. var compositedMixinIds;
  54994. var i;
  54995. var mixin;
  54996. if (!mixinEl) { return; }
  54997. // Register composited mixins (if mixin has mixins).
  54998. mixin = mixinEl.getAttribute('mixin');
  54999. if (mixin) {
  55000. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  55001. for (i = 0; i < compositedMixinIds.length; i++) {
  55002. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  55003. }
  55004. }
  55005. // Register mixin.
  55006. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  55007. this.mixinEls.push(mixinEl);
  55008. }
  55009. },
  55010. setAttribute: {
  55011. value: function (attr, newValue) {
  55012. if (attr === 'mixin') { this.updateMixins(newValue); }
  55013. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  55014. }
  55015. },
  55016. unregisterMixin: {
  55017. value: function (mixinId) {
  55018. var i;
  55019. var mixinEls = this.mixinEls;
  55020. var mixinEl;
  55021. for (i = 0; i < mixinEls.length; ++i) {
  55022. mixinEl = mixinEls[i];
  55023. if (mixinId === mixinEl.id) {
  55024. mixinEls.splice(i, 1);
  55025. break;
  55026. }
  55027. }
  55028. }
  55029. },
  55030. /**
  55031. * Emit a DOM event.
  55032. *
  55033. * @param {string} name - Name of event.
  55034. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  55035. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  55036. * @param {object} [extraData] - Extra data to pass to the event, if any.
  55037. */
  55038. emit: {
  55039. value: (function () {
  55040. var data = {};
  55041. return function (name, detail, bubbles, extraData) {
  55042. if (bubbles === undefined) { bubbles = true; }
  55043. data.bubbles = !!bubbles;
  55044. data.detail = detail;
  55045. // If extra data is present, we need to create a new object.
  55046. if (extraData) { data = utils.extend({}, extraData, data); }
  55047. this.dispatchEvent(new CustomEvent(name, data));
  55048. };
  55049. })(),
  55050. writable: window.debug
  55051. }
  55052. })
  55053. });
  55054. },{"../utils/":210,"./a-register-element":134}],134:[function(require,module,exports){
  55055. /*
  55056. ------------------------------------------------------------
  55057. ------------- WARNING WARNING WARNING WARNING --------------
  55058. ------------------------------------------------------------
  55059. This module wraps registerElement to deal with components that inherit from
  55060. `ANode` and `AEntity`. It's a pass through in any other case.
  55061. It wraps some of the prototype methods of the created element to make sure
  55062. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  55063. are also invoked. The method in the base prototype is always called before the one
  55064. in the derived prototype.
  55065. */
  55066. // Polyfill `document.registerElement`.
  55067. require('document-register-element');
  55068. var ANode; // Must declare before AEntity. Initialized at the bottom.
  55069. var AEntity;
  55070. var knownTags = module.exports.knownTags = {};
  55071. function addTagName (tagName) {
  55072. knownTags[tagName.toLowerCase()] = true;
  55073. }
  55074. /**
  55075. * Return whether the element type is one of our known registered ones.
  55076. *
  55077. * @param {string} node - The name of the tag to register.
  55078. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  55079. */
  55080. module.exports.isNode = function (node) {
  55081. return node.tagName.toLowerCase() in knownTags || node.isNode;
  55082. };
  55083. /**
  55084. * @param {string} tagName - The name of the tag to register.
  55085. * @param {object} obj - The prototype of the new element.
  55086. * @returns {object} The prototype of the new element.
  55087. */
  55088. module.exports.registerElement = function (tagName, obj) {
  55089. var proto = Object.getPrototypeOf(obj.prototype);
  55090. var newObj = obj;
  55091. var isANode = ANode && proto === ANode.prototype;
  55092. var isAEntity = AEntity && proto === AEntity.prototype;
  55093. if (isANode || isAEntity) { addTagName(tagName); }
  55094. // Wrap if element inherits from `ANode`.
  55095. if (isANode) {
  55096. newObj = wrapANodeMethods(obj.prototype);
  55097. newObj = {prototype: Object.create(proto, newObj)};
  55098. }
  55099. // Wrap if element inherits from `AEntity`.
  55100. if (isAEntity) {
  55101. newObj = wrapAEntityMethods(obj.prototype);
  55102. newObj = {prototype: Object.create(proto, newObj)};
  55103. }
  55104. // Give all functions their proper name.
  55105. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  55106. var propVal = newObj.prototype[propName];
  55107. if (typeof propVal === 'function') {
  55108. propVal.displayName = propName;
  55109. }
  55110. });
  55111. return document.registerElement(tagName, newObj);
  55112. };
  55113. /**
  55114. * Wrap some obj methods to call those on `ANode` base prototype.
  55115. *
  55116. * @param {object} obj - Object that contains the methods that will be wrapped.
  55117. * @return {object} An object with the same properties as the input parameter but
  55118. * with some of methods wrapped.
  55119. */
  55120. function wrapANodeMethods (obj) {
  55121. var newObj = {};
  55122. var ANodeMethods = [
  55123. 'attachedCallback',
  55124. 'attributeChangedCallback',
  55125. 'createdCallback',
  55126. 'detachedCallback'
  55127. ];
  55128. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55129. copyProperties(obj, newObj);
  55130. return newObj;
  55131. }
  55132. /**
  55133. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  55134. *
  55135. * @param {object} obj - The objects that contains the methods that will be wrapped.
  55136. * @return {object} - An object with the same properties as the input parameter but
  55137. * with some of methods wrapped.
  55138. */
  55139. function wrapAEntityMethods (obj) {
  55140. var newObj = {};
  55141. var ANodeMethods = [
  55142. 'attachedCallback',
  55143. 'attributeChangedCallback',
  55144. 'createdCallback',
  55145. 'detachedCallback'
  55146. ];
  55147. var AEntityMethods = [
  55148. 'attachedCallback',
  55149. 'attributeChangedCallback',
  55150. 'createdCallback',
  55151. 'detachedCallback'
  55152. ];
  55153. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55154. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  55155. // Copies the remaining properties into the new object.
  55156. copyProperties(obj, newObj);
  55157. return newObj;
  55158. }
  55159. /**
  55160. * Wrap a list a methods to ensure that those in the base prototype are called
  55161. * before the derived one.
  55162. *
  55163. * @param {object} targetObj - Object that will contain the wrapped methods.
  55164. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  55165. * @param {object} derivedObject - Object that inherits from the baseObj.
  55166. * @param {object} baseObj - Object that derivedObj inherits from.
  55167. */
  55168. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  55169. methodList.forEach(function (methodName) {
  55170. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  55171. });
  55172. }
  55173. module.exports.wrapMethods = wrapMethods;
  55174. /**
  55175. * Wrap one method to ensure that the one in the base prototype is called before
  55176. * the one in the derived one.
  55177. *
  55178. * @param {object} obj - Object that will contain the wrapped method.
  55179. * @param {string} methodName - The name of the method that will be wrapped.
  55180. * @param {object} derivedObject - Object that inherits from the baseObj.
  55181. * @param {object} baseObj - Object that derivedObj inherits from.
  55182. */
  55183. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  55184. var derivedMethod = derivedObj[methodName];
  55185. var baseMethod = baseObj[methodName];
  55186. // Derived prototype does not define method, no need to wrap.
  55187. if (!derivedMethod || !baseMethod) { return; }
  55188. // Derived prototype doesn't override the one in the base one, no need to wrap.
  55189. if (derivedMethod === baseMethod) { return; }
  55190. // Wrap to ensure the base method is called before the one in the derived prototype.
  55191. obj[methodName] = {
  55192. value: function wrappedMethod () {
  55193. baseMethod.apply(this, arguments);
  55194. return derivedMethod.apply(this, arguments);
  55195. },
  55196. writable: window.debug
  55197. };
  55198. }
  55199. /**
  55200. * It copies the properties from source to destination object if they don't
  55201. * exist already.
  55202. *
  55203. * @param {object} source - The object where properties are copied from.
  55204. * @param {type} destination - The object where properties are copied to.
  55205. */
  55206. function copyProperties (source, destination) {
  55207. var props = Object.getOwnPropertyNames(source);
  55208. props.forEach(function (prop) {
  55209. var desc;
  55210. if (!destination[prop]) {
  55211. desc = Object.getOwnPropertyDescriptor(source, prop);
  55212. destination[prop] = {value: source[prop], writable: desc.writable};
  55213. }
  55214. });
  55215. }
  55216. ANode = require('./a-node');
  55217. AEntity = require('./a-entity');
  55218. },{"./a-entity":131,"./a-node":133,"document-register-element":12}],135:[function(require,module,exports){
  55219. /* global Node */
  55220. var schema = require('./schema');
  55221. var scenes = require('./scene/scenes');
  55222. var systems = require('./system');
  55223. var utils = require('../utils/');
  55224. var components = module.exports.components = {}; // Keep track of registered components.
  55225. var parseProperties = schema.parseProperties;
  55226. var parseProperty = schema.parseProperty;
  55227. var processSchema = schema.process;
  55228. var isSingleProp = schema.isSingleProperty;
  55229. var stringifyProperties = schema.stringifyProperties;
  55230. var stringifyProperty = schema.stringifyProperty;
  55231. var styleParser = utils.styleParser;
  55232. var warn = utils.debug('core:component:warn');
  55233. var aframeScript = document.currentScript;
  55234. var upperCaseRegExp = new RegExp('[A-Z]+');
  55235. // Object pools by component, created upon registration.
  55236. var objectPools = {};
  55237. /**
  55238. * Component class definition.
  55239. *
  55240. * Components configure appearance, modify behavior, or add functionality to
  55241. * entities. The behavior and appearance of an entity can be changed at runtime
  55242. * by adding, removing, or updating components. Entities do not share instances
  55243. * of components.
  55244. *
  55245. * @member {object} el - Reference to the entity element.
  55246. * @member {string} attrValue - Value of the corresponding HTML attribute.
  55247. * @member {object} data - Component data populated by parsing the
  55248. * mapped attribute of the component plus applying defaults and mixins.
  55249. */
  55250. var Component = module.exports.Component = function (el, attrValue, id) {
  55251. var self = this;
  55252. this.el = el;
  55253. this.id = id;
  55254. this.attrName = this.name + (id ? '__' + id : '');
  55255. this.evtDetail = {id: this.id, name: this.name};
  55256. this.initialized = false;
  55257. this.isSingleProperty = isSingleProp(this.schema);
  55258. this.isSinglePropertyObject = this.isSingleProperty &&
  55259. isObject(parseProperty(undefined, this.schema)) &&
  55260. !(this.schema.default instanceof window.HTMLElement);
  55261. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  55262. this.el.components[this.attrName] = this;
  55263. this.objectPool = objectPools[this.name];
  55264. const events = this.events;
  55265. this.events = {};
  55266. eventsBind(this, events);
  55267. // Store component data from previous update call.
  55268. this.attrValue = undefined;
  55269. if (this.isObjectBased) {
  55270. this.nextData = this.objectPool.use();
  55271. // Drop any properties added by dynamic schemas in previous use
  55272. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  55273. this.oldData = this.objectPool.use();
  55274. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  55275. this.previousOldData = this.objectPool.use();
  55276. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  55277. this.parsingAttrValue = this.objectPool.use();
  55278. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  55279. } else {
  55280. this.nextData = undefined;
  55281. this.oldData = undefined;
  55282. this.previousOldData = undefined;
  55283. this.parsingAttrValue = undefined;
  55284. }
  55285. // Last value passed to updateProperties.
  55286. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  55287. el.emit('componentchanged', self.evtDetail, false);
  55288. }, 200);
  55289. this.updateProperties(attrValue);
  55290. };
  55291. Component.prototype = {
  55292. /**
  55293. * Contains the type schema and defaults for the data values.
  55294. * Data is coerced into the types of the values of the defaults.
  55295. */
  55296. schema: {},
  55297. /**
  55298. * Init handler. Similar to attachedCallback.
  55299. * Called during component initialization and is only run once.
  55300. * Components can use this to set initial state.
  55301. */
  55302. init: function () { /* no-op */ },
  55303. /**
  55304. * Map of event names to binded event handlers that will be lifecycle-handled.
  55305. * Will be detached on pause / remove.
  55306. * Will be attached on play.
  55307. */
  55308. events: {},
  55309. /**
  55310. * Update handler. Similar to attributeChangedCallback.
  55311. * Called whenever component's data changes.
  55312. * Also called on component initialization when the component receives initial data.
  55313. *
  55314. * @param {object} prevData - Previous attributes of the component.
  55315. */
  55316. update: function (prevData) { /* no-op */ },
  55317. updateSchema: undefined,
  55318. /**
  55319. * Tick handler.
  55320. * Called on each tick of the scene render loop.
  55321. * Affected by play and pause.
  55322. *
  55323. * @param {number} time - Scene tick time.
  55324. * @param {number} timeDelta - Difference in current render time and previous render time.
  55325. */
  55326. tick: undefined,
  55327. /**
  55328. * Tock handler.
  55329. * Called on each tock of the scene render loop.
  55330. * Affected by play and pause.
  55331. *
  55332. * @param {number} time - Scene tick time.
  55333. * @param {number} timeDelta - Difference in current render time and previous render time.
  55334. * @param {object} camera - Camera used to render the last frame.
  55335. */
  55336. tock: undefined,
  55337. /**
  55338. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  55339. */
  55340. play: function () { /* no-op */ },
  55341. /**
  55342. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  55343. */
  55344. pause: function () { /* no-op */ },
  55345. /**
  55346. * Remove handler. Similar to detachedCallback.
  55347. * Called whenever component is removed from the entity (i.e., removeAttribute).
  55348. * Components can use this to reset behavior on the entity.
  55349. */
  55350. remove: function () { /* no-op */ },
  55351. /**
  55352. * Parses each property based on property type.
  55353. * If component is single-property, then parses the single property value.
  55354. *
  55355. * @param {string} value - HTML attribute value.
  55356. * @param {boolean} silent - Suppress warning messages.
  55357. * @returns {object} Component data.
  55358. */
  55359. parse: function (value, silent) {
  55360. var schema = this.schema;
  55361. if (this.isSingleProperty) { return parseProperty(value, schema); }
  55362. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  55363. },
  55364. /**
  55365. * Stringify properties if necessary.
  55366. *
  55367. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  55368. * value (e.g., selector, vec3 property types).
  55369. *
  55370. * @param {object} data - Complete component data.
  55371. * @returns {string}
  55372. */
  55373. stringify: function (data) {
  55374. var schema = this.schema;
  55375. if (typeof data === 'string') { return data; }
  55376. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  55377. data = stringifyProperties(data, schema);
  55378. return styleParser.stringify(data);
  55379. },
  55380. /**
  55381. * Update the cache of the pre-parsed attribute value.
  55382. *
  55383. * @param {string} value - New data.
  55384. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  55385. */
  55386. updateCachedAttrValue: function (value, clobber) {
  55387. var newAttrValue;
  55388. var tempObject;
  55389. var property;
  55390. if (value === undefined) { return; }
  55391. // If null value is the new attribute value, make the attribute value falsy.
  55392. if (value === null) {
  55393. if (this.isObjectBased && this.attrValue) {
  55394. this.objectPool.recycle(this.attrValue);
  55395. }
  55396. this.attrValue = undefined;
  55397. return;
  55398. }
  55399. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  55400. // If value is an object, copy it to our pooled newAttrValue object to use to update
  55401. // the attrValue.
  55402. tempObject = this.objectPool.use();
  55403. newAttrValue = utils.extend(tempObject, value);
  55404. } else {
  55405. newAttrValue = this.parseAttrValueForCache(value);
  55406. }
  55407. // Merge new data with previous `attrValue` if updating and not clobbering.
  55408. if (this.isObjectBased && !clobber && this.attrValue) {
  55409. for (property in this.attrValue) {
  55410. if (newAttrValue[property] === undefined) {
  55411. newAttrValue[property] = this.attrValue[property];
  55412. }
  55413. }
  55414. }
  55415. // Update attrValue.
  55416. if (this.isObjectBased && !this.attrValue) {
  55417. this.attrValue = this.objectPool.use();
  55418. }
  55419. utils.objectPool.clearObject(this.attrValue);
  55420. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  55421. utils.objectPool.clearObject(tempObject);
  55422. },
  55423. /**
  55424. * Given an HTML attribute value parses the string based on the component schema.
  55425. * To avoid double parsings of strings into strings we store the original instead
  55426. * of the parsed one
  55427. *
  55428. * @param {string} value - HTML attribute value
  55429. */
  55430. parseAttrValueForCache: function (value) {
  55431. var parsedValue;
  55432. if (typeof value !== 'string') { return value; }
  55433. if (this.isSingleProperty) {
  55434. parsedValue = this.schema.parse(value);
  55435. /**
  55436. * To avoid bogus double parsings. Cached values will be parsed when building
  55437. * component data. For instance when parsing a src id to its url, we want to cache
  55438. * original string and not the parsed one (#monster -> models/monster.dae)
  55439. * so when building data we parse the expected value.
  55440. */
  55441. if (typeof parsedValue === 'string') { parsedValue = value; }
  55442. } else {
  55443. // Parse using the style parser to avoid double parsing of individual properties.
  55444. utils.objectPool.clearObject(this.parsingAttrValue);
  55445. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  55446. }
  55447. return parsedValue;
  55448. },
  55449. /**
  55450. * Write cached attribute data to the entity DOM element.
  55451. *
  55452. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  55453. * default components.
  55454. */
  55455. flushToDOM: function (isDefault) {
  55456. var attrValue = isDefault ? this.data : this.attrValue;
  55457. if (attrValue === null || attrValue === undefined) { return; }
  55458. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  55459. this.stringify(attrValue));
  55460. },
  55461. /**
  55462. * Apply new component data if data has changed (from setAttribute).
  55463. *
  55464. * @param {string} attrValue - HTML attribute value.
  55465. * If undefined, use the cached attribute value and continue updating properties.
  55466. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  55467. */
  55468. updateProperties: function (attrValue, clobber) {
  55469. var el = this.el;
  55470. // Just cache the attribute if the entity has not loaded
  55471. // Components are not initialized until the entity has loaded
  55472. if (!el.hasLoaded) {
  55473. this.updateCachedAttrValue(attrValue);
  55474. return;
  55475. }
  55476. // Parse the attribute value.
  55477. // Cache current attrValue for future updates. Updates `this.attrValue`.
  55478. // `null` means no value on purpose, do not set a default value, let mixins take over.
  55479. if (attrValue !== null) {
  55480. attrValue = this.parseAttrValueForCache(attrValue);
  55481. }
  55482. // Cache current attrValue for future updates.
  55483. this.updateCachedAttrValue(attrValue, clobber);
  55484. if (this.initialized) {
  55485. this.updateComponent(attrValue, clobber);
  55486. this.callUpdateHandler();
  55487. } else {
  55488. this.initComponent();
  55489. }
  55490. },
  55491. initComponent: function () {
  55492. var el = this.el;
  55493. var initialOldData;
  55494. // Build data.
  55495. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  55496. this.data = this.buildData(this.attrValue);
  55497. // Component is being already initialized.
  55498. if (el.initializingComponents[this.name]) { return; }
  55499. // Prevent infinite loop in case of init method setting same component on the entity.
  55500. el.initializingComponents[this.name] = true;
  55501. // Initialize component.
  55502. this.init();
  55503. this.initialized = true;
  55504. delete el.initializingComponents[this.name];
  55505. // Store current data as previous data for future updates.
  55506. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55507. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  55508. // Pass undefined to rest of types.
  55509. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  55510. this.update(initialOldData);
  55511. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  55512. // Play the component if the entity is playing.
  55513. if (el.isPlaying) { this.play(); }
  55514. el.emit('componentinitialized', this.evtDetail, false);
  55515. },
  55516. /**
  55517. * @param attrValue - Passed argument from setAttribute.
  55518. */
  55519. updateComponent: function (attrValue, clobber) {
  55520. var key;
  55521. var mayNeedSchemaUpdate;
  55522. if (clobber) {
  55523. // Clobber. Rebuild.
  55524. if (this.updateSchema) {
  55525. this.updateSchema(this.buildData(this.attrValue, true, true));
  55526. }
  55527. this.data = this.buildData(this.attrValue, true, false);
  55528. return;
  55529. }
  55530. // Apply new value to this.data in place since direct update.
  55531. if (this.isSingleProperty) {
  55532. if (this.isObjectBased) {
  55533. parseProperty(attrValue, this.schema);
  55534. }
  55535. // Single-property (already parsed).
  55536. this.data = attrValue;
  55537. return;
  55538. }
  55539. parseProperties(attrValue, this.schema, true, this.name);
  55540. // Check if we need to update schema.
  55541. if (this.schemaChangeKeys.length) {
  55542. for (key in attrValue) {
  55543. if (this.schema[key].schemaChange) {
  55544. mayNeedSchemaUpdate = true;
  55545. break;
  55546. }
  55547. }
  55548. }
  55549. if (mayNeedSchemaUpdate) {
  55550. // Rebuild data if need schema update.
  55551. if (this.updateSchema) {
  55552. this.updateSchema(this.buildData(this.attrValue, true, true));
  55553. }
  55554. this.data = this.buildData(this.attrValue, true, false);
  55555. return;
  55556. }
  55557. // Normal update.
  55558. for (key in attrValue) {
  55559. if (attrValue[key] === undefined) { continue; }
  55560. this.data[key] = attrValue[key];
  55561. }
  55562. },
  55563. /**
  55564. * Check if component should fire update and fire update lifecycle handler.
  55565. */
  55566. callUpdateHandler: function () {
  55567. var hasComponentChanged;
  55568. // Store the previous old data before we calculate the new oldData.
  55569. if (this.previousOldData instanceof Object) {
  55570. utils.objectPool.clearObject(this.previousOldData);
  55571. }
  55572. if (this.isObjectBased) {
  55573. copyData(this.previousOldData, this.oldData);
  55574. } else {
  55575. this.previousOldData = this.oldData;
  55576. }
  55577. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  55578. // Don't update if properties haven't changed.
  55579. // Always update rotation, position, scale.
  55580. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  55581. // Store current data as previous data for future updates.
  55582. // Reuse `this.oldData` object to try not to allocate another one.
  55583. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  55584. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55585. // Update component with the previous old data.
  55586. this.update(this.previousOldData);
  55587. this.throttledEmitComponentChanged();
  55588. },
  55589. handleMixinUpdate: function () {
  55590. this.data = this.buildData(this.attrValue);
  55591. this.callUpdateHandler();
  55592. },
  55593. /**
  55594. * Reset value of a property to the property's default value.
  55595. * If single-prop component, reset value to component's default value.
  55596. *
  55597. * @param {string} propertyName - Name of property to reset.
  55598. */
  55599. resetProperty: function (propertyName) {
  55600. if (this.isObjectBased) {
  55601. if (!(propertyName in this.attrValue)) { return; }
  55602. delete this.attrValue[propertyName];
  55603. this.data[propertyName] = this.schema[propertyName].default;
  55604. } else {
  55605. this.attrValue = this.schema.default;
  55606. this.data = this.schema.default;
  55607. }
  55608. this.updateProperties(this.attrValue);
  55609. },
  55610. /**
  55611. * Extend schema of component given a partial schema.
  55612. *
  55613. * Some components might want to mutate their schema based on certain properties.
  55614. * e.g., Material component changes its schema based on `shader` to account for different
  55615. * uniforms
  55616. *
  55617. * @param {object} schemaAddon - Schema chunk that extend base schema.
  55618. */
  55619. extendSchema: function (schemaAddon) {
  55620. var extendedSchema;
  55621. // Clone base schema.
  55622. extendedSchema = utils.extend({}, components[this.name].schema);
  55623. // Extend base schema with new schema chunk.
  55624. utils.extend(extendedSchema, schemaAddon);
  55625. this.schema = processSchema(extendedSchema);
  55626. this.el.emit('schemachanged', this.evtDetail);
  55627. },
  55628. /**
  55629. * Build component data from the current state of the entity.data.
  55630. *
  55631. * Precedence:
  55632. * 1. Defaults data
  55633. * 2. Mixin data.
  55634. * 3. Attribute data.
  55635. *
  55636. * Finally coerce the data to the types of the defaults.
  55637. *
  55638. * @param {object} newData - Element new data.
  55639. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  55640. * @param {boolean} silent - Suppress warning messages.
  55641. * @return {object} The component data
  55642. */
  55643. buildData: function (newData, clobber, silent) {
  55644. var componentDefined;
  55645. var data;
  55646. var defaultValue;
  55647. var key;
  55648. var mixinData;
  55649. var nextData = this.nextData;
  55650. var schema = this.schema;
  55651. var i;
  55652. var mixinEls = this.el.mixinEls;
  55653. var previousData;
  55654. // Whether component has a defined value. For arrays, treat empty as not defined.
  55655. componentDefined = newData && newData.constructor === Array
  55656. ? newData.length
  55657. : newData !== undefined && newData !== null;
  55658. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  55659. // 1. Gather default values (lowest precendence).
  55660. if (this.isSingleProperty) {
  55661. if (this.isObjectBased) {
  55662. // If object-based single-prop, then copy over the data to our pooled object.
  55663. data = copyData(nextData, schema.default);
  55664. } else {
  55665. // If is plain single-prop, copy by value the default.
  55666. data = isObjectOrArray(schema.default)
  55667. ? utils.clone(schema.default)
  55668. : schema.default;
  55669. }
  55670. } else {
  55671. // Preserve previously set properties if clobber not enabled.
  55672. previousData = !clobber && this.attrValue;
  55673. // Clone default value if object so components don't share object
  55674. data = previousData instanceof Object
  55675. ? copyData(nextData, previousData)
  55676. : nextData;
  55677. // Apply defaults.
  55678. for (key in schema) {
  55679. defaultValue = schema[key].default;
  55680. if (data[key] !== undefined) { continue; }
  55681. // Clone default value if object so components don't share object
  55682. data[key] = isObjectOrArray(defaultValue)
  55683. ? utils.clone(defaultValue)
  55684. : defaultValue;
  55685. }
  55686. }
  55687. // 2. Gather mixin values.
  55688. for (i = 0; i < mixinEls.length; i++) {
  55689. mixinData = mixinEls[i].getAttribute(this.attrName);
  55690. if (!mixinData) { continue; }
  55691. data = extendProperties(data, mixinData, this.isObjectBased);
  55692. }
  55693. // 3. Gather attribute values (highest precendence).
  55694. if (componentDefined) {
  55695. if (this.isSingleProperty) {
  55696. // If object-based, copy the value to not modify the original.
  55697. if (isObject(newData)) {
  55698. copyData(this.parsingAttrValue, newData);
  55699. return parseProperty(this.parsingAttrValue, schema);
  55700. }
  55701. return parseProperty(newData, schema);
  55702. }
  55703. data = extendProperties(data, newData, this.isObjectBased);
  55704. } else {
  55705. // Parse and coerce using the schema.
  55706. if (this.isSingleProperty) { return parseProperty(data, schema); }
  55707. }
  55708. return parseProperties(data, schema, undefined, this.name, silent);
  55709. },
  55710. /**
  55711. * Attach events from component-defined events map.
  55712. */
  55713. eventsAttach: function () {
  55714. var eventName;
  55715. // Safety detach to prevent double-registration.
  55716. this.eventsDetach();
  55717. for (eventName in this.events) {
  55718. this.el.addEventListener(eventName, this.events[eventName]);
  55719. }
  55720. },
  55721. /**
  55722. * Detach events from component-defined events map.
  55723. */
  55724. eventsDetach: function () {
  55725. var eventName;
  55726. for (eventName in this.events) {
  55727. this.el.removeEventListener(eventName, this.events[eventName]);
  55728. }
  55729. },
  55730. /**
  55731. * Release and free memory.
  55732. */
  55733. destroy: function () {
  55734. this.objectPool.recycle(this.attrValue);
  55735. this.objectPool.recycle(this.oldData);
  55736. this.objectPool.recycle(this.parsingAttrValue);
  55737. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  55738. }
  55739. };
  55740. function eventsBind (component, events) {
  55741. var eventName;
  55742. for (eventName in events) {
  55743. component.events[eventName] = events[eventName].bind(component);
  55744. }
  55745. }
  55746. // For testing.
  55747. if (window.debug) {
  55748. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  55749. }
  55750. /**
  55751. * Register a component to A-Frame.
  55752. *
  55753. * @param {string} name - Component name.
  55754. * @param {object} definition - Component schema and lifecycle method handlers.
  55755. * @returns {object} Component.
  55756. */
  55757. module.exports.registerComponent = function (name, definition) {
  55758. var NewComponent;
  55759. var propertyName;
  55760. var proto = {};
  55761. var schema;
  55762. var schemaIsSingleProp;
  55763. // Warning if component is statically registered after the scene.
  55764. if (document.currentScript && document.currentScript !== aframeScript) {
  55765. scenes.forEach(function checkPosition (sceneEl) {
  55766. // Okay to register component after the scene at runtime.
  55767. if (sceneEl.hasLoaded) { return; }
  55768. // Check that component is declared before the scene.
  55769. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  55770. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  55771. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  55772. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  55773. 'such that the component is available to entities during scene initialization.');
  55774. // For testing.
  55775. if (window.debug) { registrationOrderWarnings[name] = true; }
  55776. });
  55777. }
  55778. if (upperCaseRegExp.test(name) === true) {
  55779. warn('The component name `' + name + '` contains uppercase characters, but ' +
  55780. 'HTML will ignore the capitalization of attribute names. ' +
  55781. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  55782. }
  55783. if (name.indexOf('__') !== -1) {
  55784. throw new Error('The component name `' + name + '` is not allowed. ' +
  55785. 'The sequence __ (double underscore) is reserved to specify an id' +
  55786. ' for multiple components of the same type');
  55787. }
  55788. // Format definition object to prototype object.
  55789. Object.keys(definition).forEach(function (key) {
  55790. proto[key] = {
  55791. value: definition[key],
  55792. writable: true
  55793. };
  55794. });
  55795. if (components[name]) {
  55796. throw new Error('The component `' + name + '` has been already registered. ' +
  55797. 'Check that you are not loading two versions of the same component ' +
  55798. 'or two different components of the same name.');
  55799. }
  55800. NewComponent = function (el, attr, id) {
  55801. Component.call(this, el, attr, id);
  55802. };
  55803. NewComponent.prototype = Object.create(Component.prototype, proto);
  55804. NewComponent.prototype.name = name;
  55805. NewComponent.prototype.isPositionRotationScale =
  55806. name === 'position' || name === 'rotation' || name === 'scale';
  55807. NewComponent.prototype.constructor = NewComponent;
  55808. NewComponent.prototype.system = systems && systems.systems[name];
  55809. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  55810. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  55811. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  55812. NewComponent.prototype.name));
  55813. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  55814. // Keep track of keys that may potentially change the schema.
  55815. if (!schemaIsSingleProp) {
  55816. NewComponent.prototype.schemaChangeKeys = [];
  55817. for (propertyName in schema) {
  55818. if (schema[propertyName].schemaChange) {
  55819. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  55820. }
  55821. }
  55822. }
  55823. // Create object pool for class of components.
  55824. objectPools[name] = utils.objectPool.createPool();
  55825. components[name] = {
  55826. Component: NewComponent,
  55827. dependencies: NewComponent.prototype.dependencies,
  55828. isSingleProp: schemaIsSingleProp,
  55829. multiple: NewComponent.prototype.multiple,
  55830. name: name,
  55831. parse: NewComponent.prototype.parse,
  55832. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  55833. schema: schema,
  55834. stringify: NewComponent.prototype.stringify,
  55835. type: NewComponent.prototype.type
  55836. };
  55837. return NewComponent;
  55838. };
  55839. /**
  55840. * Clone component data.
  55841. * Clone only the properties that are plain objects while keeping a reference for the rest.
  55842. *
  55843. * @param data - Component data to clone.
  55844. * @returns Cloned data.
  55845. */
  55846. function copyData (dest, sourceData) {
  55847. var parsedProperty;
  55848. var key;
  55849. for (key in sourceData) {
  55850. if (sourceData[key] === undefined) { continue; }
  55851. parsedProperty = sourceData[key];
  55852. dest[key] = isObjectOrArray(parsedProperty)
  55853. ? utils.clone(parsedProperty)
  55854. : parsedProperty;
  55855. }
  55856. return dest;
  55857. }
  55858. /**
  55859. * Object extending with checking for single-property schema.
  55860. *
  55861. * @param dest - Destination object or value.
  55862. * @param source - Source object or value
  55863. * @param {boolean} isObjectBased - Whether values are objects.
  55864. * @returns Overridden object or value.
  55865. */
  55866. function extendProperties (dest, source, isObjectBased) {
  55867. var key;
  55868. if (isObjectBased && source.constructor === Object) {
  55869. for (key in source) {
  55870. if (source[key] === undefined) { continue; }
  55871. if (source[key] && source[key].constructor === Object) {
  55872. dest[key] = utils.clone(source[key]);
  55873. } else {
  55874. dest[key] = source[key];
  55875. }
  55876. }
  55877. return dest;
  55878. }
  55879. return source;
  55880. }
  55881. /**
  55882. * Checks if a component has defined a method that needs to run every frame.
  55883. */
  55884. function hasBehavior (component) {
  55885. return component.tick || component.tock;
  55886. }
  55887. /**
  55888. * Wrapper for defined pause method.
  55889. * Pause component by removing tick behavior and calling user's pause method.
  55890. *
  55891. * @param pauseMethod {function}
  55892. */
  55893. function wrapPause (pauseMethod) {
  55894. return function pause () {
  55895. var sceneEl = this.el.sceneEl;
  55896. if (!this.isPlaying) { return; }
  55897. pauseMethod.call(this);
  55898. this.isPlaying = false;
  55899. this.eventsDetach();
  55900. // Remove tick behavior.
  55901. if (!hasBehavior(this)) { return; }
  55902. sceneEl.removeBehavior(this);
  55903. };
  55904. }
  55905. /**
  55906. * Wrapper for defined play method.
  55907. * Play component by adding tick behavior and calling user's play method.
  55908. *
  55909. * @param playMethod {function}
  55910. */
  55911. function wrapPlay (playMethod) {
  55912. return function play () {
  55913. var sceneEl = this.el.sceneEl;
  55914. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  55915. if (!this.initialized || !shouldPlay) { return; }
  55916. playMethod.call(this);
  55917. this.isPlaying = true;
  55918. this.eventsAttach();
  55919. // Add tick behavior.
  55920. if (!hasBehavior(this)) { return; }
  55921. sceneEl.addBehavior(this);
  55922. };
  55923. }
  55924. function isObject (value) {
  55925. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  55926. }
  55927. function isObjectOrArray (value) {
  55928. return value && (value.constructor === Object || value.constructor === Array) &&
  55929. !(value instanceof window.HTMLElement);
  55930. }
  55931. },{"../utils/":210,"./scene/scenes":142,"./schema":144,"./system":146}],136:[function(require,module,exports){
  55932. var schema = require('./schema');
  55933. var processSchema = schema.process;
  55934. var geometries = module.exports.geometries = {}; // Registered geometries.
  55935. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  55936. var THREE = require('../lib/three');
  55937. /**
  55938. * Geometry class definition.
  55939. *
  55940. * Geometries extend the geometry component API to create and register geometry types.
  55941. */
  55942. var Geometry = module.exports.Geometry = function () {};
  55943. Geometry.prototype = {
  55944. /**
  55945. * Contains the type schema and defaults for the data values.
  55946. * Data is coerced into the types of the values of the defaults.
  55947. */
  55948. schema: {},
  55949. /**
  55950. * Init handler. Similar to attachedCallback.
  55951. * Called during shader initialization and is only run once.
  55952. */
  55953. init: function (data) {
  55954. this.geometry = new THREE.BufferGeometry();
  55955. return this.geometry;
  55956. },
  55957. /**
  55958. * Update handler. Similar to attributeChangedCallback.
  55959. * Called whenever the associated geometry data changes.
  55960. *
  55961. * @param {object} data - New geometry data.
  55962. */
  55963. update: function (data) { /* no-op */ }
  55964. };
  55965. /**
  55966. * Registers a geometry to A-Frame.
  55967. *
  55968. * @param {string} name - Geometry name.
  55969. * @param {object} definition - Geometry property and methods.
  55970. * @returns {object} Geometry.
  55971. */
  55972. module.exports.registerGeometry = function (name, definition) {
  55973. var NewGeometry;
  55974. var proto = {};
  55975. // Format definition object to prototype object.
  55976. Object.keys(definition).forEach(function expandDefinition (key) {
  55977. proto[key] = {
  55978. value: definition[key],
  55979. writable: true
  55980. };
  55981. });
  55982. if (geometries[name]) {
  55983. throw new Error('The geometry `' + name + '` has been already registered');
  55984. }
  55985. NewGeometry = function () { Geometry.call(this); };
  55986. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  55987. NewGeometry.prototype.name = name;
  55988. NewGeometry.prototype.constructor = NewGeometry;
  55989. geometries[name] = {
  55990. Geometry: NewGeometry,
  55991. schema: processSchema(NewGeometry.prototype.schema)
  55992. };
  55993. geometryNames.push(name);
  55994. return NewGeometry;
  55995. };
  55996. },{"../lib/three":183,"./schema":144}],137:[function(require,module,exports){
  55997. var coordinates = require('../utils/coordinates');
  55998. var debug = require('debug');
  55999. var error = debug('core:propertyTypes:warn');
  56000. var warn = debug('core:propertyTypes:warn');
  56001. var propertyTypes = module.exports.propertyTypes = {};
  56002. var nonCharRegex = /[,> .[\]:]/;
  56003. var urlRegex = /\url\((.+)\)/;
  56004. // Built-in property types.
  56005. registerPropertyType('audio', '', assetParse);
  56006. registerPropertyType('array', [], arrayParse, arrayStringify);
  56007. registerPropertyType('asset', '', assetParse);
  56008. registerPropertyType('boolean', false, boolParse);
  56009. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  56010. registerPropertyType('int', 0, intParse);
  56011. registerPropertyType('number', 0, numberParse);
  56012. registerPropertyType('map', '', assetParse);
  56013. registerPropertyType('model', '', assetParse);
  56014. registerPropertyType('selector', null, selectorParse, selectorStringify);
  56015. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  56016. registerPropertyType('src', '', srcParse);
  56017. registerPropertyType('string', '', defaultParse, defaultStringify);
  56018. registerPropertyType('time', 0, intParse);
  56019. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  56020. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  56021. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  56022. /**
  56023. * Register a parser for re-use such that when someone uses `type` in the schema,
  56024. * `schema.process` will set the property `parse` and `stringify`.
  56025. *
  56026. * @param {string} type - Type name.
  56027. * @param [defaultValue=null] -
  56028. * Default value to use if component does not define default value.
  56029. * @param {function} [parse=defaultParse] - Parse string function.
  56030. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  56031. */
  56032. function registerPropertyType (type, defaultValue, parse, stringify) {
  56033. if ('type' in propertyTypes) {
  56034. error('Property type ' + type + ' is already registered.');
  56035. return;
  56036. }
  56037. propertyTypes[type] = {
  56038. default: defaultValue,
  56039. parse: parse || defaultParse,
  56040. stringify: stringify || defaultStringify
  56041. };
  56042. }
  56043. module.exports.registerPropertyType = registerPropertyType;
  56044. function arrayParse (value) {
  56045. if (Array.isArray(value)) { return value; }
  56046. if (!value || typeof value !== 'string') { return []; }
  56047. return value.split(',').map(trim);
  56048. function trim (str) { return str.trim(); }
  56049. }
  56050. function arrayStringify (value) {
  56051. return value.join(', ');
  56052. }
  56053. /**
  56054. * For general assets.
  56055. *
  56056. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  56057. * just string.
  56058. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  56059. * just string.
  56060. */
  56061. function assetParse (value) {
  56062. var el;
  56063. var parsedUrl;
  56064. // If an element was provided (e.g. canvas or video), just return it.
  56065. if (typeof value !== 'string') { return value; }
  56066. // Wrapped `url()` in case of data URI.
  56067. parsedUrl = value.match(urlRegex);
  56068. if (parsedUrl) { return parsedUrl[1]; }
  56069. // ID.
  56070. if (value.charAt(0) === '#') {
  56071. el = document.getElementById(value.substring(1));
  56072. if (el) {
  56073. // Pass through media elements. If we have the elements, we don't have to call
  56074. // three.js loaders which would re-request the assets.
  56075. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  56076. return el;
  56077. }
  56078. return el.getAttribute('src');
  56079. }
  56080. warn('"' + value + '" asset not found.');
  56081. return;
  56082. }
  56083. // Non-wrapped url().
  56084. return value;
  56085. }
  56086. function defaultParse (value) {
  56087. return value;
  56088. }
  56089. function defaultStringify (value) {
  56090. if (value === null) { return 'null'; }
  56091. return value.toString();
  56092. }
  56093. function boolParse (value) {
  56094. return value !== 'false' && value !== false;
  56095. }
  56096. function intParse (value) {
  56097. return parseInt(value, 10);
  56098. }
  56099. function numberParse (value) {
  56100. return parseFloat(value, 10);
  56101. }
  56102. function selectorParse (value) {
  56103. if (!value) { return null; }
  56104. if (typeof value !== 'string') { return value; }
  56105. if (value[0] === '#' && !nonCharRegex.test(value)) {
  56106. // When selecting element by ID only, use getElementById for better performance.
  56107. // Don't match like #myId .child.
  56108. return document.getElementById(value.substring(1));
  56109. }
  56110. return document.querySelector(value);
  56111. }
  56112. function selectorAllParse (value) {
  56113. if (!value) { return null; }
  56114. if (typeof value !== 'string') { return value; }
  56115. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  56116. }
  56117. function selectorStringify (value) {
  56118. if (value.getAttribute) {
  56119. return '#' + value.getAttribute('id');
  56120. }
  56121. return defaultStringify(value);
  56122. }
  56123. function selectorAllStringify (value) {
  56124. if (value instanceof Array) {
  56125. return value.map(function (element) {
  56126. return '#' + element.getAttribute('id');
  56127. }).join(', ');
  56128. }
  56129. return defaultStringify(value);
  56130. }
  56131. function srcParse (value) {
  56132. warn('`src` property type is deprecated. Use `asset` instead.');
  56133. return assetParse(value);
  56134. }
  56135. function vecParse (value) {
  56136. return coordinates.parse(value, this.default);
  56137. }
  56138. /**
  56139. * Validate the default values in a schema to match their type.
  56140. *
  56141. * @param {string} type - Property type name.
  56142. * @param defaultVal - Property type default value.
  56143. * @returns {boolean} Whether default value is accurate given the type.
  56144. */
  56145. function isValidDefaultValue (type, defaultVal) {
  56146. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  56147. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  56148. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  56149. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  56150. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  56151. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  56152. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  56153. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  56154. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  56155. if (type === 'selector' && typeof defaultVal !== 'string' &&
  56156. defaultVal !== null) { return false; }
  56157. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  56158. defaultVal !== null) { return false; }
  56159. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  56160. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  56161. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  56162. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  56163. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  56164. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  56165. return true;
  56166. }
  56167. module.exports.isValidDefaultValue = isValidDefaultValue;
  56168. /**
  56169. * Checks if default coordinates are valid.
  56170. *
  56171. * @param possibleCoordinates
  56172. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  56173. * @returns {boolean} Whether coordinates are parsed correctly.
  56174. */
  56175. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  56176. if (possibleCoordinates === null) { return true; }
  56177. if (typeof possibleCoordinates !== 'object') { return false; }
  56178. if (Object.keys(possibleCoordinates).length !== dimensions) {
  56179. return false;
  56180. } else {
  56181. var x = possibleCoordinates.x;
  56182. var y = possibleCoordinates.y;
  56183. var z = possibleCoordinates.z;
  56184. var w = possibleCoordinates.w;
  56185. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  56186. if (dimensions > 2 && typeof z !== 'number') { return false; }
  56187. if (dimensions > 3 && typeof w !== 'number') { return false; }
  56188. }
  56189. return true;
  56190. }
  56191. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  56192. },{"../utils/coordinates":205,"debug":8}],138:[function(require,module,exports){
  56193. /* global Promise, screen, CustomEvent */
  56194. var initMetaTags = require('./metaTags').inject;
  56195. var initWakelock = require('./wakelock');
  56196. var loadingScreen = require('./loadingScreen');
  56197. var re = require('../a-register-element');
  56198. var scenes = require('./scenes');
  56199. var systems = require('../system').systems;
  56200. var THREE = require('../../lib/three');
  56201. var utils = require('../../utils/');
  56202. // Require after.
  56203. var AEntity = require('../a-entity');
  56204. var ANode = require('../a-node');
  56205. var initPostMessageAPI = require('./postMessage');
  56206. var bind = utils.bind;
  56207. var isIOS = utils.device.isIOS();
  56208. var isMobile = utils.device.isMobile();
  56209. var isWebXRAvailable = utils.device.isWebXRAvailable;
  56210. var registerElement = re.registerElement;
  56211. var warn = utils.debug('core:a-scene:warn');
  56212. if (isIOS) { require('../../utils/ios-orientationchange-blank-bug'); }
  56213. /**
  56214. * Scene element, holds all entities.
  56215. *
  56216. * @member {array} behaviors - Component instances that have registered themselves to be
  56217. updated on every tick.
  56218. * @member {object} camera - three.js Camera object.
  56219. * @member {object} canvas
  56220. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  56221. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  56222. * @member {object} object3D - Root three.js Scene object.
  56223. * @member {object} renderer
  56224. * @member {bool} renderStarted
  56225. * @member {object} systems - Registered instantiated systems.
  56226. * @member {number} time
  56227. */
  56228. module.exports.AScene = registerElement('a-scene', {
  56229. prototype: Object.create(AEntity.prototype, {
  56230. createdCallback: {
  56231. value: function () {
  56232. this.clock = new THREE.Clock();
  56233. this.isIOS = isIOS;
  56234. this.isMobile = isMobile;
  56235. this.hasWebXR = isWebXRAvailable;
  56236. this.isAR = false;
  56237. this.isScene = true;
  56238. this.object3D = new THREE.Scene();
  56239. var self = this;
  56240. this.object3D.onAfterRender = function (renderer, scene, camera) {
  56241. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  56242. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  56243. };
  56244. this.resize = bind(this.resize, this);
  56245. this.render = bind(this.render, this);
  56246. this.systems = {};
  56247. this.systemNames = [];
  56248. this.time = this.delta = 0;
  56249. this.behaviors = {tick: [], tock: []};
  56250. this.hasLoaded = false;
  56251. this.isPlaying = false;
  56252. this.originalHTML = this.innerHTML;
  56253. // Default components.
  56254. this.setAttribute('inspector', '');
  56255. this.setAttribute('keyboard-shortcuts', '');
  56256. this.setAttribute('screenshot', '');
  56257. this.setAttribute('vr-mode-ui', '');
  56258. this.setAttribute('device-orientation-permission-ui', '');
  56259. }
  56260. },
  56261. addFullScreenStyles: {
  56262. value: function () {
  56263. document.documentElement.classList.add('a-fullscreen');
  56264. }
  56265. },
  56266. removeFullScreenStyles: {
  56267. value: function () {
  56268. document.documentElement.classList.remove('a-fullscreen');
  56269. }
  56270. },
  56271. attachedCallback: {
  56272. value: function () {
  56273. var self = this;
  56274. var embedded = this.hasAttribute('embedded');
  56275. // Renderer initialization
  56276. setupCanvas(this);
  56277. this.setupRenderer();
  56278. loadingScreen.setup(this, getCanvasSize);
  56279. this.resize();
  56280. if (!embedded) { this.addFullScreenStyles(); }
  56281. initPostMessageAPI(this);
  56282. initMetaTags(this);
  56283. initWakelock(this);
  56284. // Handler to exit VR (e.g., Oculus Browser back button).
  56285. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  56286. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56287. // Bind functions.
  56288. this.enterVRBound = function () { self.enterVR(); };
  56289. this.exitVRBound = function () { self.exitVR(); };
  56290. this.exitVRTrueBound = function () { self.exitVR(true); };
  56291. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  56292. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  56293. if (!isWebXRAvailable) {
  56294. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  56295. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  56296. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  56297. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56298. // Register for mouse restricted events while in VR
  56299. // (e.g. mouse no longer available on desktop 2D view)
  56300. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56301. // Register for mouse unrestricted events while in VR
  56302. // (e.g. mouse once again available on desktop 2D view)
  56303. window.addEventListener('vrdisplaypointerunrestricted',
  56304. this.pointerUnrestrictedBound);
  56305. }
  56306. window.addEventListener('sessionend', this.resize);
  56307. // Camera set up by camera system.
  56308. this.addEventListener('cameraready', function () {
  56309. self.attachedCallbackPostCamera();
  56310. });
  56311. this.initSystems();
  56312. // WebXR Immersive navigation handler.
  56313. if (this.hasWebXR && navigator.xr && navigator.xr.addEventListener) {
  56314. navigator.xr.addEventListener('sessiongranted', function () { self.enterVR(); });
  56315. }
  56316. }
  56317. },
  56318. attachedCallbackPostCamera: {
  56319. value: function () {
  56320. var resize;
  56321. var self = this;
  56322. window.addEventListener('load', resize);
  56323. window.addEventListener('resize', function () {
  56324. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  56325. // where the window does not contain the correct viewport size
  56326. // after an orientation change. The window size is correct if the operation
  56327. // is postponed a few milliseconds.
  56328. // self.resize can be called directly once the bug above is fixed.
  56329. if (self.isIOS) {
  56330. setTimeout(self.resize, 100);
  56331. } else {
  56332. self.resize();
  56333. }
  56334. });
  56335. this.play();
  56336. // Add to scene index.
  56337. scenes.push(this);
  56338. },
  56339. writable: window.debug
  56340. },
  56341. /**
  56342. * Initialize all systems.
  56343. */
  56344. initSystems: {
  56345. value: function () {
  56346. var name;
  56347. // Initialize camera system first.
  56348. this.initSystem('camera');
  56349. for (name in systems) {
  56350. if (name === 'camera') { continue; }
  56351. this.initSystem(name);
  56352. }
  56353. }
  56354. },
  56355. /**
  56356. * Initialize a system.
  56357. */
  56358. initSystem: {
  56359. value: function (name) {
  56360. if (this.systems[name]) { return; }
  56361. this.systems[name] = new systems[name](this);
  56362. this.systemNames.push(name);
  56363. }
  56364. },
  56365. /**
  56366. * Shut down scene on detach.
  56367. */
  56368. detachedCallback: {
  56369. value: function () {
  56370. // Remove from scene index.
  56371. var sceneIndex = scenes.indexOf(this);
  56372. scenes.splice(sceneIndex, 1);
  56373. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56374. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  56375. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  56376. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  56377. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56378. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56379. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  56380. window.removeEventListener('sessionend', this.resize);
  56381. this.renderer.xr.dispose();
  56382. }
  56383. },
  56384. /**
  56385. * Add ticks and tocks.
  56386. *
  56387. * @param {object} behavior - A component.
  56388. */
  56389. addBehavior: {
  56390. value: function (behavior) {
  56391. var behaviorArr;
  56392. var behaviors = this.behaviors;
  56393. var behaviorType;
  56394. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  56395. for (behaviorType in behaviors) {
  56396. if (!behavior[behaviorType]) { continue; }
  56397. behaviorArr = this.behaviors[behaviorType];
  56398. if (behaviorArr.indexOf(behavior) === -1) {
  56399. behaviorArr.push(behavior);
  56400. }
  56401. }
  56402. }
  56403. },
  56404. /**
  56405. * For tests.
  56406. */
  56407. getPointerLockElement: {
  56408. value: function () {
  56409. return document.pointerLockElement;
  56410. },
  56411. writable: window.debug
  56412. },
  56413. /**
  56414. * For tests.
  56415. */
  56416. checkHeadsetConnected: {
  56417. value: utils.device.checkHeadsetConnected,
  56418. writable: window.debug
  56419. },
  56420. enterAR: {
  56421. value: function () {
  56422. var errorMessage;
  56423. if (!this.hasWebXR) {
  56424. errorMessage = 'Failed to enter AR mode, WebXR not supported.';
  56425. throw new Error(errorMessage);
  56426. }
  56427. if (!utils.device.checkARSupport()) {
  56428. errorMessage = 'Failed to enter AR, WebXR immersive-ar mode not supported in your browser or device.';
  56429. throw new Error(errorMessage);
  56430. }
  56431. return this.enterVR(true);
  56432. }
  56433. },
  56434. /**
  56435. * Call `requestPresent` if WebVR or WebVR polyfill.
  56436. * Call `requestFullscreen` on desktop.
  56437. * Handle events, states, fullscreen styles.
  56438. *
  56439. * @param {bool?} useAR - if true, try immersive-ar mode
  56440. * @returns {Promise}
  56441. */
  56442. enterVR: {
  56443. value: function (useAR) {
  56444. var self = this;
  56445. var vrDisplay;
  56446. var vrManager = self.renderer.xr;
  56447. var xrInit;
  56448. // Don't enter VR if already in VR.
  56449. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  56450. // Has VR.
  56451. if (this.checkHeadsetConnected() || this.isMobile) {
  56452. vrManager.enabled = true;
  56453. if (this.hasWebXR) {
  56454. // XR API.
  56455. if (this.xrSession) {
  56456. this.xrSession.removeEventListener('end', this.exitVRBound);
  56457. }
  56458. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  56459. vrManager.setReferenceSpaceType(refspace);
  56460. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  56461. xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  56462. return new Promise(function (resolve, reject) {
  56463. navigator.xr.requestSession(xrMode, xrInit).then(
  56464. function requestSuccess (xrSession) {
  56465. self.xrSession = xrSession;
  56466. vrManager.layersEnabled = xrInit.requiredFeatures.indexOf('layers') !== -1;
  56467. vrManager.setSession(xrSession);
  56468. xrSession.addEventListener('end', self.exitVRBound);
  56469. enterVRSuccess(resolve);
  56470. },
  56471. function requestFail (error) {
  56472. var useAR = xrMode === 'immersive-ar';
  56473. var mode = useAR ? 'AR' : 'VR';
  56474. throw new Error('Failed to enter ' + mode + ' mode (`requestSession`) ' + error);
  56475. }
  56476. );
  56477. });
  56478. } else {
  56479. vrDisplay = utils.device.getVRDisplay();
  56480. vrManager.setDevice(vrDisplay);
  56481. if (vrDisplay.isPresenting &&
  56482. !window.hasNativeWebVRImplementation) {
  56483. enterVRSuccess();
  56484. return Promise.resolve();
  56485. }
  56486. var rendererSystem = this.getAttribute('renderer');
  56487. var presentationAttributes = {
  56488. highRefreshRate: rendererSystem.highRefreshRate,
  56489. foveationLevel: rendererSystem.foveationLevel
  56490. };
  56491. return vrDisplay.requestPresent([{
  56492. source: this.canvas,
  56493. attributes: presentationAttributes
  56494. }]).then(enterVRSuccess, enterVRFailure);
  56495. }
  56496. }
  56497. // No VR.
  56498. enterVRSuccess();
  56499. return Promise.resolve();
  56500. // Callback that happens on enter VR success or enter fullscreen (any API).
  56501. function enterVRSuccess (resolve) {
  56502. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  56503. // the first requestPresent could be called from ondisplayactivate and there is no way
  56504. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  56505. // for the actual requestPresent. Need to make sure there are no issues with firing the
  56506. // vrdisplaypresentchange multiple times.
  56507. var event;
  56508. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  56509. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  56510. window.dispatchEvent(event);
  56511. }
  56512. if (useAR) {
  56513. self.addState('ar-mode');
  56514. } else {
  56515. self.addState('vr-mode');
  56516. }
  56517. self.emit('enter-vr', {target: self});
  56518. // Lock to landscape orientation on mobile.
  56519. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  56520. screen.orientation.lock('landscape');
  56521. }
  56522. self.addFullScreenStyles();
  56523. // On mobile, the polyfill handles fullscreen.
  56524. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  56525. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  56526. // connected.
  56527. if (!self.isMobile && !self.checkHeadsetConnected()) {
  56528. requestFullscreen(self.canvas);
  56529. }
  56530. self.resize();
  56531. if (resolve) { resolve(); }
  56532. }
  56533. function enterVRFailure (err) {
  56534. self.removeState('vr-mode');
  56535. if (err && err.message) {
  56536. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  56537. } else {
  56538. throw new Error('Failed to enter VR mode (`requestPresent`).');
  56539. }
  56540. }
  56541. },
  56542. writable: true
  56543. },
  56544. /**
  56545. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  56546. * Handle events, states, fullscreen styles.
  56547. *
  56548. * @returns {Promise}
  56549. */
  56550. exitVR: {
  56551. value: function () {
  56552. var self = this;
  56553. var vrDisplay;
  56554. var vrManager = this.renderer.xr;
  56555. // Don't exit VR if not in VR.
  56556. if (!this.is('vr-mode') && !this.is('ar-mode')) { return Promise.resolve('Not in immersive mode.'); }
  56557. // Handle exiting VR if not yet already and in a headset or polyfill.
  56558. if (this.checkHeadsetConnected() || this.isMobile) {
  56559. vrManager.enabled = false;
  56560. vrDisplay = utils.device.getVRDisplay();
  56561. if (this.hasWebXR) {
  56562. this.xrSession.removeEventListener('end', this.exitVRBound);
  56563. // Capture promise to avoid errors.
  56564. this.xrSession.end().then(function () {}, function () {});
  56565. this.xrSession = undefined;
  56566. vrManager.setSession(null);
  56567. } else {
  56568. if (vrDisplay.isPresenting) {
  56569. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  56570. }
  56571. }
  56572. } else {
  56573. exitFullscreen();
  56574. }
  56575. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  56576. exitVRSuccess();
  56577. return Promise.resolve();
  56578. function exitVRSuccess () {
  56579. self.removeState('vr-mode');
  56580. self.removeState('ar-mode');
  56581. // Lock to landscape orientation on mobile.
  56582. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  56583. screen.orientation.unlock();
  56584. }
  56585. // Exiting VR in embedded mode, no longer need fullscreen styles.
  56586. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  56587. self.resize();
  56588. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  56589. self.renderer.setPixelRatio(window.devicePixelRatio);
  56590. self.emit('exit-vr', {target: self});
  56591. }
  56592. function exitVRFailure (err) {
  56593. if (err && err.message) {
  56594. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  56595. } else {
  56596. throw new Error('Failed to exit VR mode (`exitPresent`).');
  56597. }
  56598. }
  56599. },
  56600. writable: true
  56601. },
  56602. pointerRestricted: {
  56603. value: function () {
  56604. if (this.canvas) {
  56605. var pointerLockElement = this.getPointerLockElement();
  56606. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  56607. // Recreate pointer lock on the canvas, if taken on another element.
  56608. document.exitPointerLock();
  56609. }
  56610. if (this.canvas.requestPointerLock) {
  56611. this.canvas.requestPointerLock();
  56612. }
  56613. }
  56614. }
  56615. },
  56616. pointerUnrestricted: {
  56617. value: function () {
  56618. var pointerLockElement = this.getPointerLockElement();
  56619. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  56620. document.exitPointerLock();
  56621. }
  56622. }
  56623. },
  56624. /**
  56625. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  56626. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  56627. */
  56628. onVRPresentChange: {
  56629. value: function (evt) {
  56630. // Polyfill places display inside the detail property
  56631. var display = evt.display || evt.detail.display;
  56632. // Entering VR.
  56633. if (display && display.isPresenting) {
  56634. this.enterVR();
  56635. return;
  56636. }
  56637. // Exiting VR.
  56638. this.exitVR();
  56639. }
  56640. },
  56641. /**
  56642. * Wraps Entity.getAttribute to take into account for systems.
  56643. * If system exists, then return system data rather than possible component data.
  56644. */
  56645. getAttribute: {
  56646. value: function (attr) {
  56647. var system = this.systems[attr];
  56648. if (system) { return system.data; }
  56649. return AEntity.prototype.getAttribute.call(this, attr);
  56650. }
  56651. },
  56652. /**
  56653. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  56654. * what `getAttribute` is now. Now legacy code.
  56655. */
  56656. getComputedAttribute: {
  56657. value: function (attr) {
  56658. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  56659. this.getAttribute(attr);
  56660. }
  56661. },
  56662. /**
  56663. * Wraps Entity.getDOMAttribute to take into account for systems.
  56664. * If system exists, then return system data rather than possible component data.
  56665. */
  56666. getDOMAttribute: {
  56667. value: function (attr) {
  56668. var system = this.systems[attr];
  56669. if (system) { return system.data; }
  56670. return AEntity.prototype.getDOMAttribute.call(this, attr);
  56671. }
  56672. },
  56673. /**
  56674. * Wrap Entity.setAttribute to take into account for systems.
  56675. * If system exists, then skip component initialization checks and do a normal
  56676. * setAttribute.
  56677. */
  56678. setAttribute: {
  56679. value: function (attr, value, componentPropValue) {
  56680. var system = this.systems[attr];
  56681. if (system) {
  56682. ANode.prototype.setAttribute.call(this, attr, value);
  56683. system.updateProperties(value);
  56684. return;
  56685. }
  56686. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  56687. }
  56688. },
  56689. /**
  56690. * @param {object} behavior - A component.
  56691. */
  56692. removeBehavior: {
  56693. value: function (behavior) {
  56694. var behaviorArr;
  56695. var behaviorType;
  56696. var behaviors = this.behaviors;
  56697. var index;
  56698. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  56699. // array.
  56700. for (behaviorType in behaviors) {
  56701. if (!behavior[behaviorType]) { continue; }
  56702. behaviorArr = this.behaviors[behaviorType];
  56703. index = behaviorArr.indexOf(behavior);
  56704. if (index !== -1) { behaviorArr.splice(index, 1); }
  56705. }
  56706. }
  56707. },
  56708. resize: {
  56709. value: function () {
  56710. var camera = this.camera;
  56711. var canvas = this.canvas;
  56712. var embedded;
  56713. var isVRPresenting;
  56714. var size;
  56715. var isPresenting = this.renderer.xr.isPresenting;
  56716. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  56717. // Do not update renderer, if a camera or a canvas have not been injected.
  56718. // In VR mode, three handles canvas resize based on the dimensions returned by
  56719. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  56720. // the window size, therefore should not be overwritten with the window's width and
  56721. // height, // except when in fullscreen mode.
  56722. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  56723. return;
  56724. }
  56725. // Update camera.
  56726. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  56727. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  56728. camera.aspect = size.width / size.height;
  56729. camera.updateProjectionMatrix();
  56730. // Notify renderer of size change.
  56731. this.renderer.setSize(size.width, size.height, false);
  56732. this.emit('rendererresize', null, false);
  56733. },
  56734. writable: true
  56735. },
  56736. setupRenderer: {
  56737. value: function () {
  56738. var self = this;
  56739. var renderer;
  56740. var rendererAttr;
  56741. var rendererAttrString;
  56742. var rendererConfig;
  56743. rendererConfig = {
  56744. alpha: true,
  56745. antialias: !isMobile,
  56746. canvas: this.canvas,
  56747. logarithmicDepthBuffer: false,
  56748. powerPreference: 'high-performance'
  56749. };
  56750. this.maxCanvasSize = {height: 1920, width: 1920};
  56751. if (this.hasAttribute('renderer')) {
  56752. rendererAttrString = this.getAttribute('renderer');
  56753. rendererAttr = utils.styleParser.parse(rendererAttrString);
  56754. if (rendererAttr.precision) {
  56755. rendererConfig.precision = rendererAttr.precision + 'p';
  56756. }
  56757. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  56758. rendererConfig.antialias = rendererAttr.antialias === 'true';
  56759. }
  56760. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  56761. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  56762. }
  56763. if (rendererAttr.alpha) {
  56764. rendererConfig.alpha = rendererAttr.alpha === 'true';
  56765. }
  56766. this.maxCanvasSize = {
  56767. width: rendererAttr.maxCanvasWidth
  56768. ? parseInt(rendererAttr.maxCanvasWidth)
  56769. : this.maxCanvasSize.width,
  56770. height: rendererAttr.maxCanvasHeight
  56771. ? parseInt(rendererAttr.maxCanvasHeight)
  56772. : this.maxCanvasSize.height
  56773. };
  56774. }
  56775. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  56776. renderer.setPixelRatio(window.devicePixelRatio);
  56777. renderer.sortObjects = false;
  56778. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  56779. this.addEventListener('camera-set-active', function () {
  56780. renderer.xr.setPoseTarget(self.camera.el.object3D);
  56781. });
  56782. },
  56783. writable: window.debug
  56784. },
  56785. /**
  56786. * Handler attached to elements to help scene know when to kick off.
  56787. * Scene waits for all entities to load.
  56788. */
  56789. play: {
  56790. value: function () {
  56791. var self = this;
  56792. var sceneEl = this;
  56793. if (this.renderStarted) {
  56794. AEntity.prototype.play.call(this);
  56795. return;
  56796. }
  56797. this.addEventListener('loaded', function () {
  56798. var renderer = this.renderer;
  56799. var vrDisplay;
  56800. var vrManager = this.renderer.xr;
  56801. AEntity.prototype.play.call(this); // .play() *before* render.
  56802. if (sceneEl.renderStarted) { return; }
  56803. sceneEl.resize();
  56804. // Kick off render loop.
  56805. if (sceneEl.renderer) {
  56806. if (window.performance) { window.performance.mark('render-started'); }
  56807. loadingScreen.remove();
  56808. vrDisplay = utils.device.getVRDisplay();
  56809. if (vrDisplay && vrDisplay.isPresenting) {
  56810. vrManager.setDevice(vrDisplay);
  56811. vrManager.enabled = true;
  56812. sceneEl.enterVR();
  56813. }
  56814. renderer.setAnimationLoop(this.render);
  56815. sceneEl.renderStarted = true;
  56816. sceneEl.emit('renderstart');
  56817. }
  56818. });
  56819. // setTimeout to wait for all nodes to attach and run their callbacks.
  56820. setTimeout(function () {
  56821. AEntity.prototype.load.call(self);
  56822. });
  56823. }
  56824. },
  56825. /**
  56826. * Wrap `updateComponent` to not initialize the component if the component has a system
  56827. * (aframevr/aframe#2365).
  56828. */
  56829. updateComponent: {
  56830. value: function (componentName) {
  56831. if (componentName in systems) { return; }
  56832. AEntity.prototype.updateComponent.apply(this, arguments);
  56833. }
  56834. },
  56835. /**
  56836. * Behavior-updater meant to be called from scene render.
  56837. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  56838. * needing to render.
  56839. */
  56840. tick: {
  56841. value: function (time, timeDelta) {
  56842. var i;
  56843. var systems = this.systems;
  56844. // Components.
  56845. for (i = 0; i < this.behaviors.tick.length; i++) {
  56846. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  56847. this.behaviors.tick[i].tick(time, timeDelta);
  56848. }
  56849. // Systems.
  56850. for (i = 0; i < this.systemNames.length; i++) {
  56851. if (!systems[this.systemNames[i]].tick) { continue; }
  56852. systems[this.systemNames[i]].tick(time, timeDelta);
  56853. }
  56854. }
  56855. },
  56856. /**
  56857. * Behavior-updater meant to be called after scene render for post processing purposes.
  56858. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  56859. * needing to render.
  56860. */
  56861. tock: {
  56862. value: function (time, timeDelta, camera) {
  56863. var i;
  56864. var systems = this.systems;
  56865. // Components.
  56866. for (i = 0; i < this.behaviors.tock.length; i++) {
  56867. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  56868. this.behaviors.tock[i].tock(time, timeDelta, camera);
  56869. }
  56870. // Systems.
  56871. for (i = 0; i < this.systemNames.length; i++) {
  56872. if (!systems[this.systemNames[i]].tock) { continue; }
  56873. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  56874. }
  56875. }
  56876. },
  56877. /**
  56878. * The render loop.
  56879. *
  56880. * Updates animations.
  56881. * Updates behaviors.
  56882. * Renders with request animation frame.
  56883. */
  56884. render: {
  56885. value: function (time, frame) {
  56886. var renderer = this.renderer;
  56887. this.frame = frame;
  56888. this.delta = this.clock.getDelta() * 1000;
  56889. this.time = this.clock.elapsedTime * 1000;
  56890. if (this.isPlaying) { this.tick(this.time, this.delta); }
  56891. var savedBackground = null;
  56892. if (this.is('ar-mode')) {
  56893. // In AR mode, don't render the default background. Hide it, then
  56894. // restore it again after rendering.
  56895. savedBackground = this.object3D.background;
  56896. this.object3D.background = null;
  56897. }
  56898. renderer.render(this.object3D, this.camera);
  56899. if (savedBackground) {
  56900. this.object3D.background = savedBackground;
  56901. }
  56902. },
  56903. writable: true
  56904. }
  56905. })
  56906. });
  56907. /**
  56908. * Return the canvas size where the scene will be rendered.
  56909. * Will be always the window size except when the scene is embedded.
  56910. * The parent size (less than max size) will be returned in that case.
  56911. *
  56912. * @param {object} canvasEl - the canvas element
  56913. * @param {boolean} embedded - Is the scene embedded?
  56914. * @param {object} max - Max size parameters
  56915. * @param {boolean} isVR - If in VR
  56916. */
  56917. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  56918. if (!canvasEl.parentElement) { return {height: 0, width: 0}; }
  56919. if (embedded) {
  56920. return {
  56921. height: canvasEl.parentElement.offsetHeight,
  56922. width: canvasEl.parentElement.offsetWidth
  56923. };
  56924. }
  56925. return getMaxSize(maxSize, isVR);
  56926. }
  56927. /**
  56928. * Return the canvas size. Will be the window size unless that size is greater than the
  56929. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  56930. * maintaining aspect ratio
  56931. *
  56932. * @param {object} maxSize - Max size parameters (width and height).
  56933. * @param {boolean} isVR - If in VR.
  56934. * @returns {object} Width and height.
  56935. */
  56936. function getMaxSize (maxSize, isVR) {
  56937. var aspectRatio;
  56938. var size;
  56939. var pixelRatio = window.devicePixelRatio;
  56940. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  56941. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  56942. return size;
  56943. }
  56944. if (size.width * pixelRatio < maxSize.width &&
  56945. size.height * pixelRatio < maxSize.height) {
  56946. return size;
  56947. }
  56948. aspectRatio = size.width / size.height;
  56949. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  56950. size.width = Math.round(maxSize.width / pixelRatio);
  56951. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  56952. }
  56953. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  56954. size.height = Math.round(maxSize.height / pixelRatio);
  56955. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  56956. }
  56957. return size;
  56958. }
  56959. function requestFullscreen (canvas) {
  56960. var requestFullscreen =
  56961. canvas.requestFullscreen ||
  56962. canvas.webkitRequestFullscreen ||
  56963. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  56964. canvas.msRequestFullscreen;
  56965. // Hide navigation buttons on Android.
  56966. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  56967. }
  56968. function exitFullscreen () {
  56969. var fullscreenEl =
  56970. document.fullscreenElement ||
  56971. document.webkitFullscreenElement ||
  56972. document.mozFullScreenElement;
  56973. if (!fullscreenEl) { return; }
  56974. if (document.exitFullscreen) {
  56975. document.exitFullscreen();
  56976. } else if (document.mozCancelFullScreen) {
  56977. document.mozCancelFullScreen();
  56978. } else if (document.webkitExitFullscreen) {
  56979. document.webkitExitFullscreen();
  56980. }
  56981. }
  56982. function setupCanvas (sceneEl) {
  56983. var canvasEl;
  56984. canvasEl = document.createElement('canvas');
  56985. canvasEl.classList.add('a-canvas');
  56986. // Mark canvas as provided/injected by A-Frame.
  56987. canvasEl.dataset.aframeCanvas = true;
  56988. sceneEl.appendChild(canvasEl);
  56989. document.addEventListener('fullscreenchange', onFullScreenChange);
  56990. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  56991. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  56992. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  56993. // Prevent overscroll on mobile.
  56994. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  56995. // Set canvas on scene.
  56996. sceneEl.canvas = canvasEl;
  56997. sceneEl.emit('render-target-loaded', {target: canvasEl});
  56998. // For unknown reasons a synchronous resize does not work on desktop when
  56999. // entering/exiting fullscreen.
  57000. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  57001. function onFullScreenChange () {
  57002. var fullscreenEl =
  57003. document.fullscreenElement ||
  57004. document.mozFullScreenElement ||
  57005. document.webkitFullscreenElement;
  57006. // No fullscren element === exit fullscreen
  57007. if (!fullscreenEl) { sceneEl.exitVR(); }
  57008. document.activeElement.blur();
  57009. document.body.focus();
  57010. }
  57011. }
  57012. module.exports.setupCanvas = setupCanvas; // For testing.
  57013. },{"../../lib/three":183,"../../utils/":210,"../../utils/ios-orientationchange-blank-bug":211,"../a-entity":131,"../a-node":133,"../a-register-element":134,"../system":146,"./loadingScreen":139,"./metaTags":140,"./postMessage":141,"./scenes":142,"./wakelock":143}],139:[function(require,module,exports){
  57014. /* global THREE */
  57015. var utils = require('../../utils/');
  57016. var styleParser = utils.styleParser;
  57017. var sceneEl;
  57018. var titleEl;
  57019. var getSceneCanvasSize;
  57020. var ATTR_NAME = 'loading-screen';
  57021. var LOADER_TITLE_CLASS = 'a-loader-title';
  57022. module.exports.setup = function setup (el, getCanvasSize) {
  57023. sceneEl = el;
  57024. getSceneCanvasSize = getCanvasSize;
  57025. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  57026. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  57027. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  57028. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  57029. var loaderScene;
  57030. var sphereGeometry;
  57031. var sphereMaterial;
  57032. var sphereMesh1;
  57033. var sphereMesh2;
  57034. var sphereMesh3;
  57035. var camera;
  57036. var clock;
  57037. var time;
  57038. var render;
  57039. if (!loaderEnabled) { return; }
  57040. // Setup Scene.
  57041. loaderScene = new THREE.Scene();
  57042. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  57043. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  57044. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  57045. sphereMesh2 = sphereMesh1.clone();
  57046. sphereMesh3 = sphereMesh1.clone();
  57047. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  57048. clock = new THREE.Clock();
  57049. time = 0;
  57050. render = function () {
  57051. sceneEl.renderer.render(loaderScene, camera);
  57052. time = clock.getElapsedTime() % 4;
  57053. sphereMesh1.visible = time >= 1;
  57054. sphereMesh2.visible = time >= 2;
  57055. sphereMesh3.visible = time >= 3;
  57056. };
  57057. loaderScene.background = new THREE.Color(backgroundColor);
  57058. loaderScene.add(camera);
  57059. sphereMesh1.position.set(-1, 0, -15);
  57060. sphereMesh2.position.set(0, 0, -15);
  57061. sphereMesh3.position.set(1, 0, -15);
  57062. camera.add(sphereMesh1);
  57063. camera.add(sphereMesh2);
  57064. camera.add(sphereMesh3);
  57065. setupTitle();
  57066. // Delay 200ms to avoid loader flashes.
  57067. setTimeout(function () {
  57068. if (sceneEl.hasLoaded) { return; }
  57069. resize(camera);
  57070. titleEl.style.display = 'block';
  57071. window.addEventListener('resize', function () { resize(camera); });
  57072. sceneEl.renderer.setAnimationLoop(render);
  57073. }, 200);
  57074. };
  57075. module.exports.remove = function remove () {
  57076. window.removeEventListener('resize', resize);
  57077. if (!titleEl) { return; }
  57078. // Hide title.
  57079. titleEl.style.display = 'none';
  57080. };
  57081. function resize (camera) {
  57082. var embedded = sceneEl.hasAttribute('embedded');
  57083. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  57084. camera.aspect = size.width / size.height;
  57085. camera.updateProjectionMatrix();
  57086. // Notify renderer of size change.
  57087. sceneEl.renderer.setSize(size.width, size.height, false);
  57088. }
  57089. function setupTitle () {
  57090. titleEl = document.createElement('div');
  57091. titleEl.className = LOADER_TITLE_CLASS;
  57092. titleEl.innerHTML = document.title;
  57093. titleEl.style.display = 'none';
  57094. sceneEl.appendChild(titleEl);
  57095. }
  57096. },{"../../utils/":210}],140:[function(require,module,exports){
  57097. var constants = require('../../constants/');
  57098. var extend = require('../../utils').extend;
  57099. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  57100. 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'}),
  57101. // W3C-standardised meta tags.
  57102. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  57103. Meta({name: 'theme-color', content: 'black'})
  57104. ];
  57105. var MOBILE_IOS_HEAD_TAGS = [
  57106. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  57107. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  57108. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  57109. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  57110. ];
  57111. function Meta (attrs) {
  57112. return {
  57113. tagName: 'meta',
  57114. attributes: attrs,
  57115. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  57116. };
  57117. }
  57118. function Link (attrs) {
  57119. return {
  57120. tagName: 'link',
  57121. attributes: attrs,
  57122. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  57123. };
  57124. }
  57125. /**
  57126. * Injects the necessary metatags in the document for mobile support:
  57127. * 1. Prevent the user to zoom in the document.
  57128. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  57129. * values and the canvas is properly scaled.
  57130. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  57131. * iOS.
  57132. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  57133. *
  57134. * @param {object} scene - Scene element
  57135. * @returns {Array}
  57136. */
  57137. module.exports.inject = function injectHeadTags (scene) {
  57138. var headEl = document.head;
  57139. var headScriptEl = headEl.querySelector('script');
  57140. var tag;
  57141. var headTags = [];
  57142. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  57143. if (scene.isIOS) {
  57144. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  57145. }
  57146. return headTags;
  57147. function createAndInjectTag (tagObj) {
  57148. if (!tagObj || tagObj.exists()) { return; }
  57149. tag = createTag(tagObj);
  57150. if (!tag) { return; }
  57151. if (headScriptEl) {
  57152. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  57153. } else {
  57154. headEl.appendChild(tag);
  57155. }
  57156. headTags.push(tag);
  57157. }
  57158. };
  57159. function createTag (tagObj) {
  57160. if (!tagObj || !tagObj.tagName) { return; }
  57161. var meta = document.createElement(tagObj.tagName);
  57162. meta.setAttribute(constants.AFRAME_INJECTED, '');
  57163. return extend(meta, tagObj.attributes);
  57164. }
  57165. },{"../../constants/":127,"../../utils":210}],141:[function(require,module,exports){
  57166. var bind = require('../../utils/bind');
  57167. var isIframed = require('../../utils/').isIframed;
  57168. /**
  57169. * Provides a post message API for scenes contained
  57170. * in an iframe.
  57171. */
  57172. module.exports = function initPostMessageAPI (scene) {
  57173. // Handles fullscreen behavior when inside an iframe.
  57174. if (!isIframed()) { return; }
  57175. // postMessage API handler
  57176. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  57177. };
  57178. function postMessageAPIHandler (event) {
  57179. var scene = this;
  57180. if (!event.data) { return; }
  57181. switch (event.data.type) {
  57182. case 'vr': {
  57183. switch (event.data.data) {
  57184. case 'enter':
  57185. scene.enterVR();
  57186. break;
  57187. case 'exit':
  57188. scene.exitVR();
  57189. break;
  57190. }
  57191. }
  57192. }
  57193. }
  57194. },{"../../utils/":210,"../../utils/bind":204}],142:[function(require,module,exports){
  57195. /*
  57196. Scene index for keeping track of created scenes.
  57197. */
  57198. module.exports = [];
  57199. },{}],143:[function(require,module,exports){
  57200. var Wakelock = require('../../../vendor/wakelock/wakelock');
  57201. module.exports = function initWakelock (scene) {
  57202. if (!scene.isMobile) { return; }
  57203. var wakelock = scene.wakelock = new Wakelock();
  57204. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  57205. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  57206. };
  57207. },{"../../../vendor/wakelock/wakelock":225}],144:[function(require,module,exports){
  57208. var utils = require('../utils/');
  57209. var PropertyTypes = require('./propertyTypes');
  57210. var debug = utils.debug;
  57211. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  57212. var propertyTypes = PropertyTypes.propertyTypes;
  57213. var warn = debug('core:schema:warn');
  57214. /**
  57215. * A schema is classified as a schema for a single property if:
  57216. * - `type` is defined on the schema as a string.
  57217. * - OR `default` is defined on the schema, as a reserved keyword.
  57218. * - OR schema is empty.
  57219. */
  57220. function isSingleProperty (schema) {
  57221. if ('type' in schema) {
  57222. return typeof schema.type === 'string';
  57223. }
  57224. return 'default' in schema;
  57225. }
  57226. module.exports.isSingleProperty = isSingleProperty;
  57227. /**
  57228. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  57229. *
  57230. * @param {object} schema
  57231. * @param {string} componentName
  57232. * @returns {object} Schema.
  57233. */
  57234. module.exports.process = function (schema, componentName) {
  57235. var propName;
  57236. // For single property schema, run processPropDefinition over the whole schema.
  57237. if (isSingleProperty(schema)) {
  57238. return processPropertyDefinition(schema, componentName);
  57239. }
  57240. // For multi-property schema, run processPropDefinition over each property definition.
  57241. for (propName in schema) {
  57242. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  57243. }
  57244. return schema;
  57245. };
  57246. /**
  57247. * Inject default value, parser, stringifier for single property.
  57248. *
  57249. * @param {object} propDefinition
  57250. * @param {string} componentName
  57251. */
  57252. function processPropertyDefinition (propDefinition, componentName) {
  57253. var defaultVal = propDefinition.default;
  57254. var isCustomType;
  57255. var propType;
  57256. var typeName = propDefinition.type;
  57257. // Type inference.
  57258. if (!propDefinition.type) {
  57259. if (defaultVal !== undefined &&
  57260. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  57261. // Type inference.
  57262. typeName = typeof defaultVal;
  57263. } else if (Array.isArray(defaultVal)) {
  57264. typeName = 'array';
  57265. } else {
  57266. // Fall back to string.
  57267. typeName = 'string';
  57268. }
  57269. } else if (propDefinition.type === 'bool') {
  57270. typeName = 'boolean';
  57271. } else if (propDefinition.type === 'float') {
  57272. typeName = 'number';
  57273. }
  57274. propType = propertyTypes[typeName];
  57275. if (!propType) {
  57276. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  57277. }
  57278. // Fill in parse and stringify using property types.
  57279. isCustomType = !!propDefinition.parse;
  57280. propDefinition.parse = propDefinition.parse || propType.parse;
  57281. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  57282. // Fill in type name.
  57283. propDefinition.type = typeName;
  57284. // Check that default value exists.
  57285. if ('default' in propDefinition) {
  57286. // Check that default values are valid.
  57287. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  57288. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  57289. '` in component `' + componentName + '`');
  57290. }
  57291. } else {
  57292. // Fill in default value.
  57293. propDefinition.default = propType.default;
  57294. }
  57295. return propDefinition;
  57296. }
  57297. module.exports.processPropertyDefinition = processPropertyDefinition;
  57298. /**
  57299. * Parse propData using schema. Use default values if not existing in propData.
  57300. *
  57301. * @param {object} propData - Unparsed properties.
  57302. * @param {object} schema - Property types definition.
  57303. * @param {boolean} getPartialData - Whether to return full component data or just the data
  57304. * with keys in `propData`.
  57305. * @param {string } componentName - Name of the component, used for the property warning.
  57306. * @param {boolean} silent - Suppress warning messages.
  57307. */
  57308. module.exports.parseProperties = (function () {
  57309. var propNames = [];
  57310. return function (propData, schema, getPartialData, componentName, silent) {
  57311. var i;
  57312. var propName;
  57313. var propDefinition;
  57314. var propValue;
  57315. propNames.length = 0;
  57316. for (propName in (getPartialData ? propData : schema)) {
  57317. if (getPartialData && propData[propName] === undefined) { continue; }
  57318. propNames.push(propName);
  57319. }
  57320. if (propData === null || typeof propData !== 'object') { return propData; }
  57321. // Validation errors.
  57322. for (propName in propData) {
  57323. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  57324. warn('Unknown property `' + propName +
  57325. '` for component/system `' + componentName + '`.');
  57326. }
  57327. }
  57328. for (i = 0; i < propNames.length; i++) {
  57329. propName = propNames[i];
  57330. propDefinition = schema[propName];
  57331. propValue = propData[propName];
  57332. if (!(schema[propName])) { return; }
  57333. propData[propName] = parseProperty(propValue, propDefinition);
  57334. }
  57335. return propData;
  57336. };
  57337. })();
  57338. /**
  57339. * Deserialize a single property.
  57340. */
  57341. function parseProperty (value, propDefinition) {
  57342. // Use default value if value is falsy.
  57343. if (value === undefined || value === null || value === '') {
  57344. value = propDefinition.default;
  57345. if (Array.isArray(value)) { value = value.slice(); }
  57346. }
  57347. // Invoke property type parser.
  57348. return propDefinition.parse(value, propDefinition.default);
  57349. }
  57350. module.exports.parseProperty = parseProperty;
  57351. /**
  57352. * Serialize a group of properties.
  57353. */
  57354. module.exports.stringifyProperties = function (propData, schema) {
  57355. var propName;
  57356. var propDefinition;
  57357. var propValue;
  57358. var stringifiedData = {};
  57359. var value;
  57360. for (propName in propData) {
  57361. propDefinition = schema[propName];
  57362. propValue = propData[propName];
  57363. value = propValue;
  57364. if (typeof value === 'object') {
  57365. value = stringifyProperty(propValue, propDefinition);
  57366. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  57367. }
  57368. stringifiedData[propName] = value;
  57369. }
  57370. return stringifiedData;
  57371. };
  57372. /**
  57373. * Serialize a single property.
  57374. */
  57375. function stringifyProperty (value, propDefinition) {
  57376. // This function stringifies but it's used in a context where
  57377. // there's always second stringification pass. By returning the original
  57378. // value when it's not an object we save one unnecessary call
  57379. // to JSON.stringify.
  57380. if (typeof value !== 'object') { return value; }
  57381. // if there's no schema for the property we use standar JSON stringify
  57382. if (!propDefinition || value === null) { return JSON.stringify(value); }
  57383. return propDefinition.stringify(value);
  57384. }
  57385. module.exports.stringifyProperty = stringifyProperty;
  57386. },{"../utils/":210,"./propertyTypes":137}],145:[function(require,module,exports){
  57387. var schema = require('./schema');
  57388. var processSchema = schema.process;
  57389. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  57390. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  57391. var THREE = require('../lib/three');
  57392. var utils = require('../utils');
  57393. // A-Frame properties to three.js uniform types.
  57394. var propertyToThreeMapping = {
  57395. array: 'v3',
  57396. color: 'v3',
  57397. int: 'i',
  57398. number: 'f',
  57399. map: 't',
  57400. time: 'f',
  57401. vec2: 'v2',
  57402. vec3: 'v3',
  57403. vec4: 'v4'
  57404. };
  57405. /**
  57406. * Shader class definition.
  57407. *
  57408. * Shaders extend the material component API so you can create your own library
  57409. * of customized materials
  57410. *
  57411. */
  57412. var Shader = module.exports.Shader = function () {};
  57413. Shader.prototype = {
  57414. /**
  57415. * Contains the type schema and defaults for the data values.
  57416. * Data is coerced into the types of the values of the defaults.
  57417. */
  57418. schema: {},
  57419. vertexShader:
  57420. 'void main() {' +
  57421. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  57422. '}',
  57423. fragmentShader:
  57424. 'void main() {' +
  57425. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  57426. '}',
  57427. /**
  57428. * Init handler. Similar to attachedCallback.
  57429. * Called during shader initialization and is only run once.
  57430. */
  57431. init: function (data) {
  57432. this.attributes = this.initVariables(data, 'attribute');
  57433. this.uniforms = this.initVariables(data, 'uniform');
  57434. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  57435. // attributes: this.attributes,
  57436. uniforms: this.uniforms,
  57437. vertexShader: this.vertexShader,
  57438. fragmentShader: this.fragmentShader
  57439. });
  57440. return this.material;
  57441. },
  57442. initVariables: function (data, type) {
  57443. var key;
  57444. var schema = this.schema;
  57445. var variables = {};
  57446. var varType;
  57447. for (key in schema) {
  57448. if (schema[key].is !== type) { continue; }
  57449. varType = propertyToThreeMapping[schema[key].type];
  57450. variables[key] = {
  57451. type: varType,
  57452. value: undefined // Let updateVariables handle setting these.
  57453. };
  57454. }
  57455. return variables;
  57456. },
  57457. /**
  57458. * Update handler. Similar to attributeChangedCallback.
  57459. * Called whenever the associated material data changes.
  57460. *
  57461. * @param {object} data - New material data.
  57462. */
  57463. update: function (data) {
  57464. this.updateVariables(data, 'attribute');
  57465. this.updateVariables(data, 'uniform');
  57466. },
  57467. updateVariables: function (data, type) {
  57468. var key;
  57469. var materialKey;
  57470. var schema = this.schema;
  57471. var variables;
  57472. variables = type === 'uniform' ? this.uniforms : this.attributes;
  57473. for (key in data) {
  57474. if (!schema[key] || schema[key].is !== type) { continue; }
  57475. if (schema[key].type === 'map') {
  57476. // If data unchanged, get out early.
  57477. if (!variables[key] || variables[key].value === data[key]) { continue; }
  57478. // Special handling is needed for textures.
  57479. materialKey = '_texture_' + key;
  57480. // We can't actually set the variable correctly until we've loaded the texture.
  57481. this.setMapOnTextureLoad(variables, key, materialKey);
  57482. // Kick off the texture update now that handler is added.
  57483. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  57484. continue;
  57485. }
  57486. variables[key].value = this.parseValue(schema[key].type, data[key]);
  57487. variables[key].needsUpdate = true;
  57488. }
  57489. },
  57490. parseValue: function (type, value) {
  57491. var color;
  57492. switch (type) {
  57493. case 'vec2': {
  57494. return new THREE.Vector2(value.x, value.y);
  57495. }
  57496. case 'vec3': {
  57497. return new THREE.Vector3(value.x, value.y, value.z);
  57498. }
  57499. case 'vec4': {
  57500. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  57501. }
  57502. case 'color': {
  57503. color = new THREE.Color(value);
  57504. return new THREE.Vector3(color.r, color.g, color.b);
  57505. }
  57506. case 'map': {
  57507. return THREE.ImageUtils.loadTexture(value);
  57508. }
  57509. default: {
  57510. return value;
  57511. }
  57512. }
  57513. },
  57514. setMapOnTextureLoad: function (variables, key, materialKey) {
  57515. var self = this;
  57516. this.el.addEventListener('materialtextureloaded', function () {
  57517. variables[key].value = self.material[materialKey];
  57518. variables[key].needsUpdate = true;
  57519. });
  57520. }
  57521. };
  57522. /**
  57523. * Registers a shader to A-Frame.
  57524. *
  57525. * @param {string} name - shader name.
  57526. * @param {object} definition - shader property and methods.
  57527. * @returns {object} Shader.
  57528. */
  57529. module.exports.registerShader = function (name, definition) {
  57530. var NewShader;
  57531. var proto = {};
  57532. // Format definition object to prototype object.
  57533. Object.keys(definition).forEach(function (key) {
  57534. proto[key] = {
  57535. value: definition[key],
  57536. writable: true
  57537. };
  57538. });
  57539. if (shaders[name]) {
  57540. throw new Error('The shader ' + name + ' has been already registered');
  57541. }
  57542. NewShader = function () { Shader.call(this); };
  57543. NewShader.prototype = Object.create(Shader.prototype, proto);
  57544. NewShader.prototype.name = name;
  57545. NewShader.prototype.constructor = NewShader;
  57546. shaders[name] = {
  57547. Shader: NewShader,
  57548. schema: processSchema(NewShader.prototype.schema)
  57549. };
  57550. shaderNames.push(name);
  57551. return NewShader;
  57552. };
  57553. },{"../lib/three":183,"../utils":210,"./schema":144}],146:[function(require,module,exports){
  57554. var components = require('./component');
  57555. var schema = require('./schema');
  57556. var utils = require('../utils/');
  57557. var parseProperties = schema.parseProperties;
  57558. var parseProperty = schema.parseProperty;
  57559. var processSchema = schema.process;
  57560. var isSingleProp = schema.isSingleProperty;
  57561. var styleParser = utils.styleParser;
  57562. var systems = module.exports.systems = {}; // Keep track of registered systems.
  57563. /**
  57564. * System class definition.
  57565. *
  57566. * Systems provide global scope and services to a group of instantiated components of the
  57567. * same class. They can also help abstract logic away from components such that components
  57568. * only have to worry about data.
  57569. *
  57570. * For example, a physics component that creates a physics world that oversees
  57571. * all entities with a physics or rigid body component.
  57572. *
  57573. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  57574. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  57575. * setAttribute behavior).
  57576. *
  57577. * @member {string} name - Name that system is registered under.
  57578. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  57579. */
  57580. var System = module.exports.System = function (sceneEl) {
  57581. var component = components && components.components[this.name];
  57582. // Set reference to scene.
  57583. this.el = sceneEl;
  57584. this.sceneEl = sceneEl;
  57585. // Set reference to matching component (if exists).
  57586. if (component) { component.Component.prototype.system = this; }
  57587. // Process system configuration.
  57588. this.buildData();
  57589. this.init();
  57590. this.update({});
  57591. };
  57592. System.prototype = {
  57593. /**
  57594. * Schema to configure system.
  57595. */
  57596. schema: {},
  57597. /**
  57598. * Init handler. Called during scene initialization and is only run once.
  57599. * Systems can use this to set initial state.
  57600. */
  57601. init: function () { /* no-op */ },
  57602. /**
  57603. * Update handler. Called during scene attribute updates.
  57604. * Systems can use this to dynamically update their state.
  57605. */
  57606. update: function (oldData) { /* no-op */ },
  57607. /**
  57608. * Build data and call update handler.
  57609. *
  57610. * @private
  57611. */
  57612. updateProperties: function (rawData) {
  57613. var oldData = this.data;
  57614. if (!Object.keys(schema).length) { return; }
  57615. this.buildData(rawData);
  57616. this.update(oldData);
  57617. },
  57618. /**
  57619. * Parse data.
  57620. */
  57621. buildData: function (rawData) {
  57622. var schema = this.schema;
  57623. if (!Object.keys(schema).length) { return; }
  57624. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  57625. if (isSingleProp(schema)) {
  57626. this.data = parseProperty(rawData, schema);
  57627. } else {
  57628. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  57629. }
  57630. },
  57631. /**
  57632. * Tick handler.
  57633. * Called on each tick of the scene render loop.
  57634. * Affected by play and pause.
  57635. *
  57636. * @param {number} time - Scene tick time.
  57637. * @param {number} timeDelta - Difference in current render time and previous render time.
  57638. */
  57639. tick: undefined,
  57640. /**
  57641. * Tock handler.
  57642. * Called on each tock of the scene render loop.
  57643. * Affected by play and pause.
  57644. *
  57645. * @param {number} time - Scene tick time.
  57646. * @param {number} timeDelta - Difference in current render time and previous render time.
  57647. */
  57648. tock: undefined,
  57649. /**
  57650. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  57651. */
  57652. play: function () { /* no-op */ },
  57653. /**
  57654. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  57655. */
  57656. pause: function () { /* no-op */ }
  57657. };
  57658. /**
  57659. * Registers a system to A-Frame.
  57660. *
  57661. * @param {string} name - Component name.
  57662. * @param {object} definition - Component property and methods.
  57663. * @returns {object} Component.
  57664. */
  57665. module.exports.registerSystem = function (name, definition) {
  57666. var i;
  57667. var NewSystem;
  57668. var proto = {};
  57669. var scenes = utils.findAllScenes(document);
  57670. // Format definition object to prototype object.
  57671. Object.keys(definition).forEach(function (key) {
  57672. proto[key] = {
  57673. value: definition[key],
  57674. writable: true
  57675. };
  57676. });
  57677. if (systems[name]) {
  57678. throw new Error('The system `' + name + '` has been already registered. ' +
  57679. 'Check that you are not loading two versions of the same system ' +
  57680. 'or two different systems of the same name.');
  57681. }
  57682. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  57683. NewSystem.prototype = Object.create(System.prototype, proto);
  57684. NewSystem.prototype.name = name;
  57685. NewSystem.prototype.constructor = NewSystem;
  57686. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  57687. systems[name] = NewSystem;
  57688. // Initialize systems for existing scenes
  57689. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  57690. };
  57691. },{"../utils/":210,"./component":135,"./schema":144}],147:[function(require,module,exports){
  57692. require('./pivot');
  57693. },{"./pivot":148}],148:[function(require,module,exports){
  57694. var registerComponent = require('../../core/component').registerComponent;
  57695. var THREE = require('../../lib/three');
  57696. var originalPosition = new THREE.Vector3();
  57697. var originalRotation = new THREE.Vector3();
  57698. /**
  57699. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  57700. */
  57701. registerComponent('pivot', {
  57702. dependencies: ['position'],
  57703. schema: {type: 'vec3'},
  57704. init: function () {
  57705. var data = this.data;
  57706. var el = this.el;
  57707. var originalParent = el.object3D.parent;
  57708. var originalGroup = el.object3D;
  57709. var outerGroup = new THREE.Group();
  57710. originalPosition.copy(originalGroup.position);
  57711. originalRotation.copy(originalGroup.rotation);
  57712. // Detach current group from parent.
  57713. originalParent.remove(originalGroup);
  57714. outerGroup.add(originalGroup);
  57715. // Set new group as the outer group.
  57716. originalParent.add(outerGroup);
  57717. // Set outer group as new object3D.
  57718. el.object3D = outerGroup;
  57719. // Apply pivot to original group.
  57720. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  57721. // Offset the pivot so that world position not affected.
  57722. // And restore position onto outer group.
  57723. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  57724. data.z + originalPosition.z);
  57725. // Transfer rotation to outer group.
  57726. outerGroup.rotation.copy(originalGroup.rotation);
  57727. originalGroup.rotation.set(0, 0, 0);
  57728. }
  57729. });
  57730. },{"../../core/component":135,"../../lib/three":183}],149:[function(require,module,exports){
  57731. /**
  57732. * Common mesh defaults, mappings, and transforms.
  57733. */
  57734. var components = require('../../core/component').components;
  57735. var shaders = require('../../core/shader').shaders;
  57736. var utils = require('../../utils/');
  57737. var materialMappings = {};
  57738. Object.keys(components.material.schema).forEach(addMapping);
  57739. Object.keys(shaders.standard.schema).forEach(addMapping);
  57740. function addMapping (prop) {
  57741. // To hyphenated.
  57742. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  57743. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  57744. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  57745. materialMappings[htmlAttrName] = 'material.' + prop;
  57746. }
  57747. module.exports = function getMeshMixin () {
  57748. return {
  57749. defaultComponents: {material: {}},
  57750. mappings: utils.extend({}, materialMappings)
  57751. };
  57752. };
  57753. },{"../../core/component":135,"../../core/shader":145,"../../utils/":210}],150:[function(require,module,exports){
  57754. require('./primitives/a-camera');
  57755. require('./primitives/a-cursor');
  57756. require('./primitives/a-curvedimage');
  57757. require('./primitives/a-gltf-model');
  57758. require('./primitives/a-image');
  57759. require('./primitives/a-light');
  57760. require('./primitives/a-link');
  57761. require('./primitives/a-obj-model');
  57762. require('./primitives/a-sky');
  57763. require('./primitives/a-sound');
  57764. require('./primitives/a-text');
  57765. require('./primitives/a-video');
  57766. require('./primitives/a-videosphere');
  57767. require('./primitives/meshPrimitives');
  57768. },{"./primitives/a-camera":152,"./primitives/a-cursor":153,"./primitives/a-curvedimage":154,"./primitives/a-gltf-model":155,"./primitives/a-image":156,"./primitives/a-light":157,"./primitives/a-link":158,"./primitives/a-obj-model":159,"./primitives/a-sky":160,"./primitives/a-sound":161,"./primitives/a-text":162,"./primitives/a-video":163,"./primitives/a-videosphere":164,"./primitives/meshPrimitives":165}],151:[function(require,module,exports){
  57769. var AEntity = require('../../core/a-entity');
  57770. var components = require('../../core/component').components;
  57771. var registerElement = require('../../core/a-register-element').registerElement;
  57772. var utils = require('../../utils/');
  57773. var debug = utils.debug;
  57774. var setComponentProperty = utils.entity.setComponentProperty;
  57775. var log = debug('extras:primitives:debug');
  57776. var warn = debug('extras:primitives:warn');
  57777. var primitives = module.exports.primitives = {};
  57778. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  57779. name = name.toLowerCase();
  57780. log('Registering <%s>', name);
  57781. // Deprecation warning for defaultAttributes usage.
  57782. if (definition.defaultAttributes) {
  57783. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  57784. }
  57785. var primitive = registerElement(name, {
  57786. prototype: Object.create(AEntity.prototype, {
  57787. defaultComponentsFromPrimitive: {
  57788. value: definition.defaultComponents || definition.defaultAttributes || {}
  57789. },
  57790. deprecated: {value: definition.deprecated || null},
  57791. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  57792. mappings: {value: definition.mappings || {}},
  57793. createdCallback: {
  57794. value: function () {
  57795. if (definition.deprecated) { console.warn(definition.deprecated); }
  57796. this.resolveMappingCollisions();
  57797. }
  57798. },
  57799. /**
  57800. * If a mapping collides with a registered component name
  57801. * it renames the mapping to componentname-property
  57802. */
  57803. resolveMappingCollisions: {
  57804. value: function () {
  57805. var mappings = this.mappings;
  57806. var self = this;
  57807. Object.keys(mappings).forEach(function resolveCollision (key) {
  57808. var newAttribute;
  57809. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  57810. if (components[key]) {
  57811. newAttribute = mappings[key].replace('.', '-');
  57812. mappings[newAttribute] = mappings[key];
  57813. delete mappings[key];
  57814. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  57815. 'The attribute ' + key + ' has the same name as a registered component and' +
  57816. ' has been renamed to ' + newAttribute);
  57817. }
  57818. });
  57819. }
  57820. },
  57821. getExtraComponents: {
  57822. value: function () {
  57823. var attr;
  57824. var data;
  57825. var i;
  57826. var mapping;
  57827. var mixins;
  57828. var path;
  57829. var self = this;
  57830. // Gather component data from default components.
  57831. data = utils.clone(this.defaultComponentsFromPrimitive);
  57832. // Factor in mixins to overwrite default components.
  57833. mixins = this.getAttribute('mixin');
  57834. if (mixins) {
  57835. mixins = mixins.trim().split(' ');
  57836. mixins.forEach(function applyMixin (mixinId) {
  57837. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  57838. Object.keys(mixinComponents).forEach(function setComponent (name) {
  57839. data[name] = extend(data[name], mixinComponents[name]);
  57840. });
  57841. });
  57842. }
  57843. // Gather component data from mappings.
  57844. for (i = 0; i < this.attributes.length; i++) {
  57845. attr = this.attributes[i];
  57846. mapping = this.mappings[attr.name];
  57847. if (mapping) {
  57848. path = utils.entity.getComponentPropertyPath(mapping);
  57849. if (path.constructor === Array) {
  57850. data[path[0]] = data[path[0]] || {};
  57851. data[path[0]][path[1]] = attr.value.trim();
  57852. } else {
  57853. data[path] = attr.value.trim();
  57854. }
  57855. continue;
  57856. }
  57857. }
  57858. return data;
  57859. /**
  57860. * For the base to be extensible, both objects must be pure JavaScript objects.
  57861. * The function assumes that base is undefined, or null or a pure object.
  57862. */
  57863. function extend (base, extension) {
  57864. if (isUndefined(base)) {
  57865. return copy(extension);
  57866. }
  57867. if (isUndefined(extension)) {
  57868. return copy(base);
  57869. }
  57870. if (isPureObject(base) && isPureObject(extension)) {
  57871. return utils.extendDeep(base, extension);
  57872. }
  57873. return copy(extension);
  57874. }
  57875. function isUndefined (value) {
  57876. return typeof value === 'undefined';
  57877. }
  57878. function copy (value) {
  57879. if (isPureObject(value)) {
  57880. return utils.extendDeep({}, value);
  57881. }
  57882. return value;
  57883. }
  57884. function isPureObject (value) {
  57885. return value !== null && value.constructor === Object;
  57886. }
  57887. }
  57888. },
  57889. /**
  57890. * Sync to attribute to component property whenever mapped attribute changes.
  57891. * If attribute is mapped to a component property, set the component property using
  57892. * the attribute value.
  57893. */
  57894. attributeChangedCallback: {
  57895. value: function (attr, oldVal, value) {
  57896. var componentName = this.mappings[attr];
  57897. if (attr in this.deprecatedMappings) {
  57898. console.warn(this.deprecatedMappings[attr]);
  57899. }
  57900. if (!attr || !componentName) { return; }
  57901. // Set value.
  57902. setComponentProperty(this, componentName, value);
  57903. }
  57904. }
  57905. })
  57906. });
  57907. // Store.
  57908. primitives[name] = primitive;
  57909. return primitive;
  57910. };
  57911. /**
  57912. * Add component mappings using schema.
  57913. */
  57914. function addComponentMapping (componentName, mappings) {
  57915. var schema = components[componentName].schema;
  57916. Object.keys(schema).map(function (prop) {
  57917. // Hyphenate where there is camelCase.
  57918. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  57919. // If there is a mapping collision, prefix with component name and hyphen.
  57920. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  57921. mappings[attrName] = componentName + '.' + prop;
  57922. });
  57923. }
  57924. /**
  57925. * Helper to define a primitive, building mappings using a component schema.
  57926. */
  57927. function definePrimitive (tagName, defaultComponents, mappings) {
  57928. // If no initial mappings provided, start from empty map.
  57929. mappings = mappings || {};
  57930. // From the default components, add mapping automagically.
  57931. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  57932. addComponentMapping(componentName, mappings);
  57933. });
  57934. // Register the primitive.
  57935. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  57936. defaultComponents: defaultComponents,
  57937. mappings: mappings
  57938. }));
  57939. }
  57940. module.exports.definePrimitive = definePrimitive;
  57941. },{"../../core/a-entity":131,"../../core/a-register-element":134,"../../core/component":135,"../../utils/":210}],152:[function(require,module,exports){
  57942. var registerPrimitive = require('../primitives').registerPrimitive;
  57943. registerPrimitive('a-camera', {
  57944. defaultComponents: {
  57945. 'camera': {},
  57946. 'look-controls': {},
  57947. 'wasd-controls': {},
  57948. 'position': {x: 0, y: 1.6, z: 0}
  57949. },
  57950. mappings: {
  57951. active: 'camera.active',
  57952. far: 'camera.far',
  57953. fov: 'camera.fov',
  57954. 'look-controls-enabled': 'look-controls.enabled',
  57955. near: 'camera.near',
  57956. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  57957. 'wasd-controls-enabled': 'wasd-controls.enabled',
  57958. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  57959. zoom: 'camera.zoom'
  57960. }
  57961. });
  57962. },{"../primitives":151}],153:[function(require,module,exports){
  57963. var getMeshMixin = require('../getMeshMixin');
  57964. var registerPrimitive = require('../primitives').registerPrimitive;
  57965. var utils = require('../../../utils/');
  57966. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  57967. defaultComponents: {
  57968. cursor: {},
  57969. geometry: {
  57970. primitive: 'ring',
  57971. radiusOuter: 0.016,
  57972. radiusInner: 0.01,
  57973. segmentsTheta: 32
  57974. },
  57975. material: {
  57976. color: '#000',
  57977. shader: 'flat',
  57978. opacity: 0.8
  57979. },
  57980. position: {
  57981. x: 0,
  57982. y: 0,
  57983. z: -1
  57984. }
  57985. },
  57986. mappings: {
  57987. far: 'raycaster.far',
  57988. fuse: 'cursor.fuse',
  57989. 'fuse-timeout': 'cursor.fuseTimeout',
  57990. interval: 'raycaster.interval',
  57991. objects: 'raycaster.objects'
  57992. }
  57993. }));
  57994. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],154:[function(require,module,exports){
  57995. var getMeshMixin = require('../getMeshMixin');
  57996. var registerPrimitive = require('../primitives').registerPrimitive;
  57997. var utils = require('../../../utils/');
  57998. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  57999. defaultComponents: {
  58000. geometry: {
  58001. height: 1,
  58002. primitive: 'cylinder',
  58003. radius: 2,
  58004. segmentsRadial: 48,
  58005. thetaLength: 270,
  58006. openEnded: true,
  58007. thetaStart: 0
  58008. },
  58009. material: {
  58010. color: '#FFF',
  58011. shader: 'flat',
  58012. side: 'double',
  58013. transparent: true,
  58014. repeat: '-1 1'
  58015. }
  58016. },
  58017. mappings: {
  58018. height: 'geometry.height',
  58019. 'open-ended': 'geometry.openEnded',
  58020. radius: 'geometry.radius',
  58021. segments: 'geometry.segmentsRadial',
  58022. start: 'geometry.thetaStart',
  58023. 'theta-length': 'geometry.thetaLength',
  58024. 'theta-start': 'geometry.thetaStart',
  58025. 'width': 'geometry.thetaLength'
  58026. }
  58027. }));
  58028. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],155:[function(require,module,exports){
  58029. var registerPrimitive = require('../primitives').registerPrimitive;
  58030. registerPrimitive('a-gltf-model', {
  58031. mappings: {
  58032. src: 'gltf-model'
  58033. }
  58034. });
  58035. },{"../primitives":151}],156:[function(require,module,exports){
  58036. var getMeshMixin = require('../getMeshMixin');
  58037. var registerPrimitive = require('../primitives').registerPrimitive;
  58038. var utils = require('../../../utils/');
  58039. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  58040. defaultComponents: {
  58041. geometry: {
  58042. primitive: 'plane'
  58043. },
  58044. material: {
  58045. color: '#FFF',
  58046. shader: 'flat',
  58047. side: 'double',
  58048. transparent: true
  58049. }
  58050. },
  58051. mappings: {
  58052. height: 'geometry.height',
  58053. width: 'geometry.width'
  58054. }
  58055. }));
  58056. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],157:[function(require,module,exports){
  58057. var registerPrimitive = require('../primitives').registerPrimitive;
  58058. registerPrimitive('a-light', {
  58059. defaultComponents: {
  58060. light: {}
  58061. },
  58062. mappings: {
  58063. angle: 'light.angle',
  58064. color: 'light.color',
  58065. 'ground-color': 'light.groundColor',
  58066. decay: 'light.decay',
  58067. distance: 'light.distance',
  58068. intensity: 'light.intensity',
  58069. penumbra: 'light.penumbra',
  58070. type: 'light.type',
  58071. target: 'light.target',
  58072. envmap: 'light.envMap'
  58073. }
  58074. });
  58075. },{"../primitives":151}],158:[function(require,module,exports){
  58076. var registerPrimitive = require('../primitives').registerPrimitive;
  58077. registerPrimitive('a-link', {
  58078. defaultComponents: {
  58079. link: {
  58080. visualAspectEnabled: true
  58081. }
  58082. },
  58083. mappings: {
  58084. href: 'link.href',
  58085. image: 'link.image',
  58086. title: 'link.title'
  58087. }
  58088. });
  58089. },{"../primitives":151}],159:[function(require,module,exports){
  58090. var meshMixin = require('../getMeshMixin')();
  58091. var registerPrimitive = require('../primitives').registerPrimitive;
  58092. var utils = require('../../../utils/');
  58093. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  58094. defaultComponents: {
  58095. 'obj-model': {}
  58096. },
  58097. mappings: {
  58098. src: 'obj-model.obj',
  58099. mtl: 'obj-model.mtl'
  58100. }
  58101. }));
  58102. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],160:[function(require,module,exports){
  58103. var getMeshMixin = require('../getMeshMixin');
  58104. var registerPrimitive = require('../primitives').registerPrimitive;
  58105. var utils = require('../../../utils/');
  58106. var meshPrimitives = require('./meshPrimitives');
  58107. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  58108. defaultComponents: {
  58109. geometry: {
  58110. primitive: 'sphere',
  58111. radius: 500,
  58112. segmentsWidth: 64,
  58113. segmentsHeight: 32
  58114. },
  58115. material: {
  58116. color: '#FFF',
  58117. side: 'back',
  58118. shader: 'flat',
  58119. npot: true
  58120. },
  58121. scale: '-1 1 1'
  58122. },
  58123. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  58124. }));
  58125. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151,"./meshPrimitives":165}],161:[function(require,module,exports){
  58126. var registerPrimitive = require('../primitives').registerPrimitive;
  58127. registerPrimitive('a-sound', {
  58128. defaultComponents: {
  58129. sound: {}
  58130. },
  58131. mappings: {
  58132. src: 'sound.src',
  58133. on: 'sound.on',
  58134. autoplay: 'sound.autoplay',
  58135. loop: 'sound.loop',
  58136. volume: 'sound.volume'
  58137. }
  58138. });
  58139. },{"../primitives":151}],162:[function(require,module,exports){
  58140. // <a-text> using `definePrimitive` helper.
  58141. var definePrimitive = require('../primitives').definePrimitive;
  58142. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  58143. },{"../primitives":151}],163:[function(require,module,exports){
  58144. var getMeshMixin = require('../getMeshMixin');
  58145. var registerPrimitive = require('../primitives').registerPrimitive;
  58146. var utils = require('../../../utils/');
  58147. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  58148. defaultComponents: {
  58149. geometry: {
  58150. primitive: 'plane'
  58151. },
  58152. material: {
  58153. color: '#FFF',
  58154. shader: 'flat',
  58155. side: 'double',
  58156. transparent: true
  58157. }
  58158. },
  58159. mappings: {
  58160. height: 'geometry.height',
  58161. width: 'geometry.width'
  58162. }
  58163. }));
  58164. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],164:[function(require,module,exports){
  58165. var getMeshMixin = require('../getMeshMixin');
  58166. var registerPrimitive = require('../primitives').registerPrimitive;
  58167. var utils = require('../../../utils/');
  58168. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  58169. defaultComponents: {
  58170. geometry: {
  58171. primitive: 'sphere',
  58172. radius: 500,
  58173. segmentsWidth: 64,
  58174. segmentsHeight: 32
  58175. },
  58176. material: {
  58177. color: '#FFF',
  58178. shader: 'flat',
  58179. side: 'back',
  58180. npot: true
  58181. },
  58182. scale: '-1 1 1'
  58183. },
  58184. mappings: {
  58185. radius: 'geometry.radius',
  58186. 'segments-height': 'geometry.segmentsHeight',
  58187. 'segments-width': 'geometry.segmentsWidth'
  58188. }
  58189. }));
  58190. },{"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],165:[function(require,module,exports){
  58191. /**
  58192. * Automated mesh primitive registration.
  58193. */
  58194. var getMeshMixin = require('../getMeshMixin');
  58195. var geometries = require('../../../core/geometry').geometries;
  58196. var geometryNames = require('../../../core/geometry').geometryNames;
  58197. var registerPrimitive = require('../primitives').registerPrimitive;
  58198. var utils = require('../../../utils/');
  58199. // For testing.
  58200. var meshPrimitives = module.exports = {};
  58201. // Generate primitive for each geometry type.
  58202. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  58203. var geometry = geometries[geometryName];
  58204. var geometryHyphened = unCamelCase(geometryName);
  58205. // Generate mappings.
  58206. var mappings = {};
  58207. Object.keys(geometry.schema).forEach(function createMapping (property) {
  58208. mappings[unCamelCase(property)] = 'geometry.' + property;
  58209. });
  58210. // Register.
  58211. var tagName = 'a-' + geometryHyphened;
  58212. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  58213. defaultComponents: {geometry: {primitive: geometryName}},
  58214. mappings: mappings
  58215. }));
  58216. meshPrimitives[tagName] = primitive;
  58217. });
  58218. /**
  58219. * camelCase to hyphened-string.
  58220. */
  58221. function unCamelCase (str) {
  58222. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58223. }
  58224. },{"../../../core/geometry":136,"../../../utils/":210,"../getMeshMixin":149,"../primitives":151}],166:[function(require,module,exports){
  58225. var registerGeometry = require('../core/geometry').registerGeometry;
  58226. var THREE = require('../lib/three');
  58227. registerGeometry('box', {
  58228. schema: {
  58229. depth: {default: 1, min: 0},
  58230. height: {default: 1, min: 0},
  58231. width: {default: 1, min: 0},
  58232. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58233. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  58234. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  58235. },
  58236. init: function (data) {
  58237. this.geometry = new THREE.BoxGeometry(
  58238. data.width, data.height, data.depth,
  58239. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  58240. }
  58241. });
  58242. },{"../core/geometry":136,"../lib/three":183}],167:[function(require,module,exports){
  58243. var registerGeometry = require('../core/geometry').registerGeometry;
  58244. var THREE = require('../lib/three');
  58245. var degToRad = THREE.Math.degToRad;
  58246. registerGeometry('circle', {
  58247. schema: {
  58248. radius: {default: 1, min: 0},
  58249. segments: {default: 32, min: 3, type: 'int'},
  58250. thetaLength: {default: 360, min: 0},
  58251. thetaStart: {default: 0}
  58252. },
  58253. init: function (data) {
  58254. this.geometry = new THREE.CircleGeometry(
  58255. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58256. }
  58257. });
  58258. },{"../core/geometry":136,"../lib/three":183}],168:[function(require,module,exports){
  58259. var registerGeometry = require('../core/geometry').registerGeometry;
  58260. var THREE = require('../lib/three');
  58261. var degToRad = THREE.Math.degToRad;
  58262. registerGeometry('cone', {
  58263. schema: {
  58264. height: {default: 1, min: 0},
  58265. openEnded: {default: false},
  58266. radiusBottom: {default: 1, min: 0},
  58267. radiusTop: {default: 0.01, min: 0},
  58268. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58269. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58270. thetaLength: {default: 360, min: 0},
  58271. thetaStart: {default: 0}
  58272. },
  58273. init: function (data) {
  58274. this.geometry = new THREE.CylinderGeometry(
  58275. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  58276. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  58277. degToRad(data.thetaLength));
  58278. }
  58279. });
  58280. },{"../core/geometry":136,"../lib/three":183}],169:[function(require,module,exports){
  58281. var registerGeometry = require('../core/geometry').registerGeometry;
  58282. var THREE = require('../lib/three');
  58283. var degToRad = THREE.Math.degToRad;
  58284. registerGeometry('cylinder', {
  58285. schema: {
  58286. height: {default: 1, min: 0},
  58287. openEnded: {default: false},
  58288. radius: {default: 1, min: 0},
  58289. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58290. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58291. thetaLength: {default: 360, min: 0},
  58292. thetaStart: {default: 0}
  58293. },
  58294. init: function (data) {
  58295. this.geometry = new THREE.CylinderGeometry(
  58296. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  58297. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58298. }
  58299. });
  58300. },{"../core/geometry":136,"../lib/three":183}],170:[function(require,module,exports){
  58301. var registerGeometry = require('../core/geometry').registerGeometry;
  58302. var THREE = require('../lib/three');
  58303. registerGeometry('dodecahedron', {
  58304. schema: {
  58305. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58306. radius: {default: 1, min: 0}
  58307. },
  58308. init: function (data) {
  58309. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  58310. }
  58311. });
  58312. },{"../core/geometry":136,"../lib/three":183}],171:[function(require,module,exports){
  58313. var registerGeometry = require('../core/geometry').registerGeometry;
  58314. var THREE = require('../lib/three');
  58315. registerGeometry('icosahedron', {
  58316. schema: {
  58317. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58318. radius: {default: 1, min: 0}
  58319. },
  58320. init: function (data) {
  58321. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  58322. }
  58323. });
  58324. },{"../core/geometry":136,"../lib/three":183}],172:[function(require,module,exports){
  58325. require('./box.js');
  58326. require('./circle.js');
  58327. require('./cone.js');
  58328. require('./cylinder.js');
  58329. require('./dodecahedron.js');
  58330. require('./icosahedron.js');
  58331. require('./octahedron.js');
  58332. require('./plane.js');
  58333. require('./ring.js');
  58334. require('./sphere.js');
  58335. require('./tetrahedron.js');
  58336. require('./torus.js');
  58337. require('./torusKnot.js');
  58338. require('./triangle.js');
  58339. },{"./box.js":166,"./circle.js":167,"./cone.js":168,"./cylinder.js":169,"./dodecahedron.js":170,"./icosahedron.js":171,"./octahedron.js":173,"./plane.js":174,"./ring.js":175,"./sphere.js":176,"./tetrahedron.js":177,"./torus.js":178,"./torusKnot.js":179,"./triangle.js":180}],173:[function(require,module,exports){
  58340. var registerGeometry = require('../core/geometry').registerGeometry;
  58341. var THREE = require('../lib/three');
  58342. registerGeometry('octahedron', {
  58343. schema: {
  58344. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58345. radius: {default: 1, min: 0}
  58346. },
  58347. init: function (data) {
  58348. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  58349. }
  58350. });
  58351. },{"../core/geometry":136,"../lib/three":183}],174:[function(require,module,exports){
  58352. var registerGeometry = require('../core/geometry').registerGeometry;
  58353. var THREE = require('../lib/three');
  58354. registerGeometry('plane', {
  58355. schema: {
  58356. height: {default: 1, min: 0},
  58357. width: {default: 1, min: 0},
  58358. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58359. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  58360. },
  58361. init: function (data) {
  58362. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  58363. }
  58364. });
  58365. },{"../core/geometry":136,"../lib/three":183}],175:[function(require,module,exports){
  58366. var registerGeometry = require('../core/geometry').registerGeometry;
  58367. var THREE = require('../lib/three');
  58368. var degToRad = THREE.Math.degToRad;
  58369. registerGeometry('ring', {
  58370. schema: {
  58371. radiusInner: {default: 0.8, min: 0},
  58372. radiusOuter: {default: 1.2, min: 0},
  58373. segmentsPhi: {default: 10, min: 1, type: 'int'},
  58374. segmentsTheta: {default: 32, min: 3, type: 'int'},
  58375. thetaLength: {default: 360, min: 0},
  58376. thetaStart: {default: 0}
  58377. },
  58378. init: function (data) {
  58379. this.geometry = new THREE.RingGeometry(
  58380. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  58381. degToRad(data.thetaStart), degToRad(data.thetaLength));
  58382. }
  58383. });
  58384. },{"../core/geometry":136,"../lib/three":183}],176:[function(require,module,exports){
  58385. var registerGeometry = require('../core/geometry').registerGeometry;
  58386. var THREE = require('../lib/three');
  58387. var degToRad = THREE.Math.degToRad;
  58388. registerGeometry('sphere', {
  58389. schema: {
  58390. radius: {default: 1, min: 0},
  58391. phiLength: {default: 360},
  58392. phiStart: {default: 0, min: 0},
  58393. thetaLength: {default: 180, min: 0},
  58394. thetaStart: {default: 0},
  58395. segmentsHeight: {default: 18, min: 2, type: 'int'},
  58396. segmentsWidth: {default: 36, min: 3, type: 'int'}
  58397. },
  58398. init: function (data) {
  58399. this.geometry = new THREE.SphereGeometry(
  58400. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  58401. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  58402. }
  58403. });
  58404. },{"../core/geometry":136,"../lib/three":183}],177:[function(require,module,exports){
  58405. var registerGeometry = require('../core/geometry').registerGeometry;
  58406. var THREE = require('../lib/three');
  58407. registerGeometry('tetrahedron', {
  58408. schema: {
  58409. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58410. radius: {default: 1, min: 0}
  58411. },
  58412. init: function (data) {
  58413. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  58414. }
  58415. });
  58416. },{"../core/geometry":136,"../lib/three":183}],178:[function(require,module,exports){
  58417. var registerGeometry = require('../core/geometry').registerGeometry;
  58418. var THREE = require('../lib/three');
  58419. var degToRad = THREE.Math.degToRad;
  58420. registerGeometry('torus', {
  58421. schema: {
  58422. arc: {default: 360},
  58423. radius: {default: 1, min: 0},
  58424. radiusTubular: {default: 0.2, min: 0},
  58425. segmentsRadial: {default: 36, min: 2, type: 'int'},
  58426. segmentsTubular: {default: 32, min: 3, type: 'int'}
  58427. },
  58428. init: function (data) {
  58429. this.geometry = new THREE.TorusGeometry(
  58430. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  58431. degToRad(data.arc));
  58432. }
  58433. });
  58434. },{"../core/geometry":136,"../lib/three":183}],179:[function(require,module,exports){
  58435. var registerGeometry = require('../core/geometry').registerGeometry;
  58436. var THREE = require('../lib/three');
  58437. registerGeometry('torusKnot', {
  58438. schema: {
  58439. p: {default: 2, min: 1},
  58440. q: {default: 3, min: 1},
  58441. radius: {default: 1, min: 0},
  58442. radiusTubular: {default: 0.2, min: 0},
  58443. segmentsRadial: {default: 8, min: 3, type: 'int'},
  58444. segmentsTubular: {default: 100, min: 3, type: 'int'}
  58445. },
  58446. init: function (data) {
  58447. this.geometry = new THREE.TorusKnotGeometry(
  58448. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  58449. data.p, data.q);
  58450. }
  58451. });
  58452. },{"../core/geometry":136,"../lib/three":183}],180:[function(require,module,exports){
  58453. var registerGeometry = require('../core/geometry').registerGeometry;
  58454. var THREE = require('../lib/three');
  58455. var quaternion = new THREE.Quaternion();
  58456. var rotateVector = new THREE.Vector3(0, 0, 1);
  58457. var uvMinVector = new THREE.Vector2();
  58458. var uvMaxVector = new THREE.Vector2();
  58459. var uvScaleVector = new THREE.Vector2();
  58460. registerGeometry('triangle', {
  58461. schema: {
  58462. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  58463. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  58464. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  58465. },
  58466. init: function (data) {
  58467. var geometry;
  58468. var normal;
  58469. var triangle;
  58470. var uvA;
  58471. var uvB;
  58472. var uvC;
  58473. var vertices;
  58474. var normals;
  58475. var uvs;
  58476. triangle = new THREE.Triangle();
  58477. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  58478. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  58479. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  58480. normal = triangle.getNormal(new THREE.Vector3());
  58481. // Rotate the 3D triangle to be parallel to XY plane.
  58482. quaternion.setFromUnitVectors(normal, rotateVector);
  58483. uvA = triangle.a.clone().applyQuaternion(quaternion);
  58484. uvB = triangle.b.clone().applyQuaternion(quaternion);
  58485. uvC = triangle.c.clone().applyQuaternion(quaternion);
  58486. // Compute UVs.
  58487. // Normalize x/y values of UV so they are within 0 to 1.
  58488. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  58489. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  58490. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  58491. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  58492. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  58493. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  58494. geometry = this.geometry = new THREE.BufferGeometry();
  58495. vertices = [
  58496. triangle.a.x, triangle.a.y, triangle.a.z,
  58497. triangle.b.x, triangle.b.y, triangle.b.z,
  58498. triangle.c.x, triangle.c.y, triangle.c.z
  58499. ];
  58500. normals = [
  58501. normal.x, normal.y, normal.z,
  58502. normal.x, normal.y, normal.z,
  58503. normal.x, normal.y, normal.z
  58504. ];
  58505. uvs = [
  58506. uvA.x, uvA.y,
  58507. uvB.x, uvB.y,
  58508. uvC.x, uvC.y
  58509. ];
  58510. geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
  58511. geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
  58512. geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
  58513. }
  58514. });
  58515. },{"../core/geometry":136,"../lib/three":183}],181:[function(require,module,exports){
  58516. // Polyfill `Promise`.
  58517. window.Promise = window.Promise || require('promise-polyfill');
  58518. // WebVR polyfill
  58519. // Check before the polyfill runs.
  58520. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  58521. !!window.navigator.getVRDevices;
  58522. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  58523. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  58524. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  58525. var isIOSOlderThan10 = require('./utils/isIOSOlderThan10');
  58526. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  58527. // Only for iOS on versions older than 10.
  58528. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  58529. var WebVRPolyfill = require('webvr-polyfill');
  58530. var polyfillConfig = {
  58531. BUFFER_SCALE: bufferScale,
  58532. CARDBOARD_UI_DISABLED: true,
  58533. ROTATE_INSTRUCTIONS_DISABLED: true,
  58534. MOBILE_WAKE_LOCK: !!window.cordova
  58535. };
  58536. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  58537. }
  58538. var utils = require('./utils/');
  58539. var debug = utils.debug;
  58540. if (utils.isIE11) {
  58541. // Polyfill `CustomEvent`.
  58542. require('custom-event-polyfill');
  58543. // Polyfill String.startsWith.
  58544. require('../vendor/starts-with-polyfill');
  58545. }
  58546. var error = debug('A-Frame:error');
  58547. var warn = debug('A-Frame:warn');
  58548. if (window.document.currentScript && window.document.currentScript.parentNode !==
  58549. window.document.head && !window.debug) {
  58550. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  58551. 'ensure everything for A-Frame is properly registered before they are used from ' +
  58552. 'HTML.');
  58553. }
  58554. // Error if not using a server.
  58555. if (!window.cordova && window.location.protocol === 'file:') {
  58556. error(
  58557. 'This HTML file is currently being served via the file:// protocol. ' +
  58558. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  58559. 'Please use a local or hosted server: ' +
  58560. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  58561. }
  58562. require('present'); // Polyfill `performance.now()`.
  58563. // CSS.
  58564. if (utils.device.isBrowserEnvironment) {
  58565. require('./style/aframe.css');
  58566. require('./style/rStats.css');
  58567. }
  58568. // Required before `AEntity` so that all components are registered.
  58569. var AScene = require('./core/scene/a-scene').AScene;
  58570. var components = require('./core/component').components;
  58571. var registerComponent = require('./core/component').registerComponent;
  58572. var registerGeometry = require('./core/geometry').registerGeometry;
  58573. var registerPrimitive = require('./extras/primitives/primitives').registerPrimitive;
  58574. var registerShader = require('./core/shader').registerShader;
  58575. var registerSystem = require('./core/system').registerSystem;
  58576. var shaders = require('./core/shader').shaders;
  58577. var systems = require('./core/system').systems;
  58578. // Exports THREE to window so three.js can be used without alteration.
  58579. var THREE = window.THREE = require('./lib/three');
  58580. var pkg = require('../package');
  58581. require('./components/index'); // Register standard components.
  58582. require('./geometries/index'); // Register standard geometries.
  58583. require('./shaders/index'); // Register standard shaders.
  58584. require('./systems/index'); // Register standard systems.
  58585. var ANode = require('./core/a-node');
  58586. var AEntity = require('./core/a-entity'); // Depends on ANode and core components.
  58587. require('./core/a-assets');
  58588. require('./core/a-cubemap');
  58589. require('./core/a-mixin');
  58590. // Extras.
  58591. require('./extras/components/');
  58592. require('./extras/primitives/');
  58593. console.log('A-Frame Version: 1.2.0 (Date 2021-11-22, Commit #cf65f451)');
  58594. console.log('THREE Version (https://github.com/supermedium/three.js):',
  58595. pkg.dependencies['super-three']);
  58596. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  58597. module.exports = window.AFRAME = {
  58598. AComponent: require('./core/component').Component,
  58599. AEntity: AEntity,
  58600. ANode: ANode,
  58601. ANIME: require('super-animejs'),
  58602. AScene: AScene,
  58603. components: components,
  58604. coreComponents: Object.keys(components),
  58605. geometries: require('./core/geometry').geometries,
  58606. registerComponent: registerComponent,
  58607. registerElement: require('./core/a-register-element').registerElement,
  58608. registerGeometry: registerGeometry,
  58609. registerPrimitive: registerPrimitive,
  58610. registerShader: registerShader,
  58611. registerSystem: registerSystem,
  58612. primitives: {
  58613. getMeshMixin: require('./extras/primitives/getMeshMixin'),
  58614. primitives: require('./extras/primitives/primitives').primitives
  58615. },
  58616. scenes: require('./core/scene/scenes'),
  58617. schema: require('./core/schema'),
  58618. shaders: shaders,
  58619. systems: systems,
  58620. THREE: THREE,
  58621. utils: utils,
  58622. version: pkg.version
  58623. };
  58624. },{"../package":74,"../vendor/starts-with-polyfill":223,"./components/index":87,"./core/a-assets":129,"./core/a-cubemap":130,"./core/a-entity":131,"./core/a-mixin":132,"./core/a-node":133,"./core/a-register-element":134,"./core/component":135,"./core/geometry":136,"./core/scene/a-scene":138,"./core/scene/scenes":142,"./core/schema":144,"./core/shader":145,"./core/system":146,"./extras/components/":147,"./extras/primitives/":150,"./extras/primitives/getMeshMixin":149,"./extras/primitives/primitives":151,"./geometries/index":172,"./lib/three":183,"./shaders/index":185,"./style/aframe.css":191,"./style/rStats.css":192,"./systems/index":196,"./utils/":210,"./utils/isIOSOlderThan10":213,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":69}],182:[function(require,module,exports){
  58625. window.aframeStats = function (scene) {
  58626. var _rS = null;
  58627. var _scene = scene;
  58628. var _values = {
  58629. te: {
  58630. caption: 'Entities'
  58631. },
  58632. lt: {
  58633. caption: 'Load Time'
  58634. }
  58635. };
  58636. var _groups = [ {
  58637. caption: 'A-Frame',
  58638. values: [ 'te', 'lt' ]
  58639. } ];
  58640. function _update () {
  58641. _rS('te').set(getEntityCount());
  58642. if (window.performance.getEntriesByName) {
  58643. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  58644. }
  58645. }
  58646. function getEntityCount () {
  58647. var elements = _scene.querySelectorAll('*');
  58648. Array.prototype.slice.call(elements).filter(function (el) {
  58649. return el.isEntity;
  58650. });
  58651. return elements.length;
  58652. }
  58653. function _start () {}
  58654. function _end () {}
  58655. function _attach (r) {
  58656. _rS = r;
  58657. }
  58658. return {
  58659. update: _update,
  58660. start: _start,
  58661. end: _end,
  58662. attach: _attach,
  58663. values: _values,
  58664. groups: _groups,
  58665. fractions: []
  58666. };
  58667. };
  58668. if (typeof module === 'object') {
  58669. module.exports = {
  58670. aframeStats: window.aframeStats
  58671. };
  58672. }
  58673. },{}],183:[function(require,module,exports){
  58674. (function (global){
  58675. var THREE = global.THREE = require('super-three');
  58676. // Allow cross-origin images to be loaded.
  58677. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  58678. // Must be on `THREE.TextureLoader`.
  58679. if (THREE.TextureLoader) {
  58680. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  58681. }
  58682. // This is for images loaded from the model loaders.
  58683. if (THREE.ImageLoader) {
  58684. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  58685. }
  58686. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  58687. if (THREE.Cache) {
  58688. THREE.Cache.enabled = true;
  58689. }
  58690. // TODO: Eventually include these only if they are needed by a component.
  58691. require('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  58692. require('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  58693. require('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  58694. require('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  58695. require('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  58696. require('super-three/examples/js/utils/BufferGeometryUtils'); // THREE.BufferGeometryUtils
  58697. require('super-three/examples/js/lights/LightProbeGenerator'); // THREE.LightProbeGenerator
  58698. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  58699. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  58700. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  58701. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  58702. module.exports = THREE;
  58703. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  58704. },{"../../vendor/DeviceOrientationControls":220,"super-three":57,"super-three/examples/js/lights/LightProbeGenerator":58,"super-three/examples/js/loaders/DRACOLoader":59,"super-three/examples/js/loaders/GLTFLoader":60,"super-three/examples/js/loaders/MTLLoader":61,"super-three/examples/js/loaders/OBJLoader":62,"super-three/examples/js/utils/BufferGeometryUtils":63}],184:[function(require,module,exports){
  58705. var registerShader = require('../core/shader').registerShader;
  58706. var THREE = require('../lib/three');
  58707. var utils = require('../utils/');
  58708. /**
  58709. * Flat shader using THREE.MeshBasicMaterial.
  58710. */
  58711. module.exports.Shader = registerShader('flat', {
  58712. schema: {
  58713. color: {type: 'color'},
  58714. fog: {default: true},
  58715. height: {default: 256},
  58716. offset: {type: 'vec2', default: {x: 0, y: 0}},
  58717. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  58718. src: {type: 'map'},
  58719. width: {default: 512},
  58720. wireframe: {default: false},
  58721. wireframeLinewidth: {default: 2}
  58722. },
  58723. /**
  58724. * Initializes the shader.
  58725. * Adds a reference from the scene to this entity as the camera.
  58726. */
  58727. init: function (data) {
  58728. this.rendererSystem = this.el.sceneEl.systems.renderer;
  58729. this.materialData = {color: new THREE.Color()};
  58730. this.textureSrc = null;
  58731. getMaterialData(data, this.materialData);
  58732. this.rendererSystem.applyColorCorrection(this.materialData.color);
  58733. this.material = new THREE.MeshBasicMaterial(this.materialData);
  58734. utils.material.updateMap(this, data);
  58735. },
  58736. update: function (data) {
  58737. this.updateMaterial(data);
  58738. utils.material.updateMap(this, data);
  58739. },
  58740. /**
  58741. * Updating existing material.
  58742. *
  58743. * @param {object} data - Material component data.
  58744. */
  58745. updateMaterial: function (data) {
  58746. var key;
  58747. getMaterialData(data, this.materialData);
  58748. this.rendererSystem.applyColorCorrection(this.materialData.color);
  58749. for (key in this.materialData) {
  58750. this.material[key] = this.materialData[key];
  58751. }
  58752. }
  58753. });
  58754. /**
  58755. * Builds and normalize material data, normalizing stuff along the way.
  58756. *
  58757. * @param {object} data - Material data.
  58758. * @param {object} materialData - Object to reuse.
  58759. * @returns {object} Updated material data.
  58760. */
  58761. function getMaterialData (data, materialData) {
  58762. materialData.color.set(data.color);
  58763. materialData.fog = data.fog;
  58764. materialData.wireframe = data.wireframe;
  58765. materialData.wireframeLinewidth = data.wireframeLinewidth;
  58766. return materialData;
  58767. }
  58768. },{"../core/shader":145,"../lib/three":183,"../utils/":210}],185:[function(require,module,exports){
  58769. require('./flat');
  58770. require('./standard');
  58771. require('./sdf');
  58772. require('./msdf');
  58773. require('./ios10hls');
  58774. require('./shadow');
  58775. },{"./flat":184,"./ios10hls":186,"./msdf":187,"./sdf":188,"./shadow":189,"./standard":190}],186:[function(require,module,exports){
  58776. var registerShader = require('../core/shader').registerShader;
  58777. /**
  58778. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  58779. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  58780. */
  58781. module.exports.Shader = registerShader('ios10hls', {
  58782. schema: {
  58783. src: {type: 'map', is: 'uniform'},
  58784. opacity: {type: 'number', is: 'uniform', default: 1}
  58785. },
  58786. vertexShader: [
  58787. 'varying vec2 vUV;',
  58788. 'void main(void) {',
  58789. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  58790. ' vUV = uv;',
  58791. '}'
  58792. ].join('\n'),
  58793. fragmentShader: [
  58794. 'uniform sampler2D src;',
  58795. 'uniform float opacity;',
  58796. 'varying vec2 vUV;',
  58797. 'void main() {',
  58798. ' vec2 offset = vec2(0, 0);',
  58799. ' vec2 repeat = vec2(1, 1);',
  58800. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  58801. ' gl_FragColor = vec4(color.rgb, opacity);',
  58802. '}'
  58803. ].join('\n')
  58804. });
  58805. },{"../core/shader":145}],187:[function(require,module,exports){
  58806. var registerShader = require('../core/shader').registerShader;
  58807. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  58808. var VERTEX_SHADER_WEBGL1 = [
  58809. 'attribute vec2 uv;',
  58810. 'attribute vec3 position;',
  58811. 'uniform mat4 projectionMatrix;',
  58812. 'uniform mat4 modelViewMatrix;',
  58813. 'varying vec2 vUV;',
  58814. 'void main(void) {',
  58815. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  58816. ' vUV = uv;',
  58817. '}'
  58818. ].join('\n');
  58819. var VERTEX_SHADER_WEBGL2 = [
  58820. '#version 300 es',
  58821. 'in vec2 uv;',
  58822. 'in vec3 position;',
  58823. 'uniform mat4 projectionMatrix;',
  58824. 'uniform mat4 modelViewMatrix;',
  58825. 'out vec2 vUV;',
  58826. 'void main(void) {',
  58827. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  58828. ' vUV = uv;',
  58829. '}'
  58830. ].join('\n');
  58831. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  58832. var FRAGMENT_SHADER_WEBGL1 = [
  58833. '#ifdef GL_OES_standard_derivatives',
  58834. '#extension GL_OES_standard_derivatives: enable',
  58835. '#endif',
  58836. 'precision highp float;',
  58837. 'uniform bool negate;',
  58838. 'uniform float alphaTest;',
  58839. 'uniform float opacity;',
  58840. 'uniform sampler2D map;',
  58841. 'uniform vec3 color;',
  58842. 'varying vec2 vUV;',
  58843. 'float median(float r, float g, float b) {',
  58844. ' return max(min(r, g), min(max(r, g), b));',
  58845. '}',
  58846. // FIXME: Experimentally determined constants.
  58847. '#define BIG_ENOUGH 0.001',
  58848. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  58849. 'void main() {',
  58850. ' vec3 sampleColor = texture2D(map, vUV).rgb;',
  58851. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  58852. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  58853. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  58854. ' float dscale = 0.353505;',
  58855. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  58856. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  58857. // When texel is too small, blend raw alpha value rather than supersampling.
  58858. // FIXME: Experimentally determined constant.
  58859. ' // Do modified alpha test.',
  58860. ' if (isBigEnough > BIG_ENOUGH) {',
  58861. ' float ratio = BIG_ENOUGH / isBigEnough;',
  58862. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  58863. ' }',
  58864. ' // Do modified alpha test.',
  58865. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  58866. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  58867. '}'
  58868. ].join('\n');
  58869. var FRAGMENT_SHADER_WEBGL2 = [
  58870. '#version 300 es',
  58871. 'precision highp float;',
  58872. 'uniform bool negate;',
  58873. 'uniform float alphaTest;',
  58874. 'uniform float opacity;',
  58875. 'uniform sampler2D map;',
  58876. 'uniform vec3 color;',
  58877. 'in vec2 vUV;',
  58878. 'out vec4 fragColor;',
  58879. 'float median(float r, float g, float b) {',
  58880. ' return max(min(r, g), min(max(r, g), b));',
  58881. '}',
  58882. // FIXME: Experimentally determined constants.
  58883. '#define BIG_ENOUGH 0.001',
  58884. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  58885. 'void main() {',
  58886. ' vec3 sampleColor = texture(map, vUV).rgb;',
  58887. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  58888. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  58889. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  58890. ' float dscale = 0.353505;',
  58891. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  58892. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  58893. // When texel is too small, blend raw alpha value rather than supersampling.
  58894. // FIXME: Experimentally determined constant.
  58895. ' // Do modified alpha test.',
  58896. ' if (isBigEnough > BIG_ENOUGH) {',
  58897. ' float ratio = BIG_ENOUGH / isBigEnough;',
  58898. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  58899. ' }',
  58900. ' // Do modified alpha test.',
  58901. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  58902. ' fragColor = vec4(color.xyz, alpha * opacity);',
  58903. '}'
  58904. ].join('\n');
  58905. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  58906. /**
  58907. * Multi-channel signed distance field.
  58908. * Used by text component.
  58909. */
  58910. module.exports.Shader = registerShader('msdf', {
  58911. schema: {
  58912. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  58913. color: {type: 'color', is: 'uniform', default: 'white'},
  58914. map: {type: 'map', is: 'uniform'},
  58915. negate: {type: 'boolean', is: 'uniform', default: true},
  58916. opacity: {type: 'number', is: 'uniform', default: 1.0}
  58917. },
  58918. raw: true,
  58919. vertexShader: VERTEX_SHADER,
  58920. fragmentShader: FRAGMENT_SHADER
  58921. });
  58922. },{"../core/shader":145}],188:[function(require,module,exports){
  58923. var registerShader = require('../core/shader').registerShader;
  58924. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  58925. var VERTEX_SHADER_WEBGL1 = [
  58926. 'attribute vec2 uv;',
  58927. 'attribute vec3 position;',
  58928. 'uniform mat4 projectionMatrix;',
  58929. 'uniform mat4 modelViewMatrix;',
  58930. 'varying vec2 vUV;',
  58931. 'void main(void) {',
  58932. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  58933. ' vUV = uv;',
  58934. '}'
  58935. ].join('\n');
  58936. var VERTEX_SHADER_WEBGL2 = [
  58937. '#version 300 es',
  58938. 'in vec2 uv;',
  58939. 'in vec3 position;',
  58940. 'uniform mat4 projectionMatrix;',
  58941. 'uniform mat4 modelViewMatrix;',
  58942. 'out vec2 vUV;',
  58943. 'void main(void) {',
  58944. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  58945. ' vUV = uv;',
  58946. '}'
  58947. ].join('\n');
  58948. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  58949. var FRAGMENT_SHADER_WEBGL1 = [
  58950. '#ifdef GL_OES_standard_derivatives',
  58951. '#extension GL_OES_standard_derivatives: enable',
  58952. '#endif',
  58953. 'precision highp float;',
  58954. 'uniform float alphaTest;',
  58955. 'uniform float opacity;',
  58956. 'uniform sampler2D map;',
  58957. 'uniform vec3 color;',
  58958. 'varying vec2 vUV;',
  58959. '#ifdef GL_OES_standard_derivatives',
  58960. ' float contour(float width, float value) {',
  58961. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  58962. ' }',
  58963. '#else',
  58964. ' float aastep(float value, float afwidth) {',
  58965. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  58966. ' }',
  58967. '#endif',
  58968. // FIXME: Experimentally determined constants.
  58969. '#define BIG_ENOUGH 0.001',
  58970. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  58971. '#define ALL_SMOOTH 0.4',
  58972. '#define ALL_ROUGH 0.02',
  58973. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  58974. 'void main() {',
  58975. // When we have derivatives and can get texel size for supersampling.
  58976. ' #ifdef GL_OES_standard_derivatives',
  58977. ' vec2 uv = vUV;',
  58978. ' vec4 texColor = texture2D(map, uv);',
  58979. ' float dist = texColor.a;',
  58980. ' float width = fwidth(dist);',
  58981. ' float alpha = contour(dist, width);',
  58982. ' float dscale = 0.353505;',
  58983. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  58984. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  58985. // When texel is too small, blend raw alpha value rather than supersampling.
  58986. // FIXME: experimentally determined constant
  58987. ' if (isBigEnough > BIG_ENOUGH) {',
  58988. ' float ratio = BIG_ENOUGH / isBigEnough;',
  58989. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  58990. ' }',
  58991. // Otherwise do weighted supersampling.
  58992. // FIXME: why this weighting?
  58993. ' if (isBigEnough <= BIG_ENOUGH) {',
  58994. ' vec4 box = vec4 (uv - duv, uv + duv);',
  58995. ' alpha = (alpha + 0.5 * (',
  58996. ' contour(texture2D(map, box.xy).a, width)',
  58997. ' + contour(texture2D(map, box.zw).a, width)',
  58998. ' + contour(texture2D(map, box.xw).a, width)',
  58999. ' + contour(texture2D(map, box.zy).a, width)',
  59000. ' )) / 3.0;',
  59001. ' }',
  59002. // Do modified alpha test.
  59003. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59004. ' #else',
  59005. // When we don't have derivatives, use approximations.
  59006. ' vec4 texColor = texture2D(map, vUV);',
  59007. ' float value = texColor.a;',
  59008. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59009. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59010. ' float alpha = aastep(value, afwidth);',
  59011. // Use gl_FragCoord.w to guess when we should blend.
  59012. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59013. ' 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);',
  59014. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59015. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59016. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59017. ' #endif',
  59018. ' gl_FragColor = vec4(color, opacity * alpha);',
  59019. '}'
  59020. ].join('\n');
  59021. var FRAGMENT_SHADER_WEBGL2 = [
  59022. '#version 300 es',
  59023. 'precision highp float;',
  59024. 'uniform float alphaTest;',
  59025. 'uniform float opacity;',
  59026. 'uniform sampler2D map;',
  59027. 'uniform vec3 color;',
  59028. 'in vec2 vUV;',
  59029. 'out vec4 fragColor;',
  59030. '#ifdef GL_OES_standard_derivatives',
  59031. ' float contour(float width, float value) {',
  59032. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59033. ' }',
  59034. '#else',
  59035. ' float aastep(float value, float afwidth) {',
  59036. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59037. ' }',
  59038. '#endif',
  59039. // FIXME: Experimentally determined constants.
  59040. '#define BIG_ENOUGH 0.001',
  59041. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59042. '#define ALL_SMOOTH 0.4',
  59043. '#define ALL_ROUGH 0.02',
  59044. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59045. 'void main() {',
  59046. // When we have derivatives and can get texel size for supersampling.
  59047. ' #ifdef GL_OES_standard_derivatives',
  59048. ' vec2 uv = vUV;',
  59049. ' vec4 texColor = texture(map, uv);',
  59050. ' float dist = texColor.a;',
  59051. ' float width = fwidth(dist);',
  59052. ' float alpha = contour(dist, width);',
  59053. ' float dscale = 0.353505;',
  59054. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59055. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59056. // When texel is too small, blend raw alpha value rather than supersampling.
  59057. // FIXME: experimentally determined constant
  59058. ' if (isBigEnough > BIG_ENOUGH) {',
  59059. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59060. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59061. ' }',
  59062. // Otherwise do weighted supersampling.
  59063. // FIXME: why this weighting?
  59064. ' if (isBigEnough <= BIG_ENOUGH) {',
  59065. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59066. ' alpha = (alpha + 0.5 * (',
  59067. ' contour(texture(map, box.xy).a, width)',
  59068. ' + contour(texture(map, box.zw).a, width)',
  59069. ' + contour(texture(map, box.xw).a, width)',
  59070. ' + contour(texture(map, box.zy).a, width)',
  59071. ' )) / 3.0;',
  59072. ' }',
  59073. // Do modified alpha test.
  59074. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59075. ' #else',
  59076. // When we don't have derivatives, use approximations.
  59077. ' vec4 texColor = texture(map, vUV);',
  59078. ' float value = texColor.a;',
  59079. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59080. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59081. ' float alpha = aastep(value, afwidth);',
  59082. // Use gl_FragCoord.w to guess when we should blend.
  59083. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59084. ' 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);',
  59085. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59086. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59087. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59088. ' #endif',
  59089. ' fragColor = vec4(color, opacity * alpha);',
  59090. '}'
  59091. ].join('\n');
  59092. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59093. /**
  59094. * Signed distance field.
  59095. * Used by text component.
  59096. */
  59097. module.exports.Shader = registerShader('sdf', {
  59098. schema: {
  59099. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59100. color: {type: 'color', is: 'uniform', default: 'white'},
  59101. map: {type: 'map', is: 'uniform'},
  59102. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59103. },
  59104. raw: true,
  59105. vertexShader: VERTEX_SHADER,
  59106. fragmentShader: FRAGMENT_SHADER
  59107. });
  59108. },{"../core/shader":145}],189:[function(require,module,exports){
  59109. var registerShader = require('../core/shader').registerShader;
  59110. var THREE = require('../lib/three');
  59111. /**
  59112. * Flat shader using THREE.ShadowMaterial.
  59113. */
  59114. module.exports.Shader = registerShader('shadow', {
  59115. schema: {
  59116. opacity: {default: 0.5},
  59117. transparent: {default: true},
  59118. alphaToCoverage: {default: true}
  59119. },
  59120. /**
  59121. * Initializes the shader.
  59122. * Adds a reference from the scene to this entity as the camera.
  59123. */
  59124. init: function (data) {
  59125. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59126. this.material = new THREE.ShadowMaterial();
  59127. },
  59128. update: function (data) {
  59129. this.material.opacity = data.opacity;
  59130. this.material.alphaToCoverage = data.alphaToCoverage;
  59131. this.material.transparent = data.transparent;
  59132. }
  59133. });
  59134. },{"../core/shader":145,"../lib/three":183}],190:[function(require,module,exports){
  59135. var registerShader = require('../core/shader').registerShader;
  59136. var THREE = require('../lib/three');
  59137. var utils = require('../utils/');
  59138. var CubeLoader = new THREE.CubeTextureLoader();
  59139. var texturePromises = {};
  59140. /**
  59141. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  59142. */
  59143. module.exports.Shader = registerShader('standard', {
  59144. schema: {
  59145. ambientOcclusionMap: {type: 'map'},
  59146. ambientOcclusionMapIntensity: {default: 1},
  59147. ambientOcclusionTextureOffset: {type: 'vec2'},
  59148. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59149. color: {type: 'color'},
  59150. displacementMap: {type: 'map'},
  59151. displacementScale: {default: 1},
  59152. displacementBias: {default: 0.5},
  59153. displacementTextureOffset: {type: 'vec2'},
  59154. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59155. emissive: {type: 'color', default: '#000'},
  59156. emissiveIntensity: {default: 1},
  59157. envMap: {default: ''},
  59158. fog: {default: true},
  59159. height: {default: 256},
  59160. metalness: {default: 0.0, min: 0.0, max: 1.0},
  59161. metalnessMap: {type: 'map'},
  59162. metalnessTextureOffset: {type: 'vec2'},
  59163. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59164. normalMap: {type: 'map'},
  59165. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  59166. normalTextureOffset: {type: 'vec2'},
  59167. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59168. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59169. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59170. roughness: {default: 0.5, min: 0.0, max: 1.0},
  59171. roughnessMap: {type: 'map'},
  59172. roughnessTextureOffset: {type: 'vec2'},
  59173. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59174. sphericalEnvMap: {type: 'map'},
  59175. src: {type: 'map'},
  59176. width: {default: 512},
  59177. wireframe: {default: false},
  59178. wireframeLinewidth: {default: 2}
  59179. },
  59180. /**
  59181. * Initializes the shader.
  59182. * Adds a reference from the scene to this entity as the camera.
  59183. */
  59184. init: function (data) {
  59185. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59186. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  59187. getMaterialData(data, this.materialData);
  59188. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59189. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59190. this.material = new THREE.MeshStandardMaterial(this.materialData);
  59191. utils.material.updateMap(this, data);
  59192. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59193. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59194. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59195. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59196. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59197. this.updateEnvMap(data);
  59198. },
  59199. update: function (data) {
  59200. this.updateMaterial(data);
  59201. utils.material.updateMap(this, data);
  59202. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59203. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59204. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59205. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59206. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59207. this.updateEnvMap(data);
  59208. },
  59209. /**
  59210. * Updating existing material.
  59211. *
  59212. * @param {object} data - Material component data.
  59213. * @returns {object} Material.
  59214. */
  59215. updateMaterial: function (data) {
  59216. var key;
  59217. var material = this.material;
  59218. getMaterialData(data, this.materialData);
  59219. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59220. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59221. for (key in this.materialData) {
  59222. material[key] = this.materialData[key];
  59223. }
  59224. },
  59225. /**
  59226. * Handle environment cubemap. Textures are cached in texturePromises.
  59227. */
  59228. updateEnvMap: function (data) {
  59229. var self = this;
  59230. var material = this.material;
  59231. var envMap = data.envMap;
  59232. var sphericalEnvMap = data.sphericalEnvMap;
  59233. // No envMap defined or already loading.
  59234. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  59235. material.envMap = null;
  59236. material.needsUpdate = true;
  59237. return;
  59238. }
  59239. this.isLoadingEnvMap = true;
  59240. // if a spherical env map is defined then use it.
  59241. if (sphericalEnvMap) {
  59242. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  59243. self.isLoadingEnvMap = false;
  59244. texture.mapping = THREE.EquirectangularReflectionMapping;
  59245. material.envMap = texture;
  59246. utils.material.handleTextureEvents(self.el, texture);
  59247. material.needsUpdate = true;
  59248. });
  59249. return;
  59250. }
  59251. // Another material is already loading this texture. Wait on promise.
  59252. if (texturePromises[envMap]) {
  59253. texturePromises[envMap].then(function (cube) {
  59254. self.isLoadingEnvMap = false;
  59255. material.envMap = cube;
  59256. utils.material.handleTextureEvents(self.el, cube);
  59257. material.needsUpdate = true;
  59258. });
  59259. return;
  59260. }
  59261. // Material is first to load this texture. Load and resolve texture.
  59262. texturePromises[envMap] = new Promise(function (resolve) {
  59263. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  59264. CubeLoader.load(urls, function (cube) {
  59265. // Texture loaded.
  59266. self.isLoadingEnvMap = false;
  59267. material.envMap = cube;
  59268. utils.material.handleTextureEvents(self.el, cube);
  59269. resolve(cube);
  59270. });
  59271. });
  59272. });
  59273. }
  59274. });
  59275. /**
  59276. * Builds and normalize material data, normalizing stuff along the way.
  59277. *
  59278. * @param {object} data - Material data.
  59279. * @param {object} materialData - Object to use.
  59280. * @returns {object} Updated materialData.
  59281. */
  59282. function getMaterialData (data, materialData) {
  59283. materialData.color.set(data.color);
  59284. materialData.emissive.set(data.emissive);
  59285. materialData.emissiveIntensity = data.emissiveIntensity;
  59286. materialData.fog = data.fog;
  59287. materialData.metalness = data.metalness;
  59288. materialData.roughness = data.roughness;
  59289. materialData.wireframe = data.wireframe;
  59290. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59291. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  59292. if (data.ambientOcclusionMap) {
  59293. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  59294. }
  59295. if (data.displacementMap) {
  59296. materialData.displacementScale = data.displacementScale;
  59297. materialData.displacementBias = data.displacementBias;
  59298. }
  59299. return materialData;
  59300. }
  59301. },{"../core/shader":145,"../lib/three":183,"../utils/":210}],191:[function(require,module,exports){
  59302. 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%}.a-dom-overlay:not(.a-no-style){overflow:hidden;position:absolute;pointer-events:none;box-sizing:border-box;bottom:0;left:0;right:0;top:0;padding:1em}.a-dom-overlay:not(.a-no-style)>*{pointer-events:auto}"; (require("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  59303. },{"browserify-css":4}],192:[function(require,module,exports){
  59304. 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}}"; (require("browserify-css").createStyle(css, { "href": "src/style/rStats.css"})); module.exports = css;
  59305. },{"browserify-css":4}],193:[function(require,module,exports){
  59306. var constants = require('../constants/');
  59307. var registerSystem = require('../core/system').registerSystem;
  59308. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  59309. /**
  59310. * Camera system. Manages which camera is active among multiple cameras in scene.
  59311. *
  59312. * @member {object} activeCameraEl - Active camera entity.
  59313. */
  59314. module.exports.System = registerSystem('camera', {
  59315. init: function () {
  59316. this.activeCameraEl = null;
  59317. this.render = this.render.bind(this);
  59318. this.unwrapRender = this.unwrapRender.bind(this);
  59319. this.wrapRender = this.wrapRender.bind(this);
  59320. this.initialCameraFound = false;
  59321. this.numUserCameras = 0;
  59322. this.numUserCamerasChecked = 0;
  59323. this.setupInitialCamera();
  59324. },
  59325. /**
  59326. * Setup initial camera, either searching for camera or
  59327. * creating a default camera if user has not added one during the initial scene traversal.
  59328. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  59329. * loads.
  59330. *
  59331. * Default camera offset height is at average eye level (~1.6m).
  59332. */
  59333. setupInitialCamera: function () {
  59334. var cameraEls;
  59335. var i;
  59336. var sceneEl = this.sceneEl;
  59337. var self = this;
  59338. // Camera already defined or the one defined it is an spectator one.
  59339. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  59340. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  59341. return;
  59342. }
  59343. // Search for initial user-defined camera.
  59344. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  59345. // No user cameras, create default one.
  59346. if (!cameraEls.length) {
  59347. this.createDefaultCamera();
  59348. return;
  59349. }
  59350. this.numUserCameras = cameraEls.length;
  59351. for (i = 0; i < cameraEls.length; i++) {
  59352. cameraEls[i].addEventListener('object3dset', function (evt) {
  59353. if (evt.detail.type !== 'camera') { return; }
  59354. self.checkUserCamera(this);
  59355. });
  59356. // Load camera and wait for camera to initialize.
  59357. if (cameraEls[i].isNode) {
  59358. cameraEls[i].load();
  59359. } else {
  59360. cameraEls[i].addEventListener('nodeready', function () {
  59361. this.load();
  59362. });
  59363. }
  59364. }
  59365. },
  59366. /**
  59367. * Check if a user-defined camera entity is appropriate to be initial camera.
  59368. * (active + non-spectator).
  59369. *
  59370. * Keep track of the number of cameras we checked and whether we found one.
  59371. */
  59372. checkUserCamera: function (cameraEl) {
  59373. var cameraData;
  59374. var sceneEl = this.el.sceneEl;
  59375. this.numUserCamerasChecked++;
  59376. // Already found one.
  59377. if (this.initialCameraFound) { return; }
  59378. // Check if camera is appropriate for being the initial camera.
  59379. cameraData = cameraEl.getAttribute('camera');
  59380. if (!cameraData.active || cameraData.spectator) {
  59381. // No user cameras eligible, create default camera.
  59382. if (this.numUserCamerasChecked === this.numUserCameras) {
  59383. this.createDefaultCamera();
  59384. }
  59385. return;
  59386. }
  59387. this.initialCameraFound = true;
  59388. sceneEl.camera = cameraEl.getObject3D('camera');
  59389. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  59390. },
  59391. createDefaultCamera: function () {
  59392. var defaultCameraEl;
  59393. var sceneEl = this.sceneEl;
  59394. // Set up default camera.
  59395. defaultCameraEl = document.createElement('a-entity');
  59396. defaultCameraEl.setAttribute('camera', {active: true});
  59397. defaultCameraEl.setAttribute('position', {
  59398. x: 0,
  59399. y: constants.DEFAULT_CAMERA_HEIGHT,
  59400. z: 0
  59401. });
  59402. defaultCameraEl.setAttribute('wasd-controls', '');
  59403. defaultCameraEl.setAttribute('look-controls', '');
  59404. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  59405. defaultCameraEl.addEventListener('object3dset', function (evt) {
  59406. if (evt.detail.type !== 'camera') { return; }
  59407. sceneEl.camera = evt.detail.object;
  59408. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  59409. });
  59410. sceneEl.appendChild(defaultCameraEl);
  59411. },
  59412. /**
  59413. * Set a different active camera.
  59414. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  59415. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  59416. * the new camera.
  59417. */
  59418. disableActiveCamera: function () {
  59419. var cameraEls;
  59420. var newActiveCameraEl;
  59421. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  59422. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  59423. newActiveCameraEl.setAttribute('camera', 'active', true);
  59424. },
  59425. /**
  59426. * Set active camera to be used by renderer.
  59427. * Removes the default camera (if present).
  59428. * Disables all other cameras in the scene.
  59429. *
  59430. * @param {Element} newCameraEl - Entity with camera component.
  59431. */
  59432. setActiveCamera: function (newCameraEl) {
  59433. var cameraEl;
  59434. var cameraEls;
  59435. var i;
  59436. var newCamera;
  59437. var previousCamera = this.activeCameraEl;
  59438. var sceneEl = this.sceneEl;
  59439. // Same camera.
  59440. newCamera = newCameraEl.getObject3D('camera');
  59441. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  59442. // Grab the default camera.
  59443. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59444. var defaultCameraEl = defaultCameraWrapper &&
  59445. defaultCameraWrapper.querySelector('[camera]');
  59446. // Remove default camera if new camera is not the default camera.
  59447. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  59448. // Make new camera active.
  59449. this.activeCameraEl = newCameraEl;
  59450. this.activeCameraEl.play();
  59451. sceneEl.camera = newCamera;
  59452. // Disable current camera
  59453. if (previousCamera) {
  59454. previousCamera.setAttribute('camera', 'active', false);
  59455. }
  59456. // Disable other cameras in the scene
  59457. cameraEls = sceneEl.querySelectorAll('[camera]');
  59458. for (i = 0; i < cameraEls.length; i++) {
  59459. cameraEl = cameraEls[i];
  59460. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  59461. cameraEl.setAttribute('camera', 'active', false);
  59462. cameraEl.pause();
  59463. }
  59464. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  59465. },
  59466. /**
  59467. * Set spectator camera to render the scene on a 2D display.
  59468. *
  59469. * @param {Element} newCameraEl - Entity with camera component.
  59470. */
  59471. setSpectatorCamera: function (newCameraEl) {
  59472. var newCamera;
  59473. var previousCamera = this.spectatorCameraEl;
  59474. var sceneEl = this.sceneEl;
  59475. var spectatorCameraEl;
  59476. // Same camera.
  59477. newCamera = newCameraEl.getObject3D('camera');
  59478. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  59479. // Disable current camera
  59480. if (previousCamera) {
  59481. previousCamera.setAttribute('camera', 'spectator', false);
  59482. }
  59483. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  59484. sceneEl.addEventListener('enter-vr', this.wrapRender);
  59485. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  59486. spectatorCameraEl.setAttribute('camera', 'active', false);
  59487. spectatorCameraEl.play();
  59488. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  59489. },
  59490. /**
  59491. * Disables current spectator camera.
  59492. */
  59493. disableSpectatorCamera: function () {
  59494. this.spectatorCameraEl = undefined;
  59495. },
  59496. /**
  59497. * Wrap the render method of the renderer to render
  59498. * the spectator camera after vrDisplay.submitFrame.
  59499. */
  59500. wrapRender: function () {
  59501. if (!this.spectatorCameraEl || this.originalRender) { return; }
  59502. this.originalRender = this.sceneEl.renderer.render;
  59503. this.sceneEl.renderer.render = this.render;
  59504. },
  59505. unwrapRender: function () {
  59506. if (!this.originalRender) { return; }
  59507. this.sceneEl.renderer.render = this.originalRender;
  59508. this.originalRender = undefined;
  59509. },
  59510. render: function (scene, camera) {
  59511. var isVREnabled;
  59512. var sceneEl = this.sceneEl;
  59513. var spectatorCamera;
  59514. isVREnabled = sceneEl.renderer.xr.enabled;
  59515. this.originalRender.call(sceneEl.renderer, scene, camera);
  59516. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  59517. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  59518. sceneEl.renderer.xr.enabled = false;
  59519. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  59520. sceneEl.renderer.xr.enabled = isVREnabled;
  59521. }
  59522. });
  59523. /**
  59524. * Remove injected default camera from scene, if present.
  59525. *
  59526. * @param {Element} sceneEl
  59527. */
  59528. function removeDefaultCamera (sceneEl) {
  59529. var defaultCamera;
  59530. var camera = sceneEl.camera;
  59531. if (!camera) { return; }
  59532. // Remove default camera if present.
  59533. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59534. if (!defaultCamera) { return; }
  59535. sceneEl.removeChild(defaultCamera);
  59536. }
  59537. },{"../constants/":127,"../core/system":146}],194:[function(require,module,exports){
  59538. var geometries = require('../core/geometry').geometries;
  59539. var registerSystem = require('../core/system').registerSystem;
  59540. /**
  59541. * System for geometry component.
  59542. * Handle geometry caching.
  59543. *
  59544. * @member {object} cache - Mapping of stringified component data to THREE.BufferGeometry objects.
  59545. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  59546. * know whether to dispose on removal.
  59547. */
  59548. module.exports.System = registerSystem('geometry', {
  59549. init: function () {
  59550. this.cache = {};
  59551. this.cacheCount = {};
  59552. },
  59553. /**
  59554. * Reset cache. Mainly for testing.
  59555. */
  59556. clearCache: function () {
  59557. this.cache = {};
  59558. this.cacheCount = {};
  59559. },
  59560. /**
  59561. * Attempt to retrieve from cache.
  59562. *
  59563. * @returns {Object|null} A geometry if it exists, else null.
  59564. */
  59565. getOrCreateGeometry: function (data) {
  59566. var cache = this.cache;
  59567. var cachedGeometry;
  59568. var hash;
  59569. // Skip all caching logic.
  59570. if (data.skipCache) { return createGeometry(data); }
  59571. // Try to retrieve from cache first.
  59572. hash = this.hash(data);
  59573. cachedGeometry = cache[hash];
  59574. incrementCacheCount(this.cacheCount, hash);
  59575. if (cachedGeometry) { return cachedGeometry; }
  59576. // Create geometry.
  59577. cachedGeometry = createGeometry(data);
  59578. // Cache and return geometry.
  59579. cache[hash] = cachedGeometry;
  59580. return cachedGeometry;
  59581. },
  59582. /**
  59583. * Let system know that an entity is no longer using a geometry.
  59584. */
  59585. unuseGeometry: function (data) {
  59586. var cache = this.cache;
  59587. var cacheCount = this.cacheCount;
  59588. var geometry;
  59589. var hash;
  59590. if (data.skipCache) { return; }
  59591. hash = this.hash(data);
  59592. if (!cache[hash]) { return; }
  59593. decrementCacheCount(cacheCount, hash);
  59594. // Another entity is still using this geometry. No need to do anything.
  59595. if (cacheCount[hash] > 0) { return; }
  59596. // No more entities are using this geometry. Dispose.
  59597. geometry = cache[hash];
  59598. geometry.dispose();
  59599. delete cache[hash];
  59600. delete cacheCount[hash];
  59601. },
  59602. /**
  59603. * Use JSON.stringify to turn component data into hash.
  59604. * Should be deterministic within a single browser engine.
  59605. * If not, then look into json-stable-stringify.
  59606. */
  59607. hash: function (data) {
  59608. return JSON.stringify(data);
  59609. }
  59610. });
  59611. /**
  59612. * Create geometry using component data.
  59613. *
  59614. * @param {object} data - Component data.
  59615. * @returns {object} Geometry.
  59616. */
  59617. function createGeometry (data) {
  59618. var geometryType = data.primitive;
  59619. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  59620. var geometryInstance = new GeometryClass();
  59621. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  59622. geometryInstance.init(data);
  59623. return geometryInstance.geometry;
  59624. }
  59625. /**
  59626. * Decreate count of entity using a geometry.
  59627. */
  59628. function decrementCacheCount (cacheCount, hash) {
  59629. cacheCount[hash]--;
  59630. }
  59631. /**
  59632. * Increase count of entity using a geometry.
  59633. */
  59634. function incrementCacheCount (cacheCount, hash) {
  59635. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  59636. }
  59637. },{"../core/geometry":136,"../core/system":146}],195:[function(require,module,exports){
  59638. var registerSystem = require('../core/system').registerSystem;
  59639. var THREE = require('../lib/three');
  59640. function fetchScript (src) {
  59641. return new Promise(function (resolve, reject) {
  59642. var script = document.createElement('script');
  59643. document.body.appendChild(script);
  59644. script.onload = resolve;
  59645. script.onerror = reject;
  59646. script.async = true;
  59647. script.src = src;
  59648. });
  59649. }
  59650. /**
  59651. * glTF model system.
  59652. *
  59653. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  59654. * provided externally.
  59655. *
  59656. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  59657. * @param {string} meshoptDecoderPath - Full path from which to load Meshopt decoder.
  59658. */
  59659. module.exports.System = registerSystem('gltf-model', {
  59660. schema: {
  59661. dracoDecoderPath: {default: ''},
  59662. meshoptDecoderPath: {default: ''}
  59663. },
  59664. init: function () {
  59665. this.update();
  59666. },
  59667. update: function () {
  59668. var dracoDecoderPath = this.data.dracoDecoderPath;
  59669. var meshoptDecoderPath = this.data.meshoptDecoderPath;
  59670. if (!this.dracoLoader && dracoDecoderPath) {
  59671. this.dracoLoader = new THREE.DRACOLoader();
  59672. this.dracoLoader.setDecoderPath(dracoDecoderPath);
  59673. }
  59674. if (!this.meshoptDecoder && meshoptDecoderPath) {
  59675. this.meshoptDecoder = fetchScript(meshoptDecoderPath)
  59676. .then(function () { return window.MeshoptDecoder.ready; })
  59677. .then(function () { return window.MeshoptDecoder; });
  59678. }
  59679. },
  59680. getDRACOLoader: function () {
  59681. return this.dracoLoader;
  59682. },
  59683. getMeshoptDecoder: function () {
  59684. return this.meshoptDecoder;
  59685. }
  59686. });
  59687. },{"../core/system":146,"../lib/three":183}],196:[function(require,module,exports){
  59688. require('./camera');
  59689. require('./geometry');
  59690. require('./gltf-model');
  59691. require('./light');
  59692. require('./material');
  59693. require('./renderer');
  59694. require('./shadow');
  59695. require('./tracked-controls-webvr');
  59696. require('./tracked-controls-webxr');
  59697. require('./webxr');
  59698. },{"./camera":193,"./geometry":194,"./gltf-model":195,"./light":197,"./material":198,"./renderer":199,"./shadow":200,"./tracked-controls-webvr":201,"./tracked-controls-webxr":202,"./webxr":203}],197:[function(require,module,exports){
  59699. var registerSystem = require('../core/system').registerSystem;
  59700. var bind = require('../utils/bind');
  59701. var constants = require('../constants/');
  59702. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  59703. /**
  59704. * Light system.
  59705. *
  59706. * Prescribes default lighting if not specified (one ambient, one directional).
  59707. * Removes default lighting from the scene when a new light is added.
  59708. *
  59709. * @param {bool} defaultLights - Whether default lighting are defined.
  59710. * @param {bool} userDefinedLights - Whether user lighting is defined.
  59711. */
  59712. module.exports.System = registerSystem('light', {
  59713. schema: {
  59714. defaultLightsEnabled: {default: true}
  59715. },
  59716. init: function () {
  59717. this.defaultLights = false;
  59718. this.userDefinedLights = false;
  59719. // Wait for all entities to fully load before checking for existence of lights.
  59720. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  59721. // will do so asynchronously.
  59722. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  59723. },
  59724. /**
  59725. * Notify scene that light has been added and to remove the default.
  59726. *
  59727. * @param {object} el - element holding the light component.
  59728. */
  59729. registerLight: function (el) {
  59730. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  59731. // User added a light, remove default lights through DOM.
  59732. this.removeDefaultLights();
  59733. this.userDefinedLights = true;
  59734. }
  59735. },
  59736. removeDefaultLights: function () {
  59737. var defaultLights;
  59738. var sceneEl = this.sceneEl;
  59739. if (!this.defaultLights) { return; }
  59740. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  59741. for (var i = 0; i < defaultLights.length; i++) {
  59742. sceneEl.removeChild(defaultLights[i]);
  59743. }
  59744. this.defaultLights = false;
  59745. },
  59746. /**
  59747. * Prescibe default lights to the scene.
  59748. * Does so by injecting markup such that this state is not invisible.
  59749. * These lights are removed if the user adds any lights.
  59750. */
  59751. setupDefaultLights: function () {
  59752. var sceneEl = this.sceneEl;
  59753. var ambientLight;
  59754. var directionalLight;
  59755. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  59756. return;
  59757. }
  59758. ambientLight = document.createElement('a-entity');
  59759. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  59760. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  59761. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  59762. sceneEl.appendChild(ambientLight);
  59763. directionalLight = document.createElement('a-entity');
  59764. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  59765. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  59766. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  59767. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  59768. sceneEl.appendChild(directionalLight);
  59769. this.defaultLights = true;
  59770. }
  59771. });
  59772. },{"../constants/":127,"../core/system":146,"../utils/bind":204}],198:[function(require,module,exports){
  59773. var registerSystem = require('../core/system').registerSystem;
  59774. var THREE = require('../lib/three');
  59775. var utils = require('../utils/');
  59776. var isHLS = require('../utils/material').isHLS;
  59777. var setTextureProperties = require('../utils/material').setTextureProperties;
  59778. var bind = utils.bind;
  59779. var debug = utils.debug;
  59780. var error = debug('components:texture:error');
  59781. var TextureLoader = new THREE.TextureLoader();
  59782. var warn = debug('components:texture:warn');
  59783. TextureLoader.setCrossOrigin('anonymous');
  59784. /**
  59785. * System for material component.
  59786. * Handle material registration, updates (for fog), and texture caching.
  59787. *
  59788. * @member {object} materials - Registered materials.
  59789. * @member {object} textureCounts - Number of times each texture is used. Tracked
  59790. * separately from textureCache, because the cache (1) is populated in
  59791. * multiple places, and (2) may be cleared at any time.
  59792. * @member {object} textureCache - Texture cache for:
  59793. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  59794. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  59795. */
  59796. module.exports.System = registerSystem('material', {
  59797. init: function () {
  59798. this.materials = {};
  59799. this.textureCounts = {};
  59800. this.textureCache = {};
  59801. this.sceneEl.addEventListener(
  59802. 'materialtextureloaded',
  59803. bind(this.onMaterialTextureLoaded, this)
  59804. );
  59805. },
  59806. clearTextureCache: function () {
  59807. this.textureCache = {};
  59808. },
  59809. /**
  59810. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  59811. *
  59812. * @param {string, or element} src - Texture URL or element.
  59813. * @param {string} data - Relevant texture data used for caching.
  59814. * @param {function} cb - Callback to pass texture to.
  59815. */
  59816. loadTexture: function (src, data, cb) {
  59817. var self = this;
  59818. // Canvas.
  59819. if (src.tagName === 'CANVAS') {
  59820. this.loadCanvas(src, data, cb);
  59821. return;
  59822. }
  59823. // Video element.
  59824. if (src.tagName === 'VIDEO') {
  59825. if (!src.src && !src.srcObject && !src.childElementCount) {
  59826. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  59827. }
  59828. this.loadVideo(src, data, cb);
  59829. return;
  59830. }
  59831. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  59832. function loadImageCb (src) { self.loadImage(src, data, cb); }
  59833. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  59834. },
  59835. /**
  59836. * High-level function for loading image textures (THREE.Texture).
  59837. *
  59838. * @param {Element|string} src - Texture source.
  59839. * @param {object} data - Texture data.
  59840. * @param {function} cb - Callback to pass texture to.
  59841. */
  59842. loadImage: function (src, data, handleImageTextureLoaded) {
  59843. var hash = this.hash(data);
  59844. var textureCache = this.textureCache;
  59845. // Texture already being loaded or already loaded. Wait on promise.
  59846. if (textureCache[hash]) {
  59847. textureCache[hash].then(handleImageTextureLoaded);
  59848. return;
  59849. }
  59850. // Texture not yet being loaded. Start loading it.
  59851. textureCache[hash] = loadImageTexture(src, data);
  59852. textureCache[hash].then(handleImageTextureLoaded);
  59853. },
  59854. /**
  59855. * High-level function for loading canvas textures (THREE.Texture).
  59856. *
  59857. * @param {Element|string} src - Texture source.
  59858. * @param {object} data - Texture data.
  59859. * @param {function} cb - Callback to pass texture to.
  59860. */
  59861. loadCanvas: function (src, data, cb) {
  59862. var texture;
  59863. texture = new THREE.CanvasTexture(src);
  59864. setTextureProperties(texture, data);
  59865. cb(texture);
  59866. },
  59867. /**
  59868. * Load video texture (THREE.VideoTexture).
  59869. * Which is just an image texture that RAFs + needsUpdate.
  59870. * Note that creating a video texture is synchronous unlike loading an image texture.
  59871. * Made asynchronous to be consistent with image textures.
  59872. *
  59873. * @param {Element|string} src - Texture source.
  59874. * @param {object} data - Texture data.
  59875. * @param {function} cb - Callback to pass texture to.
  59876. */
  59877. loadVideo: function (src, data, cb) {
  59878. var hash;
  59879. var texture;
  59880. var textureCache = this.textureCache;
  59881. var videoEl;
  59882. var videoTextureResult;
  59883. function handleVideoTextureLoaded (result) {
  59884. result.texture.needsUpdate = true;
  59885. cb(result.texture, result.videoEl);
  59886. }
  59887. // Video element provided.
  59888. if (typeof src !== 'string') {
  59889. // Check cache before creating texture.
  59890. videoEl = src;
  59891. hash = this.hashVideo(data, videoEl);
  59892. if (textureCache[hash]) {
  59893. textureCache[hash].then(handleVideoTextureLoaded);
  59894. return;
  59895. }
  59896. // If not in cache, fix up the attributes then start to create the texture.
  59897. fixVideoAttributes(videoEl);
  59898. }
  59899. // Only URL provided. Use video element to create texture.
  59900. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  59901. // Generated video element already cached. Use that.
  59902. hash = this.hashVideo(data, videoEl);
  59903. if (textureCache[hash]) {
  59904. textureCache[hash].then(handleVideoTextureLoaded);
  59905. return;
  59906. }
  59907. // Create new video texture.
  59908. texture = new THREE.VideoTexture(videoEl);
  59909. texture.minFilter = THREE.LinearFilter;
  59910. setTextureProperties(texture, data);
  59911. // If iOS and video is HLS, do some hacks.
  59912. if (this.sceneEl.isIOS &&
  59913. isHLS(videoEl.src || videoEl.getAttribute('src'),
  59914. videoEl.type || videoEl.getAttribute('type'))) {
  59915. // Actually BGRA. Tell shader to correct later.
  59916. texture.format = THREE.RGBAFormat;
  59917. texture.needsCorrectionBGRA = true;
  59918. // Apparently needed for HLS. Tell shader to correct later.
  59919. texture.flipY = false;
  59920. texture.needsCorrectionFlipY = true;
  59921. }
  59922. // Cache as promise to be consistent with image texture caching.
  59923. videoTextureResult = {texture: texture, videoEl: videoEl};
  59924. textureCache[hash] = Promise.resolve(videoTextureResult);
  59925. handleVideoTextureLoaded(videoTextureResult);
  59926. },
  59927. /**
  59928. * Create a hash of the material properties for texture cache key.
  59929. */
  59930. hash: function (data) {
  59931. if (data.src.tagName) {
  59932. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  59933. data = utils.extendDeep({}, data);
  59934. data.src = data.src.src;
  59935. }
  59936. return JSON.stringify(data);
  59937. },
  59938. hashVideo: function (data, videoEl) {
  59939. return calculateVideoCacheHash(data, videoEl);
  59940. },
  59941. /**
  59942. * Keep track of material in case an update trigger is needed (e.g., fog).
  59943. *
  59944. * @param {object} material
  59945. */
  59946. registerMaterial: function (material) {
  59947. this.materials[material.uuid] = material;
  59948. },
  59949. /**
  59950. * Stop tracking material, and dispose of any textures not being used by
  59951. * another material component.
  59952. *
  59953. * @param {object} material
  59954. */
  59955. unregisterMaterial: function (material) {
  59956. delete this.materials[material.uuid];
  59957. // If any textures on this material are no longer in use, dispose of them.
  59958. var textureCounts = this.textureCounts;
  59959. Object.keys(material)
  59960. .filter(function (propName) {
  59961. return material[propName] && material[propName].isTexture;
  59962. })
  59963. .forEach(function (mapName) {
  59964. textureCounts[material[mapName].uuid]--;
  59965. if (textureCounts[material[mapName].uuid] <= 0) {
  59966. material[mapName].dispose();
  59967. }
  59968. });
  59969. },
  59970. /**
  59971. * Trigger update to all registered materials.
  59972. */
  59973. updateMaterials: function (material) {
  59974. var materials = this.materials;
  59975. Object.keys(materials).forEach(function (uuid) {
  59976. materials[uuid].needsUpdate = true;
  59977. });
  59978. },
  59979. /**
  59980. * Track textures used by material components, so that they can be safely
  59981. * disposed when no longer in use. Textures must be registered here, and not
  59982. * through registerMaterial(), because textures may not be attached at the
  59983. * time the material is registered.
  59984. *
  59985. * @param {Event} e
  59986. */
  59987. onMaterialTextureLoaded: function (e) {
  59988. if (!this.textureCounts[e.detail.texture.uuid]) {
  59989. this.textureCounts[e.detail.texture.uuid] = 0;
  59990. }
  59991. this.textureCounts[e.detail.texture.uuid]++;
  59992. }
  59993. });
  59994. /**
  59995. * Calculates consistent hash from a video element using its attributes.
  59996. * If the video element has an ID, use that.
  59997. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  59998. *
  59999. * @param data {object} - Texture data such as repeat.
  60000. * @param videoEl {Element} - Video element.
  60001. * @returns {string}
  60002. */
  60003. function calculateVideoCacheHash (data, videoEl) {
  60004. var i;
  60005. var id = videoEl.getAttribute('id');
  60006. var hash;
  60007. var videoAttributes;
  60008. if (id) { return id; }
  60009. // Calculate hash using sorted video attributes.
  60010. hash = '';
  60011. videoAttributes = data || {};
  60012. for (i = 0; i < videoEl.attributes.length; i++) {
  60013. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  60014. }
  60015. Object.keys(videoAttributes).sort().forEach(function (name) {
  60016. hash += name + ':' + videoAttributes[name] + ';';
  60017. });
  60018. return hash;
  60019. }
  60020. /**
  60021. * Load image texture.
  60022. *
  60023. * @private
  60024. * @param {string|object} src - An <img> element or url to an image file.
  60025. * @param {object} data - Data to set texture properties like `repeat`.
  60026. * @returns {Promise} Resolves once texture is loaded.
  60027. */
  60028. function loadImageTexture (src, data) {
  60029. return new Promise(doLoadImageTexture);
  60030. function doLoadImageTexture (resolve, reject) {
  60031. var isEl = typeof src !== 'string';
  60032. function resolveTexture (texture) {
  60033. setTextureProperties(texture, data);
  60034. texture.needsUpdate = true;
  60035. resolve(texture);
  60036. }
  60037. // Create texture from an element.
  60038. if (isEl) {
  60039. resolveTexture(new THREE.Texture(src));
  60040. return;
  60041. }
  60042. // Request and load texture from src string. THREE will create underlying element.
  60043. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  60044. TextureLoader.load(
  60045. src,
  60046. resolveTexture,
  60047. function () { /* no-op */ },
  60048. function (xhr) {
  60049. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  60050. xhr.statusText);
  60051. }
  60052. );
  60053. }
  60054. }
  60055. /**
  60056. * Create video element to be used as a texture.
  60057. *
  60058. * @param {string} src - Url to a video file.
  60059. * @param {number} width - Width of the video.
  60060. * @param {number} height - Height of the video.
  60061. * @returns {Element} Video element.
  60062. */
  60063. function createVideoEl (src, width, height) {
  60064. var videoEl = document.createElement('video');
  60065. videoEl.width = width;
  60066. videoEl.height = height;
  60067. // Support inline videos for iOS webviews.
  60068. videoEl.setAttribute('playsinline', '');
  60069. videoEl.setAttribute('webkit-playsinline', '');
  60070. videoEl.autoplay = true;
  60071. videoEl.loop = true;
  60072. videoEl.crossOrigin = 'anonymous';
  60073. videoEl.addEventListener('error', function () {
  60074. warn('`$s` is not a valid video', src);
  60075. }, true);
  60076. videoEl.src = src;
  60077. return videoEl;
  60078. }
  60079. /**
  60080. * Fixes a video element's attributes to prevent developers from accidentally passing the
  60081. * wrong attribute values to commonly misused video attributes.
  60082. *
  60083. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  60084. * as booleans. Existence of those attributes will mean truthy.
  60085. *
  60086. * For example, translates <video loop="false"> to <video>.
  60087. *
  60088. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  60089. * @param {Element} videoEl - Video element.
  60090. * @returns {Element} Video element with the correct properties updated.
  60091. */
  60092. function fixVideoAttributes (videoEl) {
  60093. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  60094. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  60095. if (videoEl.getAttribute('loop') === 'false') {
  60096. videoEl.removeAttribute('loop');
  60097. }
  60098. if (videoEl.getAttribute('preload') === 'false') {
  60099. videoEl.preload = 'none';
  60100. }
  60101. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  60102. // To support inline videos in iOS webviews.
  60103. videoEl.setAttribute('playsinline', '');
  60104. videoEl.setAttribute('webkit-playsinline', '');
  60105. return videoEl;
  60106. }
  60107. },{"../core/system":146,"../lib/three":183,"../utils/":210,"../utils/material":214}],199:[function(require,module,exports){
  60108. var registerSystem = require('../core/system').registerSystem;
  60109. var utils = require('../utils/');
  60110. var THREE = require('../lib/three');
  60111. var debug = utils.debug;
  60112. var warn = debug('components:renderer:warn');
  60113. /**
  60114. * Determines state of various renderer properties.
  60115. */
  60116. module.exports.System = registerSystem('renderer', {
  60117. schema: {
  60118. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60119. highRefreshRate: {default: utils.device.isOculusBrowser()},
  60120. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60121. maxCanvasWidth: {default: 1920},
  60122. maxCanvasHeight: {default: 1920},
  60123. physicallyCorrectLights: {default: false},
  60124. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  60125. sortObjects: {default: false},
  60126. colorManagement: {default: false},
  60127. gammaOutput: {default: false},
  60128. alpha: {default: true},
  60129. foveationLevel: {default: 0}
  60130. },
  60131. init: function () {
  60132. var data = this.data;
  60133. var sceneEl = this.el;
  60134. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  60135. var renderer = sceneEl.renderer;
  60136. renderer.sortObjects = data.sortObjects;
  60137. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  60138. if (data.colorManagement || data.gammaOutput) {
  60139. renderer.outputEncoding = THREE.sRGBEncoding;
  60140. if (data.gammaOutput) {
  60141. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  60142. }
  60143. }
  60144. if (sceneEl.hasAttribute('antialias')) {
  60145. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  60146. }
  60147. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  60148. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  60149. }
  60150. },
  60151. applyColorCorrection: function (colorOrTexture) {
  60152. if (!this.data.colorManagement || !colorOrTexture) {
  60153. return;
  60154. } else if (colorOrTexture.isColor) {
  60155. colorOrTexture.convertSRGBToLinear();
  60156. } else if (colorOrTexture.isTexture) {
  60157. colorOrTexture.encoding = THREE.sRGBEncoding;
  60158. }
  60159. }
  60160. });
  60161. },{"../core/system":146,"../lib/three":183,"../utils/":210}],200:[function(require,module,exports){
  60162. var registerSystem = require('../core/system').registerSystem;
  60163. var THREE = require('../lib/three');
  60164. var SHADOW_MAP_TYPE_MAP = {
  60165. basic: THREE.BasicShadowMap,
  60166. pcf: THREE.PCFShadowMap,
  60167. pcfsoft: THREE.PCFSoftShadowMap
  60168. };
  60169. /**
  60170. * Shadow system.
  60171. *
  60172. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  60173. * options on the WebGLRenderer for configuring shadow appearance.
  60174. */
  60175. module.exports.System = registerSystem('shadow', {
  60176. schema: {
  60177. enabled: {default: true},
  60178. autoUpdate: {default: true},
  60179. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  60180. },
  60181. init: function () {
  60182. var sceneEl = this.sceneEl;
  60183. var data = this.data;
  60184. this.shadowMapEnabled = false;
  60185. if (!sceneEl.renderer) { return; } // For tests.
  60186. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  60187. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  60188. this.setShadowMapEnabled(this.shadowMapEnabled);
  60189. },
  60190. update: function (prevData) {
  60191. if (prevData.enabled !== this.data.enabled) {
  60192. this.setShadowMapEnabled(this.data.enabled);
  60193. }
  60194. },
  60195. /**
  60196. * Enables/disables the renderer shadow map.
  60197. * @param {boolean} enabled
  60198. */
  60199. setShadowMapEnabled: function (enabled) {
  60200. var renderer = this.sceneEl.renderer;
  60201. this.shadowMapEnabled = this.data.enabled && enabled;
  60202. if (renderer) {
  60203. renderer.shadowMap.enabled = this.shadowMapEnabled;
  60204. }
  60205. }
  60206. });
  60207. },{"../core/system":146,"../lib/three":183}],201:[function(require,module,exports){
  60208. var registerSystem = require('../core/system').registerSystem;
  60209. var utils = require('../utils');
  60210. var isWebXRAvailable = utils.device.isWebXRAvailable;
  60211. /**
  60212. * Tracked controls system.
  60213. * Maintain list with available tracked controllers.
  60214. */
  60215. module.exports.System = registerSystem('tracked-controls-webvr', {
  60216. init: function () {
  60217. var self = this;
  60218. this.controllers = [];
  60219. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  60220. this.updateControllerList();
  60221. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60222. // Don't use WebVR if WebXR is available?
  60223. if (isWebXRAvailable) { return; }
  60224. if (!navigator.getVRDisplays) { return; }
  60225. this.sceneEl.addEventListener('enter-vr', function () {
  60226. navigator.getVRDisplays().then(function (displays) {
  60227. if (displays.length) { self.vrDisplay = displays[0]; }
  60228. });
  60229. });
  60230. },
  60231. tick: function () {
  60232. if (this.isChrome) {
  60233. // Retrieve new controller handlers with updated state (pose, buttons...)
  60234. this.updateControllerList();
  60235. } else {
  60236. this.throttledUpdateControllerList();
  60237. }
  60238. },
  60239. /**
  60240. * Update controller list.
  60241. */
  60242. updateControllerList: function () {
  60243. var controllers = this.controllers;
  60244. var gamepad;
  60245. var gamepads;
  60246. var i;
  60247. var prevCount;
  60248. gamepads = navigator.getGamepads && navigator.getGamepads();
  60249. if (!gamepads) { return; }
  60250. prevCount = controllers.length;
  60251. controllers.length = 0;
  60252. for (i = 0; i < gamepads.length; ++i) {
  60253. gamepad = gamepads[i];
  60254. if (gamepad && gamepad.pose) {
  60255. controllers.push(gamepad);
  60256. }
  60257. }
  60258. if (controllers.length !== prevCount) {
  60259. this.el.emit('controllersupdated', undefined, false);
  60260. }
  60261. }
  60262. });
  60263. },{"../core/system":146,"../utils":210}],202:[function(require,module,exports){
  60264. var registerSystem = require('../core/system').registerSystem;
  60265. var utils = require('../utils');
  60266. /**
  60267. * Tracked controls system.
  60268. * Maintain list with available tracked controllers.
  60269. */
  60270. module.exports.System = registerSystem('tracked-controls-webxr', {
  60271. init: function () {
  60272. this.controllers = [];
  60273. this.oldControllers = [];
  60274. this.oldControllersLength = 0;
  60275. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60276. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  60277. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  60278. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  60279. },
  60280. tick: function () {
  60281. this.throttledUpdateControllerList();
  60282. },
  60283. updateReferenceSpace: function () {
  60284. var self = this;
  60285. var xrSession = this.el.xrSession;
  60286. if (!xrSession) {
  60287. this.referenceSpace = undefined;
  60288. this.controllers = [];
  60289. if (this.oldControllersLength > 0) {
  60290. this.oldControllersLength = 0;
  60291. this.el.emit('controllersupdated', undefined, false);
  60292. }
  60293. return;
  60294. }
  60295. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  60296. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  60297. self.referenceSpace = referenceSpace;
  60298. }).catch(function (err) {
  60299. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  60300. refspace,
  60301. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  60302. throw err;
  60303. });
  60304. },
  60305. updateControllerList: function () {
  60306. var xrSession = this.el.xrSession;
  60307. var oldControllers = this.oldControllers;
  60308. var i;
  60309. if (!xrSession) {
  60310. if (this.oldControllersLength === 0) { return; }
  60311. // Broadcast that we now have zero controllers connected if there is
  60312. // no session
  60313. this.oldControllersLength = 0;
  60314. this.controllers = [];
  60315. this.el.emit('controllersupdated', undefined, false);
  60316. return;
  60317. }
  60318. if (!xrSession.inputSources) { return; }
  60319. this.controllers = xrSession.inputSources;
  60320. if (this.oldControllersLength === this.controllers.length) {
  60321. var equal = true;
  60322. for (i = 0; i < this.controllers.length; ++i) {
  60323. if (this.controllers[i] === oldControllers[i] &&
  60324. this.controllers[i].gamepad === oldControllers[i].gamepad) { continue; }
  60325. equal = false;
  60326. break;
  60327. }
  60328. if (equal) { return; }
  60329. }
  60330. // Store reference to current controllers
  60331. oldControllers.length = 0;
  60332. for (i = 0; i < this.controllers.length; i++) {
  60333. oldControllers.push(this.controllers[i]);
  60334. }
  60335. this.oldControllersLength = this.controllers.length;
  60336. this.el.emit('controllersupdated', undefined, false);
  60337. }
  60338. });
  60339. },{"../core/system":146,"../utils":210}],203:[function(require,module,exports){
  60340. var registerSystem = require('../core/system').registerSystem;
  60341. var utils = require('../utils/');
  60342. var warn = utils.debug('systems:webxr:warn');
  60343. /**
  60344. * WebXR session initialization and XR module support.
  60345. */
  60346. module.exports.System = registerSystem('webxr', {
  60347. schema: {
  60348. referenceSpaceType: {type: 'string', default: 'local-floor'},
  60349. requiredFeatures: {type: 'array', default: ['local-floor']},
  60350. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  60351. overlayElement: {type: 'selector'}
  60352. },
  60353. update: function () {
  60354. var data = this.data;
  60355. this.sessionConfiguration = {
  60356. requiredFeatures: data.requiredFeatures,
  60357. optionalFeatures: data.optionalFeatures
  60358. };
  60359. this.sessionReferenceSpaceType = data.referenceSpaceType;
  60360. if (data.overlayElement) {
  60361. // Update WebXR to support light-estimation
  60362. data.overlayElement.classList.remove('a-dom-overlay');
  60363. if (!data.optionalFeatures.includes('dom-overlay')) {
  60364. data.optionalFeatures.push('dom-overlay');
  60365. this.el.setAttribute('webxr', data);
  60366. }
  60367. this.warnIfFeatureNotRequested('dom-overlay');
  60368. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  60369. data.overlayElement.classList.add('a-dom-overlay');
  60370. }
  60371. },
  60372. wasFeatureRequested: function (feature) {
  60373. // Features available by default for immersive sessions don't need to
  60374. // be requested explicitly.
  60375. if (feature === 'viewer' || feature === 'local') { return true; }
  60376. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  60377. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  60378. return true;
  60379. }
  60380. return false;
  60381. },
  60382. warnIfFeatureNotRequested: function (feature, optIntro) {
  60383. if (!this.wasFeatureRequested(feature)) {
  60384. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  60385. 'webxr system options in requiredFeatures/optionalFeatures.';
  60386. warn((optIntro ? optIntro + ' ' : '') + msg);
  60387. }
  60388. }
  60389. });
  60390. },{"../core/system":146,"../utils/":210}],204:[function(require,module,exports){
  60391. /**
  60392. * Faster version of Function.prototype.bind
  60393. * @param {Function} fn - Function to wrap.
  60394. * @param {Object} ctx - What to bind as context.
  60395. * @param {...*} arguments - Arguments to pass through.
  60396. */
  60397. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  60398. return (function (prependedArgs) {
  60399. return function bound () {
  60400. // Concat the bound function arguments with those passed to original bind
  60401. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  60402. return fn.apply(ctx, args);
  60403. };
  60404. })(Array.prototype.slice.call(arguments, 2));
  60405. };
  60406. },{}],205:[function(require,module,exports){
  60407. /* global THREE */
  60408. var debug = require('./debug');
  60409. var extend = require('object-assign');
  60410. var warn = debug('utils:coordinates:warn');
  60411. // Order of coordinates parsed by coordinates.parse.
  60412. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  60413. // Coordinate string regex. Handles negative, positive, and decimals.
  60414. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  60415. module.exports.regex = regex;
  60416. var OBJECT = 'object';
  60417. var whitespaceRegex = /\s+/g;
  60418. /**
  60419. * Parses coordinates from an "x y z" string.
  60420. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  60421. *
  60422. * @param {string} val - An "x y z" string.
  60423. * @param {string} defaults - fallback value.
  60424. * @returns {object} An object with keys [x, y, z].
  60425. */
  60426. function parse (value, defaultVec) {
  60427. var coordinate;
  60428. var defaultVal;
  60429. var key;
  60430. var i;
  60431. var vec;
  60432. var x;
  60433. var y;
  60434. var z;
  60435. var w;
  60436. if (value && value instanceof Object) {
  60437. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  60438. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  60439. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  60440. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  60441. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  60442. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  60443. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  60444. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  60445. return value;
  60446. }
  60447. if (value === null || value === undefined) {
  60448. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  60449. }
  60450. coordinate = value.trim().split(whitespaceRegex);
  60451. vec = {};
  60452. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  60453. key = COORDINATE_KEYS[i];
  60454. if (coordinate[i]) {
  60455. vec[key] = parseFloat(coordinate[i], 10);
  60456. } else {
  60457. defaultVal = defaultVec && defaultVec[key];
  60458. if (defaultVal === undefined) { continue; }
  60459. vec[key] = parseIfString(defaultVal);
  60460. }
  60461. }
  60462. return vec;
  60463. }
  60464. module.exports.parse = parse;
  60465. /**
  60466. * Stringify coordinates from an object with keys [x y z].
  60467. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  60468. *
  60469. * @param {object|string} data - An object with keys [x y z].
  60470. * @returns {string} An "x y z" string.
  60471. */
  60472. function stringify (data) {
  60473. var str;
  60474. if (typeof data !== OBJECT) { return data; }
  60475. str = data.x + ' ' + data.y;
  60476. if (data.z != null) { str += ' ' + data.z; }
  60477. if (data.w != null) { str += ' ' + data.w; }
  60478. return str;
  60479. }
  60480. module.exports.stringify = stringify;
  60481. /**
  60482. * @returns {bool}
  60483. */
  60484. function isCoordinates (value) {
  60485. return regex.test(value);
  60486. }
  60487. module.exports.isCoordinates = isCoordinates;
  60488. module.exports.isCoordinate = function (value) {
  60489. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  60490. return isCoordinates(value);
  60491. };
  60492. function parseIfString (val) {
  60493. if (val !== null && val !== undefined && val.constructor === String) {
  60494. return parseFloat(val, 10);
  60495. }
  60496. return val;
  60497. }
  60498. /**
  60499. * Convert {x, y, z} object to three.js Vector3.
  60500. */
  60501. module.exports.toVector3 = function (vec3) {
  60502. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  60503. };
  60504. },{"./debug":206,"object-assign":39}],206:[function(require,module,exports){
  60505. (function (process){
  60506. var debugLib = require('debug');
  60507. var extend = require('object-assign');
  60508. var settings = {
  60509. colors: {
  60510. debug: 'gray',
  60511. error: 'red',
  60512. info: 'gray',
  60513. warn: 'orange'
  60514. }
  60515. };
  60516. /**
  60517. * Monkeypatches `debug` so we can colorize error/warning messages.
  60518. *
  60519. * (See issue: https://github.com/visionmedia/debug/issues/137)
  60520. */
  60521. var debug = function (namespace) {
  60522. var d = debugLib(namespace);
  60523. d.color = getDebugNamespaceColor(namespace);
  60524. return d;
  60525. };
  60526. extend(debug, debugLib);
  60527. /**
  60528. * Returns the type of the namespace (e.g., `error`, `warn`).
  60529. *
  60530. * @param {String} namespace
  60531. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60532. * @returns {String} The type of the namespace (e.g., `warn`).
  60533. * @api private
  60534. */
  60535. function getDebugNamespaceType (namespace) {
  60536. var chunks = namespace.split(':');
  60537. return chunks[chunks.length - 1]; // Return the last one
  60538. }
  60539. /**
  60540. * Returns the color of the namespace (e.g., `orange`).
  60541. *
  60542. * @param {String} namespace
  60543. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60544. * @returns {String} The color of the namespace (e.g., `orange`).
  60545. * @api private
  60546. */
  60547. function getDebugNamespaceColor (namespace) {
  60548. var type = getDebugNamespaceType(namespace);
  60549. var color = settings.colors && settings.colors[type];
  60550. return color || null;
  60551. }
  60552. /**
  60553. * Returns `localStorage` if possible.
  60554. *
  60555. * This is necessary because Safari throws when a user disables
  60556. * cookies or `localStorage` and you attempt to access it.
  60557. *
  60558. * @returns {localStorage}
  60559. * @api private
  60560. */
  60561. function storage () {
  60562. try {
  60563. return window.localStorage;
  60564. } catch (e) {
  60565. }
  60566. }
  60567. /**
  60568. * To enable console logging, type this in the Console of your Dev Tools:
  60569. *
  60570. * localStorage.logs = 1
  60571. *
  60572. * To disable console logging:
  60573. *
  60574. * localStorage.logs = 0
  60575. *
  60576. */
  60577. var ls = storage();
  60578. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  60579. debug.enable('*');
  60580. } else {
  60581. debug.enable('*:error,*:info,*:warn');
  60582. }
  60583. if (process.browser) { window.logs = debug; }
  60584. module.exports = debug;
  60585. }).call(this,require('_process'))
  60586. },{"_process":49,"debug":8,"object-assign":39}],207:[function(require,module,exports){
  60587. (function (process){
  60588. var error = require('debug')('device:error');
  60589. var vrDisplay;
  60590. var supportsVRSession = false;
  60591. var supportsARSession = false;
  60592. /**
  60593. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  60594. * We fallback to WebVR API and will hotfix when implementation is complete.
  60595. */
  60596. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  60597. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  60598. window.addEventListener('vrdisplayactivate', function (evt) {
  60599. var canvasEl;
  60600. // WebXR takes priority if available.
  60601. if (isWebXRAvailable) { return; }
  60602. canvasEl = document.createElement('canvas');
  60603. vrDisplay = evt.display;
  60604. // We need to make sure the canvas has a WebGL context associated with it.
  60605. // Otherwise, the requestPresent could be denied.
  60606. canvasEl.getContext('webgl', {});
  60607. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  60608. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  60609. });
  60610. // Support both WebVR and WebXR APIs.
  60611. if (isWebXRAvailable) {
  60612. var updateEnterInterfaces = function () {
  60613. var sceneEl = document.querySelector('a-scene');
  60614. if (!sceneEl) {
  60615. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  60616. return;
  60617. }
  60618. if (sceneEl.hasLoaded) {
  60619. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  60620. } else {
  60621. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  60622. }
  60623. };
  60624. var errorHandler = function (err) {
  60625. error('WebXR session support error: ' + err.message);
  60626. };
  60627. if (navigator.xr.isSessionSupported) {
  60628. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  60629. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  60630. supportsVRSession = supported;
  60631. updateEnterInterfaces();
  60632. }).catch(errorHandler);
  60633. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  60634. supportsARSession = supported;
  60635. updateEnterInterfaces();
  60636. }).catch(function () {});
  60637. } else if (navigator.xr.supportsSession) {
  60638. // Fallback for implementations that haven't updated to the new spec yet,
  60639. // the old version used supportsSession which is rejected for missing
  60640. // support.
  60641. navigator.xr.supportsSession('immersive-vr').then(function () {
  60642. supportsVRSession = true;
  60643. updateEnterInterfaces();
  60644. }).catch(errorHandler);
  60645. navigator.xr.supportsSession('immersive-ar').then(function () {
  60646. supportsARSession = true;
  60647. updateEnterInterfaces();
  60648. }).catch(function () {});
  60649. } else {
  60650. error('WebXR has neither isSessionSupported or supportsSession?!');
  60651. }
  60652. } else {
  60653. if (navigator.getVRDisplays) {
  60654. navigator.getVRDisplays().then(function (displays) {
  60655. var sceneEl = document.querySelector('a-scene');
  60656. vrDisplay = displays.length && displays[0];
  60657. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  60658. });
  60659. }
  60660. }
  60661. function getVRDisplay () { return vrDisplay; }
  60662. module.exports.getVRDisplay = getVRDisplay;
  60663. /**
  60664. * Determine if a headset is connected by checking if a vrDisplay is available.
  60665. */
  60666. function checkHeadsetConnected () {
  60667. return supportsVRSession || supportsARSession || !!getVRDisplay();
  60668. }
  60669. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  60670. function checkARSupport () { return supportsARSession; }
  60671. module.exports.checkARSupport = checkARSupport;
  60672. /**
  60673. * Checks if browser is mobile and not stand-alone dedicated vr device.
  60674. * @return {Boolean} True if mobile browser detected.
  60675. */
  60676. var isMobile = (function () {
  60677. var _isMobile = false;
  60678. (function (a) {
  60679. // eslint-disable-next-line no-useless-escape
  60680. 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))) {
  60681. _isMobile = true;
  60682. }
  60683. if (isIOS() || isTablet() || isR7()) {
  60684. _isMobile = true;
  60685. }
  60686. if (isMobileVR()) {
  60687. _isMobile = false;
  60688. }
  60689. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  60690. return function () { return _isMobile; };
  60691. })();
  60692. module.exports.isMobile = isMobile;
  60693. /**
  60694. * Detect tablet devices.
  60695. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  60696. */
  60697. function isTablet (mockUserAgent) {
  60698. var userAgent = mockUserAgent || window.navigator.userAgent;
  60699. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  60700. }
  60701. module.exports.isTablet = isTablet;
  60702. function isIOS () {
  60703. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  60704. }
  60705. module.exports.isIOS = isIOS;
  60706. function isMobileDeviceRequestingDesktopSite () {
  60707. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  60708. }
  60709. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  60710. /**
  60711. * Detect Oculus Browser (standalone headset)
  60712. */
  60713. function isOculusBrowser () {
  60714. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  60715. }
  60716. module.exports.isOculusBrowser = isOculusBrowser;
  60717. /**
  60718. * Detect Firefox Reality (standalone headset)
  60719. */
  60720. function isFirefoxReality () {
  60721. return /(Mobile VR)/i.test(window.navigator.userAgent);
  60722. }
  60723. module.exports.isFirefoxReality = isFirefoxReality;
  60724. /**
  60725. * Detect browsers in Stand-Alone headsets
  60726. */
  60727. function isMobileVR () {
  60728. return isOculusBrowser() || isFirefoxReality();
  60729. }
  60730. module.exports.isMobileVR = isMobileVR;
  60731. function isR7 () {
  60732. return /R7 Build/.test(window.navigator.userAgent);
  60733. }
  60734. module.exports.isR7 = isR7;
  60735. /**
  60736. * Checks mobile device orientation.
  60737. * @return {Boolean} True if landscape orientation.
  60738. */
  60739. module.exports.isLandscape = function () {
  60740. var orientation = window.orientation;
  60741. if (isR7()) { orientation += 90; }
  60742. return orientation === 90 || orientation === -90;
  60743. };
  60744. /**
  60745. * Check if running in a browser or spoofed browser (bundler).
  60746. * We need to check a node api that isn't mocked on either side.
  60747. * `require` and `module.exports` are mocked in browser by bundlers.
  60748. * `window` is mocked in node.
  60749. * `process` is also mocked by browserify, but has custom properties.
  60750. */
  60751. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  60752. /**
  60753. * Check if running in node on the server.
  60754. */
  60755. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  60756. }).call(this,require('_process'))
  60757. },{"_process":49,"debug":8}],208:[function(require,module,exports){
  60758. /**
  60759. * Split a delimited component property string (e.g., `material.color`) to an object
  60760. * containing `component` name and `property` name. If there is no delimiter, just return the
  60761. * string back.
  60762. *
  60763. * Cache arrays from splitting strings via delimiter to save on memory.
  60764. *
  60765. * @param {string} str - e.g., `material.opacity`.
  60766. * @param {string} delimiter - e.g., `.`.
  60767. * @returns {array} e.g., `['material', 'opacity']`.
  60768. */
  60769. var propertyPathCache = {};
  60770. function getComponentPropertyPath (str, delimiter) {
  60771. delimiter = delimiter || '.';
  60772. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  60773. if (str.indexOf(delimiter) !== -1) {
  60774. propertyPathCache[delimiter][str] = str.split(delimiter);
  60775. } else {
  60776. propertyPathCache[delimiter][str] = str;
  60777. }
  60778. return propertyPathCache[delimiter][str];
  60779. }
  60780. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  60781. module.exports.propertyPathCache = propertyPathCache;
  60782. /**
  60783. * Get component property using encoded component name + component property name with a
  60784. * delimiter.
  60785. */
  60786. module.exports.getComponentProperty = function (el, name, delimiter) {
  60787. var splitName;
  60788. delimiter = delimiter || '.';
  60789. if (name.indexOf(delimiter) !== -1) {
  60790. splitName = getComponentPropertyPath(name, delimiter);
  60791. if (splitName.constructor === String) {
  60792. return el.getAttribute(splitName);
  60793. }
  60794. return el.getAttribute(splitName[0])[splitName[1]];
  60795. }
  60796. return el.getAttribute(name);
  60797. };
  60798. /**
  60799. * Set component property using encoded component name + component property name with a
  60800. * delimiter.
  60801. */
  60802. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  60803. var splitName;
  60804. delimiter = delimiter || '.';
  60805. if (name.indexOf(delimiter) !== -1) {
  60806. splitName = getComponentPropertyPath(name, delimiter);
  60807. if (splitName.constructor === String) {
  60808. el.setAttribute(splitName, value);
  60809. } else {
  60810. el.setAttribute(splitName[0], splitName[1], value);
  60811. }
  60812. return;
  60813. }
  60814. el.setAttribute(name, value);
  60815. };
  60816. },{}],209:[function(require,module,exports){
  60817. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  60818. var width = canvasEl.style.width;
  60819. var height = canvasEl.style.height;
  60820. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  60821. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  60822. // By changing the size 1 pixel and restoring the previous value
  60823. // we trigger a size recalculation cycle.
  60824. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  60825. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  60826. setTimeout(function () {
  60827. canvasEl.style.width = width;
  60828. canvasEl.style.height = height;
  60829. }, 200);
  60830. };
  60831. },{}],210:[function(require,module,exports){
  60832. /* global location */
  60833. /* Centralized place to reference utilities since utils is exposed to the user. */
  60834. var debug = require('./debug');
  60835. var deepAssign = require('deep-assign');
  60836. var device = require('./device');
  60837. var objectAssign = require('object-assign');
  60838. var objectPool = require('./object-pool');
  60839. var warn = debug('utils:warn');
  60840. module.exports.bind = require('./bind');
  60841. module.exports.coordinates = require('./coordinates');
  60842. module.exports.debug = debug;
  60843. module.exports.device = device;
  60844. module.exports.entity = require('./entity');
  60845. module.exports.forceCanvasResizeSafariMobile = require('./forceCanvasResizeSafariMobile');
  60846. module.exports.isIE11 = require('./is-ie11');
  60847. module.exports.material = require('./material');
  60848. module.exports.objectPool = objectPool;
  60849. module.exports.split = require('./split').split;
  60850. module.exports.styleParser = require('./styleParser');
  60851. module.exports.trackedControls = require('./tracked-controls');
  60852. module.exports.checkHeadsetConnected = function () {
  60853. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  60854. return device.checkHeadsetConnected(arguments);
  60855. };
  60856. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  60857. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  60858. };
  60859. module.exports.isIOS = function () {
  60860. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  60861. return device.isIOS(arguments);
  60862. };
  60863. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  60864. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  60865. };
  60866. module.exports.isMobile = function () {
  60867. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  60868. return device.isMobile(arguments);
  60869. };
  60870. /**
  60871. * Returns throttle function that gets called at most once every interval.
  60872. *
  60873. * @param {function} functionToThrottle
  60874. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  60875. * @param {object} optionalContext - If given, bind function to throttle to this context.
  60876. * @returns {function} Throttled function.
  60877. */
  60878. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  60879. var lastTime;
  60880. if (optionalContext) {
  60881. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  60882. }
  60883. return function () {
  60884. var time = Date.now();
  60885. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  60886. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  60887. lastTime = time;
  60888. functionToThrottle.apply(null, arguments);
  60889. }
  60890. };
  60891. };
  60892. /**
  60893. * Returns throttle function that gets called at most once every interval.
  60894. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  60895. *
  60896. * @param {function} functionToThrottle
  60897. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  60898. * @param {object} optionalContext - If given, bind function to throttle to this context.
  60899. * @returns {function} Throttled function.
  60900. */
  60901. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  60902. var lastTime;
  60903. if (optionalContext) {
  60904. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  60905. }
  60906. return function (time, delta) {
  60907. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  60908. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  60909. lastTime = time;
  60910. functionToThrottle(time, sinceLastTime);
  60911. }
  60912. };
  60913. };
  60914. /**
  60915. * Returns debounce function that gets called only once after a set of repeated calls.
  60916. *
  60917. * @param {function} functionToDebounce
  60918. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  60919. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  60920. * @returns {function} Debounced function.
  60921. */
  60922. module.exports.debounce = function (func, wait, immediate) {
  60923. var timeout;
  60924. return function () {
  60925. var context = this;
  60926. var args = arguments;
  60927. var later = function () {
  60928. timeout = null;
  60929. if (!immediate) func.apply(context, args);
  60930. };
  60931. var callNow = immediate && !timeout;
  60932. clearTimeout(timeout);
  60933. timeout = setTimeout(later, wait);
  60934. if (callNow) func.apply(context, args);
  60935. };
  60936. };
  60937. /**
  60938. * Mix the properties of source object(s) into a destination object.
  60939. *
  60940. * @param {object} dest - The object to which properties will be copied.
  60941. * @param {...object} source - The object(s) from which properties will be copied.
  60942. */
  60943. module.exports.extend = objectAssign;
  60944. module.exports.extendDeep = deepAssign;
  60945. module.exports.clone = function (obj) {
  60946. return JSON.parse(JSON.stringify(obj));
  60947. };
  60948. /**
  60949. * Checks if two values are equal.
  60950. * Includes objects and arrays and nested objects and arrays.
  60951. * Try to keep this function performant as it will be called often to see if a component
  60952. * should be updated.
  60953. *
  60954. * @param {object} a - First object.
  60955. * @param {object} b - Second object.
  60956. * @returns {boolean} Whether two objects are deeply equal.
  60957. */
  60958. var deepEqual = (function () {
  60959. var arrayPool = objectPool.createPool(function () { return []; });
  60960. return function (a, b) {
  60961. var key;
  60962. var keysA;
  60963. var keysB;
  60964. var i;
  60965. var valA;
  60966. var valB;
  60967. // If not objects or arrays, compare as values.
  60968. if (a === undefined || b === undefined || a === null || b === null ||
  60969. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  60970. (a.constructor === Array && b.constructor === Array))) {
  60971. return a === b;
  60972. }
  60973. // Different number of keys, not equal.
  60974. keysA = arrayPool.use();
  60975. keysB = arrayPool.use();
  60976. keysA.length = 0;
  60977. keysB.length = 0;
  60978. for (key in a) { keysA.push(key); }
  60979. for (key in b) { keysB.push(key); }
  60980. if (keysA.length !== keysB.length) {
  60981. arrayPool.recycle(keysA);
  60982. arrayPool.recycle(keysB);
  60983. return false;
  60984. }
  60985. // Return `false` at the first sign of inequality.
  60986. for (i = 0; i < keysA.length; ++i) {
  60987. valA = a[keysA[i]];
  60988. valB = b[keysA[i]];
  60989. // Check nested array and object.
  60990. if ((typeof valA === 'object' || typeof valB === 'object') ||
  60991. (Array.isArray(valA) && Array.isArray(valB))) {
  60992. if (valA === valB) { continue; }
  60993. if (!deepEqual(valA, valB)) {
  60994. arrayPool.recycle(keysA);
  60995. arrayPool.recycle(keysB);
  60996. return false;
  60997. }
  60998. } else if (valA !== valB) {
  60999. arrayPool.recycle(keysA);
  61000. arrayPool.recycle(keysB);
  61001. return false;
  61002. }
  61003. }
  61004. arrayPool.recycle(keysA);
  61005. arrayPool.recycle(keysB);
  61006. return true;
  61007. };
  61008. })();
  61009. module.exports.deepEqual = deepEqual;
  61010. /**
  61011. * Computes the difference between two objects.
  61012. *
  61013. * @param {object} a - First object to compare (e.g., oldData).
  61014. * @param {object} b - Second object to compare (e.g., newData).
  61015. * @returns {object}
  61016. * Difference object where set of keys note which values were not equal, and values are
  61017. * `b`'s values.
  61018. */
  61019. module.exports.diff = (function () {
  61020. var keys = [];
  61021. return function (a, b, targetObject) {
  61022. var aVal;
  61023. var bVal;
  61024. var bKey;
  61025. var diff;
  61026. var key;
  61027. var i;
  61028. var isComparingObjects;
  61029. diff = targetObject || {};
  61030. // Collect A keys.
  61031. keys.length = 0;
  61032. for (key in a) { keys.push(key); }
  61033. if (!b) { return diff; }
  61034. // Collect B keys.
  61035. for (bKey in b) {
  61036. if (keys.indexOf(bKey) === -1) {
  61037. keys.push(bKey);
  61038. }
  61039. }
  61040. for (i = 0; i < keys.length; i++) {
  61041. key = keys[i];
  61042. aVal = a[key];
  61043. bVal = b[key];
  61044. isComparingObjects = aVal && bVal &&
  61045. aVal.constructor === Object && bVal.constructor === Object;
  61046. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  61047. (!isComparingObjects && aVal !== bVal)) {
  61048. diff[key] = bVal;
  61049. }
  61050. }
  61051. return diff;
  61052. };
  61053. })();
  61054. /**
  61055. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  61056. * @param {Event} event Event object.
  61057. * @returns {Boolean} Whether the key event should be captured.
  61058. */
  61059. module.exports.shouldCaptureKeyEvent = function (event) {
  61060. if (event.metaKey) { return false; }
  61061. return document.activeElement === document.body;
  61062. };
  61063. /**
  61064. * Splits a string into an array based on a delimiter.
  61065. *
  61066. * @param {string=} [str=''] Source string
  61067. * @param {string=} [delimiter=' '] Delimiter to use
  61068. * @returns {array} Array of delimited strings
  61069. */
  61070. module.exports.splitString = function (str, delimiter) {
  61071. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  61072. // First collapse the whitespace (or whatever the delimiter is).
  61073. var regex = new RegExp(delimiter, 'g');
  61074. str = (str || '').replace(regex, delimiter);
  61075. // Then split.
  61076. return str.split(delimiter);
  61077. };
  61078. /**
  61079. * Extracts data from the element given an object that contains expected keys.
  61080. *
  61081. * @param {Element} Source element.
  61082. * @param {Object} [defaults={}] Object of default key-value pairs.
  61083. * @returns {Object}
  61084. */
  61085. module.exports.getElData = function (el, defaults) {
  61086. defaults = defaults || {};
  61087. var data = {};
  61088. Object.keys(defaults).forEach(copyAttribute);
  61089. function copyAttribute (key) {
  61090. if (el.hasAttribute(key)) {
  61091. data[key] = el.getAttribute(key);
  61092. }
  61093. }
  61094. return data;
  61095. };
  61096. /**
  61097. * Retrieves querystring value.
  61098. * @param {String} name Name of querystring key.
  61099. * @return {String} Value
  61100. */
  61101. module.exports.getUrlParameter = function (name) {
  61102. // eslint-disable-next-line no-useless-escape
  61103. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  61104. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  61105. var results = regex.exec(location.search);
  61106. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  61107. };
  61108. /**
  61109. * Detects whether context is within iframe.
  61110. */
  61111. module.exports.isIframed = function () {
  61112. return window.top !== window.self;
  61113. };
  61114. /**
  61115. * Finds all elements under the element that have the isScene
  61116. * property set to true
  61117. */
  61118. module.exports.findAllScenes = function (el) {
  61119. var matchingElements = [];
  61120. var allElements = el.getElementsByTagName('*');
  61121. for (var i = 0, n = allElements.length; i < n; i++) {
  61122. if (allElements[i].isScene) {
  61123. // Element exists with isScene set.
  61124. matchingElements.push(allElements[i]);
  61125. }
  61126. }
  61127. return matchingElements;
  61128. };
  61129. // Must be at bottom to avoid circular dependency.
  61130. module.exports.srcLoader = require('./src-loader');
  61131. },{"./bind":204,"./coordinates":205,"./debug":206,"./device":207,"./entity":208,"./forceCanvasResizeSafariMobile":209,"./is-ie11":212,"./material":214,"./object-pool":215,"./split":216,"./src-loader":217,"./styleParser":218,"./tracked-controls":219,"deep-assign":10,"object-assign":39}],211:[function(require,module,exports){
  61132. // Safari regression introduced in iOS 12 and remains in iOS 13.
  61133. // https://stackoverflow.com/questions/62717621/white-space-at-page-bottom-after-device-rotation-in-ios-safari
  61134. window.addEventListener('orientationchange', function () {
  61135. document.documentElement.style.height = `initial`;
  61136. setTimeout(function () {
  61137. document.documentElement.style.height = `100%`;
  61138. setTimeout(function () {
  61139. // this line prevents the content
  61140. // from hiding behind the address bar
  61141. window.scrollTo(0, 1);
  61142. }, 500);
  61143. }, 500);
  61144. });
  61145. },{}],212:[function(require,module,exports){
  61146. // https://stackoverflow.com/a/17907562
  61147. function getInternetExplorerVersion () {
  61148. var version = -1;
  61149. var userAgent = navigator.userAgent;
  61150. var re;
  61151. if (navigator.appName === 'Microsoft Internet Explorer') {
  61152. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  61153. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61154. } else if (navigator.appName === 'Netscape') {
  61155. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  61156. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61157. }
  61158. return version;
  61159. }
  61160. module.exports = getInternetExplorerVersion() === 11;
  61161. },{}],213:[function(require,module,exports){
  61162. /**
  61163. * Check if device is iOS and older than version 10.
  61164. */
  61165. module.exports = function isIOSOlderThan10 (userAgent) {
  61166. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  61167. };
  61168. },{}],214:[function(require,module,exports){
  61169. var THREE = require('../lib/three');
  61170. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  61171. var COLOR_MAPS = new Set([
  61172. 'emissiveMap',
  61173. 'envMap',
  61174. 'map',
  61175. 'specularMap'
  61176. ]);
  61177. /**
  61178. * Set texture properties such as repeat and offset.
  61179. *
  61180. * @param {object} data - With keys like `repeat`.
  61181. */
  61182. function setTextureProperties (texture, data) {
  61183. var offset = data.offset || {x: 0, y: 0};
  61184. var repeat = data.repeat || {x: 1, y: 1};
  61185. var npot = data.npot || false;
  61186. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  61187. // and filters must not use mipmaps (i.e. Nearest or Linear).
  61188. if (npot) {
  61189. texture.wrapS = THREE.ClampToEdgeWrapping;
  61190. texture.wrapT = THREE.ClampToEdgeWrapping;
  61191. texture.magFilter = THREE.LinearFilter;
  61192. texture.minFilter = THREE.LinearFilter;
  61193. }
  61194. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  61195. if (repeat.x !== 1 || repeat.y !== 1) {
  61196. texture.wrapS = THREE.RepeatWrapping;
  61197. texture.wrapT = THREE.RepeatWrapping;
  61198. texture.repeat.set(repeat.x, repeat.y);
  61199. }
  61200. // Don't bother setting offset if it is 0/0.
  61201. if (offset.x !== 0 || offset.y !== 0) {
  61202. texture.offset.set(offset.x, offset.y);
  61203. }
  61204. }
  61205. module.exports.setTextureProperties = setTextureProperties;
  61206. /**
  61207. * Update `material` texture property (usually but not always `map`)
  61208. * from `data` property (usually but not always `src`)
  61209. *
  61210. * @param {object} shader - A-Frame shader instance.
  61211. * @param {object} data
  61212. */
  61213. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  61214. var el = shader.el;
  61215. var material = shader.material;
  61216. var rendererSystem = el.sceneEl.systems.renderer;
  61217. var src = data[dataName];
  61218. // Because a single material / shader may have multiple textures,
  61219. // we need to remember the source value for this data property
  61220. // to avoid redundant operations which can be expensive otherwise
  61221. // (e.g. video texture loads).
  61222. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  61223. if (!src) {
  61224. // Forget the prior material src.
  61225. delete shader.materialSrcs[materialName];
  61226. // Remove the texture.
  61227. setMap(null);
  61228. return;
  61229. }
  61230. // Don't process if material src hasn't changed.
  61231. if (src === shader.materialSrcs[materialName]) { return; }
  61232. // Remember the new src for this texture (there may be multiple).
  61233. shader.materialSrcs[materialName] = src;
  61234. // If the new material src is already a texture, just use it.
  61235. if (src instanceof THREE.Texture) { setMap(src); } else {
  61236. // Load texture for the new material src.
  61237. // (And check if we should still use it once available in callback.)
  61238. el.sceneEl.systems.material.loadTexture(src,
  61239. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  61240. checkSetMap);
  61241. }
  61242. function checkSetMap (texture) {
  61243. // If the source has been changed, don't use loaded texture.
  61244. if (shader.materialSrcs[materialName] !== src) { return; }
  61245. setMap(texture);
  61246. }
  61247. function setMap (texture) {
  61248. material[materialName] = texture;
  61249. if (texture && COLOR_MAPS.has(materialName)) {
  61250. rendererSystem.applyColorCorrection(texture);
  61251. }
  61252. material.needsUpdate = true;
  61253. handleTextureEvents(el, texture);
  61254. }
  61255. };
  61256. /**
  61257. * Update `material.map` given `data.src`. For standard and flat shaders.
  61258. *
  61259. * @param {object} shader - A-Frame shader instance.
  61260. * @param {object} data
  61261. */
  61262. module.exports.updateMap = function (shader, data) {
  61263. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  61264. };
  61265. /**
  61266. * Updates the material's maps which give the illusion of extra geometry.
  61267. *
  61268. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  61269. * @param {object} shader - A-Frame shader instance
  61270. * @param {object} data
  61271. */
  61272. module.exports.updateDistortionMap = function (longType, shader, data) {
  61273. var shortType = longType;
  61274. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  61275. var el = shader.el;
  61276. var material = shader.material;
  61277. var rendererSystem = el.sceneEl.systems.renderer;
  61278. var src = data[longType + 'Map'];
  61279. var info = {};
  61280. info.src = src;
  61281. // Pass through the repeat and offset to be handled by the material loader.
  61282. info.offset = data[longType + 'TextureOffset'];
  61283. info.repeat = data[longType + 'TextureRepeat'];
  61284. info.wrap = data[longType + 'TextureWrap'];
  61285. if (src) {
  61286. if (src === shader[longType + 'TextureSrc']) { return; }
  61287. // Texture added or changed.
  61288. shader[longType + 'TextureSrc'] = src;
  61289. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  61290. return;
  61291. }
  61292. // Texture removed.
  61293. if (!material.map) { return; }
  61294. setMap(null);
  61295. function setMap (texture) {
  61296. var slot = shortType + 'Map';
  61297. material[slot] = texture;
  61298. if (texture && COLOR_MAPS.has(slot)) {
  61299. rendererSystem.applyColorCorrection(texture);
  61300. }
  61301. if (texture) {
  61302. setTextureProperties(texture, data);
  61303. }
  61304. material.needsUpdate = true;
  61305. handleTextureEvents(el, texture);
  61306. }
  61307. };
  61308. /**
  61309. * Emit event on entities on texture-related events.
  61310. *
  61311. * @param {Element} el - Entity.
  61312. * @param {object} texture - three.js Texture.
  61313. */
  61314. function handleTextureEvents (el, texture) {
  61315. if (!texture) { return; }
  61316. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  61317. // Video events.
  61318. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  61319. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  61320. // Check to see if we need to use iOS 10 HLS shader.
  61321. // Only override the shader if it is stock shader that we know doesn't correct.
  61322. if (!el.components || !el.components.material) { return; }
  61323. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  61324. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  61325. el.setAttribute('material', 'shader', 'ios10hls');
  61326. }
  61327. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  61328. });
  61329. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  61330. // Works for non-looping videos only.
  61331. el.emit('materialvideoended', {src: texture.image, texture: texture});
  61332. });
  61333. }
  61334. module.exports.handleTextureEvents = handleTextureEvents;
  61335. /**
  61336. * Given video element src and type, guess whether stream is HLS.
  61337. *
  61338. * @param {string} src - src from video element (generally URL to content).
  61339. * @param {string} type - type from video element (generally MIME type if present).
  61340. */
  61341. module.exports.isHLS = function (src, type) {
  61342. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  61343. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  61344. return false;
  61345. };
  61346. },{"../lib/three":183}],215:[function(require,module,exports){
  61347. /*
  61348. Adapted deePool by Kyle Simpson.
  61349. MIT License: http://getify.mit-license.org
  61350. */
  61351. var EMPTY_SLOT = Object.freeze(Object.create(null));
  61352. // Default object factory.
  61353. function defaultObjectFactory () { return {}; }
  61354. /**
  61355. * Create a new pool.
  61356. */
  61357. module.exports.createPool = function createPool (objectFactory) {
  61358. var objPool = [];
  61359. var nextFreeSlot = null; // Pool location to look for a free object to use.
  61360. objectFactory = objectFactory || defaultObjectFactory;
  61361. function use () {
  61362. var objToUse;
  61363. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  61364. grow(objPool.length || 5);
  61365. }
  61366. objToUse = objPool[nextFreeSlot];
  61367. objPool[nextFreeSlot++] = EMPTY_SLOT;
  61368. clearObject(objToUse);
  61369. return objToUse;
  61370. }
  61371. function recycle (obj) {
  61372. if (!(obj instanceof Object)) { return; }
  61373. if (nextFreeSlot === null || nextFreeSlot === -1) {
  61374. objPool[objPool.length] = obj;
  61375. return;
  61376. }
  61377. objPool[--nextFreeSlot] = obj;
  61378. }
  61379. function grow (count) {
  61380. var currentLength;
  61381. var i;
  61382. count = count === undefined ? objPool.length : count;
  61383. if (count > 0 && nextFreeSlot == null) {
  61384. nextFreeSlot = 0;
  61385. }
  61386. if (count > 0) {
  61387. currentLength = objPool.length;
  61388. objPool.length += Number(count);
  61389. for (i = currentLength; i < objPool.length; i++) {
  61390. // Add new obj to pool.
  61391. objPool[i] = objectFactory();
  61392. }
  61393. }
  61394. return objPool.length;
  61395. }
  61396. function size () {
  61397. return objPool.length;
  61398. }
  61399. return {
  61400. grow: grow,
  61401. pool: objPool,
  61402. recycle: recycle,
  61403. size: size,
  61404. use: use
  61405. };
  61406. };
  61407. function clearObject (obj) {
  61408. var key;
  61409. if (!obj || obj.constructor !== Object) { return; }
  61410. for (key in obj) { obj[key] = undefined; }
  61411. }
  61412. module.exports.clearObject = clearObject;
  61413. function removeUnusedKeys (obj, schema) {
  61414. var key;
  61415. if (!obj || obj.constructor !== Object) { return; }
  61416. for (key in obj) {
  61417. if (!(key in schema)) {
  61418. delete obj[key];
  61419. }
  61420. }
  61421. }
  61422. module.exports.removeUnusedKeys = removeUnusedKeys;
  61423. },{}],216:[function(require,module,exports){
  61424. /**
  61425. * String split with cached result.
  61426. */
  61427. module.exports.split = (function () {
  61428. var splitCache = {};
  61429. return function (str, delimiter) {
  61430. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  61431. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  61432. splitCache[delimiter][str] = str.split(delimiter);
  61433. return splitCache[delimiter][str];
  61434. };
  61435. })();
  61436. },{}],217:[function(require,module,exports){
  61437. /* global Image, XMLHttpRequest */
  61438. var debug = require('./debug');
  61439. var warn = debug('utils:src-loader:warn');
  61440. /**
  61441. * Validate a texture, either as a selector or as a URL.
  61442. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  61443. * callback.
  61444. *
  61445. * `src` will be passed into the callback
  61446. *
  61447. * @params {string|Element} src - URL or media element.
  61448. * @params {function} isImageCb - callback if texture is an image.
  61449. * @params {function} isVideoCb - callback if texture is a video.
  61450. */
  61451. function validateSrc (src, isImageCb, isVideoCb) {
  61452. checkIsImage(src, function isAnImageUrl (isImage) {
  61453. if (isImage) {
  61454. isImageCb(src);
  61455. return;
  61456. }
  61457. isVideoCb(src);
  61458. });
  61459. }
  61460. /**
  61461. * Validates six images as a cubemap, either as selector or comma-separated
  61462. * URLs.
  61463. *
  61464. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61465. must be wrapped by `url()`.
  61466. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61467. must be wrapped by `url()`.
  61468. */
  61469. function validateCubemapSrc (src, cb) {
  61470. var aCubemap;
  61471. var cubemapSrcRegex = '';
  61472. var i;
  61473. var urls;
  61474. var validatedUrls = [];
  61475. for (i = 0; i < 5; i++) {
  61476. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  61477. }
  61478. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  61479. urls = src.match(new RegExp(cubemapSrcRegex));
  61480. // `src` is a comma-separated list of URLs.
  61481. // In this case, re-use validateSrc for each side of the cube.
  61482. function isImageCb (url) {
  61483. validatedUrls.push(url);
  61484. if (validatedUrls.length === 6) {
  61485. cb(validatedUrls);
  61486. }
  61487. }
  61488. if (urls) {
  61489. for (i = 1; i < 7; i++) {
  61490. validateSrc(parseUrl(urls[i]), isImageCb);
  61491. }
  61492. return;
  61493. }
  61494. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  61495. aCubemap = validateAndGetQuerySelector(src);
  61496. if (!aCubemap) { return; }
  61497. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  61498. return cb(aCubemap.srcs);
  61499. }
  61500. // Else if aCubeMap is not a <a-cubemap>.
  61501. warn('Selector "%s" does not point to <a-cubemap>', src);
  61502. }
  61503. /**
  61504. * Parses src from `url(src)`.
  61505. * @param {string} src - String to parse.
  61506. * @return {string} The parsed src, if parseable.
  61507. */
  61508. function parseUrl (src) {
  61509. var parsedSrc = src.match(/\url\((.+)\)/);
  61510. if (!parsedSrc) { return; }
  61511. return parsedSrc[1];
  61512. }
  61513. /**
  61514. * Call back whether `src` is an image.
  61515. *
  61516. * @param {string|Element} src - URL or element that will be tested.
  61517. * @param {function} onResult - Callback with whether `src` is an image.
  61518. */
  61519. function checkIsImage (src, onResult) {
  61520. var request;
  61521. if (src.tagName) {
  61522. onResult(src.tagName === 'IMG');
  61523. return;
  61524. }
  61525. request = new XMLHttpRequest();
  61526. // Try to send HEAD request to check if image first.
  61527. request.open('HEAD', src);
  61528. request.addEventListener('load', function (event) {
  61529. var contentType;
  61530. if (request.status >= 200 && request.status < 300) {
  61531. contentType = request.getResponseHeader('Content-Type');
  61532. if (contentType == null) {
  61533. checkIsImageFallback(src, onResult);
  61534. } else {
  61535. if (contentType.startsWith('image')) {
  61536. onResult(true);
  61537. } else {
  61538. onResult(false);
  61539. }
  61540. }
  61541. } else {
  61542. checkIsImageFallback(src, onResult);
  61543. }
  61544. request.abort();
  61545. });
  61546. request.send();
  61547. }
  61548. function checkIsImageFallback (src, onResult) {
  61549. var tester = new Image();
  61550. tester.addEventListener('load', onLoad);
  61551. function onLoad () { onResult(true); }
  61552. tester.addEventListener('error', onError);
  61553. function onError () { onResult(false); }
  61554. tester.src = src;
  61555. }
  61556. /**
  61557. * Query and validate a query selector,
  61558. *
  61559. * @param {string} selector - DOM selector.
  61560. * @return {object|null|undefined} Selected DOM element if exists.
  61561. null if query yields no results.
  61562. undefined if `selector` is not a valid selector.
  61563. */
  61564. function validateAndGetQuerySelector (selector) {
  61565. try {
  61566. var el = document.querySelector(selector);
  61567. if (!el) {
  61568. warn('No element was found matching the selector: "%s"', selector);
  61569. }
  61570. return el;
  61571. } catch (e) { // Capture exception if it's not a valid selector.
  61572. warn('"%s" is not a valid selector', selector);
  61573. return undefined;
  61574. }
  61575. }
  61576. module.exports = {
  61577. parseUrl: parseUrl,
  61578. validateSrc: validateSrc,
  61579. validateCubemapSrc: validateCubemapSrc
  61580. };
  61581. },{"./debug":206}],218:[function(require,module,exports){
  61582. /**
  61583. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  61584. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  61585. * by Josh Johnston (MIT License).
  61586. */
  61587. var DASH_REGEX = /-([a-z])/g;
  61588. /**
  61589. * Deserialize style-like string into an object of properties.
  61590. *
  61591. * @param {string} value - HTML attribute value.
  61592. * @param {object} obj - Reused object for object pooling.
  61593. * @returns {object} Property data.
  61594. */
  61595. module.exports.parse = function (value, obj) {
  61596. var parsedData;
  61597. if (typeof value !== 'string') { return value; }
  61598. parsedData = styleParse(value, obj);
  61599. // The style parser returns an object { "" : "test"} when fed a string
  61600. if (parsedData['']) { return value; }
  61601. return transformKeysToCamelCase(parsedData);
  61602. };
  61603. /**
  61604. * Serialize an object of properties into a style-like string.
  61605. *
  61606. * @param {object} data - Property data.
  61607. * @returns {string}
  61608. */
  61609. module.exports.stringify = function (data) {
  61610. if (typeof data === 'string') { return data; }
  61611. return styleStringify(data);
  61612. };
  61613. /**
  61614. * Converts string from hyphen to camelCase.
  61615. *
  61616. * @param {string} str - String to camelCase.
  61617. * @return {string} CamelCased string.
  61618. */
  61619. function toCamelCase (str) {
  61620. return str.replace(DASH_REGEX, upperCase);
  61621. }
  61622. module.exports.toCamelCase = toCamelCase;
  61623. /**
  61624. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  61625. * `maxValue`).
  61626. *
  61627. * @param {object} obj - The object to camelCase keys.
  61628. * @return {object} The object with keys camelCased.
  61629. */
  61630. function transformKeysToCamelCase (obj) {
  61631. var camelKey;
  61632. var key;
  61633. for (key in obj) {
  61634. camelKey = toCamelCase(key);
  61635. if (key === camelKey) { continue; }
  61636. obj[camelKey] = obj[key];
  61637. delete obj[key];
  61638. }
  61639. return obj;
  61640. }
  61641. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  61642. /**
  61643. * Split a string into chunks matching `<key>: <value>`
  61644. */
  61645. var getKeyValueChunks = (function () {
  61646. var chunks = [];
  61647. var hasUnclosedUrl = /url\([^)]+$/;
  61648. return function getKeyValueChunks (raw) {
  61649. var chunk = '';
  61650. var nextSplit;
  61651. var offset = 0;
  61652. var sep = ';';
  61653. chunks.length = 0;
  61654. while (offset < raw.length) {
  61655. nextSplit = raw.indexOf(sep, offset);
  61656. if (nextSplit === -1) { nextSplit = raw.length; }
  61657. chunk += raw.substring(offset, nextSplit);
  61658. // data URIs can contain semicolons, so make sure we get the whole thing
  61659. if (hasUnclosedUrl.test(chunk)) {
  61660. chunk += ';';
  61661. offset = nextSplit + 1;
  61662. continue;
  61663. }
  61664. chunks.push(chunk.trim());
  61665. chunk = '';
  61666. offset = nextSplit + 1;
  61667. }
  61668. return chunks;
  61669. };
  61670. })();
  61671. /**
  61672. * Convert a style attribute string to an object.
  61673. *
  61674. * @param {object} str - Attribute string.
  61675. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  61676. */
  61677. function styleParse (str, obj) {
  61678. var chunks;
  61679. var i;
  61680. var item;
  61681. var pos;
  61682. var key;
  61683. var val;
  61684. obj = obj || {};
  61685. chunks = getKeyValueChunks(str);
  61686. for (i = 0; i < chunks.length; i++) {
  61687. item = chunks[i];
  61688. if (!item) { continue; }
  61689. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  61690. pos = item.indexOf(':');
  61691. key = item.substr(0, pos).trim();
  61692. val = item.substr(pos + 1).trim();
  61693. obj[key] = val;
  61694. }
  61695. return obj;
  61696. }
  61697. /**
  61698. * Convert an object into an attribute string
  61699. **/
  61700. function styleStringify (obj) {
  61701. var key;
  61702. var keyCount = 0;
  61703. var i = 0;
  61704. var str = '';
  61705. for (key in obj) { keyCount++; }
  61706. for (key in obj) {
  61707. str += (key + ': ' + obj[key]);
  61708. if (i < keyCount - 1) { str += '; '; }
  61709. i++;
  61710. }
  61711. return str;
  61712. }
  61713. function upperCase (str) { return str[1].toUpperCase(); }
  61714. },{}],219:[function(require,module,exports){
  61715. var DEFAULT_HANDEDNESS = require('../constants').DEFAULT_HANDEDNESS;
  61716. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  61717. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  61718. /**
  61719. * Called on controller component `.play` handlers.
  61720. * Check if controller matches parameters and inject tracked-controls component.
  61721. * Handle event listeners.
  61722. * Generate controllerconnected or controllerdisconnected events.
  61723. *
  61724. * @param {object} component - Tracked controls component.
  61725. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  61726. * @param {object} queryObject - Map of values to match.
  61727. */
  61728. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  61729. var el = component.el;
  61730. var controller;
  61731. var hasWebXR = el.sceneEl.hasWebXR;
  61732. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  61733. var isPresent;
  61734. controller = isControllerPresent(component, idPrefix, queryObject);
  61735. isPresent = !!controller;
  61736. // If component was previously paused and now playing, re-add event listeners.
  61737. // Handle the event listeners here since this helper method is control of calling
  61738. // `.addEventListeners` and `.removeEventListeners`.
  61739. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  61740. component.addEventListeners();
  61741. }
  61742. // Nothing changed, no need to do anything.
  61743. if (isPresent === component.controllerPresent) { return isPresent; }
  61744. component.controllerPresent = isPresent;
  61745. // Update controller presence.
  61746. if (isPresent) {
  61747. component.addEventListeners();
  61748. component.injectTrackedControls(controller);
  61749. el.emit('controllerconnected', {name: component.name, component: component});
  61750. } else {
  61751. component.removeEventListeners();
  61752. el.emit('controllerdisconnected', {name: component.name, component: component});
  61753. }
  61754. };
  61755. /**
  61756. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  61757. *
  61758. * @param {object} component - Tracked controls component.
  61759. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  61760. * @param {object} queryObject - Map of values to match.
  61761. */
  61762. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  61763. var gamepads;
  61764. var sceneEl = component.el.sceneEl;
  61765. var trackedControlsSystem;
  61766. var filterControllerIndex = queryObject.index || 0;
  61767. if (!idPrefix) { return false; }
  61768. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  61769. if (!trackedControlsSystem) { return false; }
  61770. gamepads = trackedControlsSystem.controllers;
  61771. if (!gamepads.length) { return false; }
  61772. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  61773. filterControllerIndex);
  61774. }
  61775. /**
  61776. *
  61777. * @param {object} component - Tracked controls component.
  61778. */
  61779. function isControllerPresentWebXR (component, id, queryObject) {
  61780. var controllers;
  61781. var sceneEl = component.el.sceneEl;
  61782. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  61783. if (!trackedControlsSystem) { return false; }
  61784. controllers = trackedControlsSystem.controllers;
  61785. if (!controllers || !controllers.length) { return false; }
  61786. return findMatchingControllerWebXR(
  61787. controllers, id,
  61788. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles, queryObject.handTracking);
  61789. }
  61790. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  61791. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  61792. /**
  61793. * Walk through the given controllers to find any where the device ID equals
  61794. * filterIdExact, or startsWith filterIdPrefix.
  61795. * A controller where this considered true is considered a 'match'.
  61796. *
  61797. * For each matching controller:
  61798. * If filterHand is set, and the controller:
  61799. * is handed, we further verify that controller.hand equals filterHand.
  61800. * is unhanded (controller.hand is ''), we skip until we have found a
  61801. * number of matching controllers that equals filterControllerIndex
  61802. * If filterHand is not set, we skip until we have found the nth matching
  61803. * controller, where n equals filterControllerIndex
  61804. *
  61805. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  61806. * one or both of: [filterHand, filterControllerIndex]
  61807. *
  61808. * @param {object} controllers - Array of gamepads to search
  61809. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  61810. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  61811. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  61812. * @param {object} filterControllerIndex - Find the nth matching controller,
  61813. * where n equals filterControllerIndex. defaults to 0.
  61814. */
  61815. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  61816. filterControllerIndex) {
  61817. var controller;
  61818. var i;
  61819. var matchingControllerOccurence = 0;
  61820. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  61821. for (i = 0; i < controllers.length; i++) {
  61822. controller = controllers[i];
  61823. // Determine if the controller ID matches our criteria.
  61824. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  61825. continue;
  61826. }
  61827. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  61828. // If the hand filter and controller handedness are defined we compare them.
  61829. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  61830. // If we have detected an unhanded controller and the component was asking
  61831. // for a particular hand, we need to treat the controllers in the array as
  61832. // pairs of controllers. This effectively means that we need to skip
  61833. // NUM_HANDS matches for each controller number, instead of 1.
  61834. if (filterHand && !controller.hand) {
  61835. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  61836. } else {
  61837. return controller;
  61838. }
  61839. // We are looking for the nth occurence of a matching controller
  61840. // (n equals targetControllerMatch).
  61841. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  61842. ++matchingControllerOccurence;
  61843. }
  61844. return undefined;
  61845. }
  61846. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles, handTracking) {
  61847. var i;
  61848. var j;
  61849. var controller;
  61850. var controllerMatch = false;
  61851. var controllerHasHandedness;
  61852. var profiles;
  61853. for (i = 0; i < controllers.length; i++) {
  61854. controller = controllers[i];
  61855. profiles = controller.profiles;
  61856. if (handTracking) {
  61857. controllerMatch = controller.hand;
  61858. } else {
  61859. if (iterateProfiles) {
  61860. for (j = 0; j < profiles.length; j++) {
  61861. controllerMatch = profiles[j].startsWith(idPrefix);
  61862. if (controllerMatch) { break; }
  61863. }
  61864. } else {
  61865. controllerMatch = profiles.length > 0 && profiles[0].startsWith(idPrefix);
  61866. }
  61867. }
  61868. if (!controllerMatch) { continue; }
  61869. // Vive controllers are assigned handedness at runtime and it might not be always available.
  61870. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  61871. if (controllerHasHandedness) {
  61872. if (controller.handedness === handedness) { return controllers[i]; }
  61873. } else { // Fallback to index if controller has no handedness.
  61874. if ((i === index)) { return controllers[i]; }
  61875. }
  61876. }
  61877. return undefined;
  61878. }
  61879. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  61880. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  61881. /**
  61882. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  61883. *
  61884. * @param {object} component - Controller component in use.
  61885. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  61886. * @param {object} evt - Event to process.
  61887. */
  61888. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  61889. var axes;
  61890. var buttonType;
  61891. var changed;
  61892. var detail;
  61893. var j;
  61894. for (buttonType in axesMapping) {
  61895. axes = axesMapping[buttonType];
  61896. changed = false;
  61897. for (j = 0; j < axes.length; j++) {
  61898. if (evt.detail.changed[axes[j]]) { changed = true; }
  61899. }
  61900. if (!changed) { continue; }
  61901. // Axis has changed. Emit the specific moved event with axis values in detail.
  61902. detail = {};
  61903. for (j = 0; j < axes.length; j++) {
  61904. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  61905. }
  61906. component.el.emit(buttonType + 'moved', detail);
  61907. }
  61908. };
  61909. /**
  61910. * Handle a button event and reemits the events.
  61911. *
  61912. * @param {string} id - id of the button.
  61913. * @param {string} evtName - name of the reemitted event
  61914. * @param {object} component - reference to the component
  61915. * @param {string} hand - handedness of the controller: left or right.
  61916. */
  61917. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  61918. var mapping = hand ? component.mapping[hand] : component.mapping;
  61919. var buttonName = mapping.buttons[id];
  61920. component.el.emit(buttonName + evtName);
  61921. if (component.updateModel) {
  61922. component.updateModel(buttonName, evtName);
  61923. }
  61924. };
  61925. },{"../constants":127}],220:[function(require,module,exports){
  61926. /**
  61927. * @author richt / http://richt.me
  61928. * @author WestLangley / http://github.com/WestLangley
  61929. *
  61930. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  61931. */
  61932. THREE.DeviceOrientationControls = function ( object ) {
  61933. var scope = this;
  61934. this.object = object;
  61935. this.object.rotation.reorder( 'YXZ' );
  61936. this.enabled = true;
  61937. this.deviceOrientation = {};
  61938. this.screenOrientation = 0;
  61939. this.alphaOffset = 0; // radians
  61940. var onDeviceOrientationChangeEvent = function ( event ) {
  61941. scope.deviceOrientation = event;
  61942. };
  61943. var onScreenOrientationChangeEvent = function () {
  61944. scope.screenOrientation = window.orientation || 0;
  61945. };
  61946. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  61947. var setObjectQuaternion = function () {
  61948. var zee = new THREE.Vector3( 0, 0, 1 );
  61949. var euler = new THREE.Euler();
  61950. var q0 = new THREE.Quaternion();
  61951. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  61952. return function ( quaternion, alpha, beta, gamma, orient ) {
  61953. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  61954. quaternion.setFromEuler( euler ); // orient the device
  61955. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  61956. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  61957. };
  61958. }();
  61959. this.connect = function () {
  61960. onScreenOrientationChangeEvent();
  61961. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  61962. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  61963. scope.enabled = true;
  61964. };
  61965. this.disconnect = function () {
  61966. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  61967. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  61968. scope.enabled = false;
  61969. };
  61970. this.update = function () {
  61971. if ( scope.enabled === false ) return;
  61972. var device = scope.deviceOrientation;
  61973. if ( device ) {
  61974. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  61975. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  61976. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  61977. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  61978. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  61979. }
  61980. };
  61981. this.dispose = function () {
  61982. scope.disconnect();
  61983. };
  61984. this.connect();
  61985. };
  61986. },{}],221:[function(require,module,exports){
  61987. window.glStats = function () {
  61988. var _rS = null;
  61989. var _totalDrawArraysCalls = 0,
  61990. _totalDrawElementsCalls = 0,
  61991. _totalUseProgramCalls = 0,
  61992. _totalFaces = 0,
  61993. _totalVertices = 0,
  61994. _totalPoints = 0,
  61995. _totalBindTexures = 0;
  61996. function _h ( f, c ) {
  61997. return function () {
  61998. c.apply( this, arguments );
  61999. f.apply( this, arguments );
  62000. };
  62001. }
  62002. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  62003. _totalDrawArraysCalls++;
  62004. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  62005. else _totalVertices += arguments[ 2 ];
  62006. } );
  62007. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  62008. _totalDrawElementsCalls++;
  62009. _totalFaces += arguments[ 1 ] / 3;
  62010. _totalVertices += arguments[ 1 ];
  62011. } );
  62012. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  62013. _totalUseProgramCalls++;
  62014. } );
  62015. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  62016. _totalBindTexures++;
  62017. } );
  62018. var _values = {
  62019. allcalls: {
  62020. over: 3000,
  62021. caption: 'Calls (hook)'
  62022. },
  62023. drawelements: {
  62024. caption: 'drawElements (hook)'
  62025. },
  62026. drawarrays: {
  62027. caption: 'drawArrays (hook)'
  62028. }
  62029. };
  62030. var _groups = [ {
  62031. caption: 'WebGL',
  62032. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  62033. } ];
  62034. var _fractions = [ {
  62035. base: 'allcalls',
  62036. steps: [ 'drawelements', 'drawarrays' ]
  62037. } ];
  62038. function _update () {
  62039. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  62040. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  62041. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  62042. _rS( 'bindTexture' ).set( _totalBindTexures );
  62043. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  62044. _rS( 'glfaces' ).set( _totalFaces );
  62045. _rS( 'glvertices' ).set( _totalVertices );
  62046. _rS( 'glpoints' ).set( _totalPoints );
  62047. }
  62048. function _start () {
  62049. _totalDrawArraysCalls = 0;
  62050. _totalDrawElementsCalls = 0;
  62051. _totalUseProgramCalls = 0;
  62052. _totalFaces = 0;
  62053. _totalVertices = 0;
  62054. _totalPoints = 0;
  62055. _totalBindTexures = 0;
  62056. }
  62057. function _end () {}
  62058. function _attach ( r ) {
  62059. _rS = r;
  62060. }
  62061. return {
  62062. update: _update,
  62063. start: _start,
  62064. end: _end,
  62065. attach: _attach,
  62066. values: _values,
  62067. groups: _groups,
  62068. fractions: _fractions
  62069. };
  62070. };
  62071. window.threeStats = function ( renderer ) {
  62072. var _rS = null;
  62073. var _values = {
  62074. 'renderer.info.memory.geometries': {
  62075. caption: 'Geometries'
  62076. },
  62077. 'renderer.info.memory.textures': {
  62078. caption: 'Textures'
  62079. },
  62080. 'renderer.info.programs': {
  62081. caption: 'Programs'
  62082. },
  62083. 'renderer.info.render.calls': {
  62084. caption: 'Calls'
  62085. },
  62086. 'renderer.info.render.triangles': {
  62087. caption: 'Triangles',
  62088. over: 1000
  62089. },
  62090. 'renderer.info.render.points': {
  62091. caption: 'Points'
  62092. }
  62093. };
  62094. var _groups = [ {
  62095. caption: 'Three.js - Memory',
  62096. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  62097. }, {
  62098. caption: 'Three.js - Render',
  62099. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  62100. } ];
  62101. var _fractions = [];
  62102. function _update () {
  62103. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  62104. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  62105. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  62106. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  62107. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  62108. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  62109. }
  62110. function _start () {}
  62111. function _end () {}
  62112. function _attach ( r ) {
  62113. _rS = r;
  62114. }
  62115. return {
  62116. update: _update,
  62117. start: _start,
  62118. end: _end,
  62119. attach: _attach,
  62120. values: _values,
  62121. groups: _groups,
  62122. fractions: _fractions
  62123. };
  62124. };
  62125. /*
  62126. * From https://github.com/paulirish/memory-stats.js
  62127. */
  62128. window.BrowserStats = function () {
  62129. var _rS = null;
  62130. var _usedJSHeapSize = 0,
  62131. _totalJSHeapSize = 0;
  62132. if ( window.performance && !performance.memory ) {
  62133. performance.memory = {
  62134. usedJSHeapSize: 0,
  62135. totalJSHeapSize: 0
  62136. };
  62137. }
  62138. if ( performance.memory.totalJSHeapSize === 0 ) {
  62139. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  62140. }
  62141. var _values = {
  62142. memory: {
  62143. caption: 'Used Memory',
  62144. average: true,
  62145. avgMs: 1000,
  62146. over: 22
  62147. },
  62148. total: {
  62149. caption: 'Total Memory'
  62150. }
  62151. };
  62152. var _groups = [ {
  62153. caption: 'Browser',
  62154. values: [ 'memory', 'total' ]
  62155. } ];
  62156. var _fractions = [ {
  62157. base: 'total',
  62158. steps: [ 'memory' ]
  62159. } ];
  62160. var log1024 = Math.log( 1024 );
  62161. function _size ( v ) {
  62162. var precision = 100; //Math.pow(10, 2);
  62163. var i = Math.floor( Math.log( v ) / log1024 );
  62164. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  62165. }
  62166. function _update () {
  62167. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  62168. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  62169. _rS( 'memory' ).set( _usedJSHeapSize );
  62170. _rS( 'total' ).set( _totalJSHeapSize );
  62171. }
  62172. function _start () {
  62173. _usedJSHeapSize = 0;
  62174. }
  62175. function _end () {}
  62176. function _attach ( r ) {
  62177. _rS = r;
  62178. }
  62179. return {
  62180. update: _update,
  62181. start: _start,
  62182. end: _end,
  62183. attach: _attach,
  62184. values: _values,
  62185. groups: _groups,
  62186. fractions: _fractions
  62187. };
  62188. };
  62189. if (typeof module === 'object') {
  62190. module.exports = {
  62191. glStats: window.glStats,
  62192. threeStats: window.threeStats,
  62193. BrowserStats: window.BrowserStats
  62194. };
  62195. }
  62196. },{}],222:[function(require,module,exports){
  62197. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  62198. 'use strict';
  62199. ( function () {
  62200. if ( 'performance' in window == false ) {
  62201. window.performance = {};
  62202. }
  62203. var performance = window.performance;
  62204. if ( 'now' in performance == false ) {
  62205. var nowOffset = Date.now();
  62206. if ( performance.timing && performance.timing.navigationStart ) {
  62207. nowOffset = performance.timing.navigationStart;
  62208. }
  62209. performance.now = function now () {
  62210. return Date.now() - nowOffset;
  62211. };
  62212. }
  62213. if( !performance.mark ) {
  62214. performance.mark = function(){}
  62215. }
  62216. if( !performance.measure ) {
  62217. performance.measure = function(){}
  62218. }
  62219. } )();
  62220. window.rStats = function rStats ( settings ) {
  62221. function iterateKeys ( array, callback ) {
  62222. var keys = Object.keys( array );
  62223. for ( var j = 0, l = keys.length; j < l; j++ ) {
  62224. callback( keys[ j ] );
  62225. }
  62226. }
  62227. function importCSS ( url ) {
  62228. var element = document.createElement( 'link' );
  62229. element.href = url;
  62230. element.rel = 'stylesheet';
  62231. element.type = 'text/css';
  62232. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  62233. }
  62234. var _settings = settings || {};
  62235. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  62236. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  62237. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  62238. var _css = _settings.css || [ _cssFont, _cssRStats ];
  62239. _css.forEach(function (uri) {
  62240. importCSS( uri );
  62241. });
  62242. if ( !_settings.values ) _settings.values = {};
  62243. var _base, _div, _elHeight = 10, _elWidth = 200;
  62244. var _perfCounters = {};
  62245. function Graph ( _dom, _id, _defArg ) {
  62246. var _def = _defArg || {};
  62247. var _canvas = document.createElement( 'canvas' ),
  62248. _ctx = _canvas.getContext( '2d' ),
  62249. _max = 0,
  62250. _current = 0;
  62251. var c = _def.color ? _def.color : '#666666';
  62252. var _dotCanvas = document.createElement( 'canvas' ),
  62253. _dotCtx = _dotCanvas.getContext( '2d' );
  62254. _dotCanvas.width = 1;
  62255. _dotCanvas.height = 2 * _elHeight;
  62256. _dotCtx.fillStyle = '#444444';
  62257. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62258. _dotCtx.fillStyle = c;
  62259. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62260. _dotCtx.fillStyle = '#ffffff';
  62261. _dotCtx.globalAlpha = 0.5;
  62262. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  62263. _dotCtx.globalAlpha = 1;
  62264. var _alarmCanvas = document.createElement( 'canvas' ),
  62265. _alarmCtx = _alarmCanvas.getContext( '2d' );
  62266. _alarmCanvas.width = 1;
  62267. _alarmCanvas.height = 2 * _elHeight;
  62268. _alarmCtx.fillStyle = '#444444';
  62269. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62270. _alarmCtx.fillStyle = '#b70000';
  62271. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62272. _alarmCtx.globalAlpha = 0.5;
  62273. _alarmCtx.fillStyle = '#ffffff';
  62274. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  62275. _alarmCtx.globalAlpha = 1;
  62276. function _init () {
  62277. _canvas.width = _elWidth;
  62278. _canvas.height = _elHeight;
  62279. _canvas.style.width = _canvas.width + 'px';
  62280. _canvas.style.height = _canvas.height + 'px';
  62281. _canvas.className = 'rs-canvas';
  62282. _dom.appendChild( _canvas );
  62283. _ctx.fillStyle = '#444444';
  62284. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62285. }
  62286. function _draw ( v, alarm ) {
  62287. _current += ( v - _current ) * 0.1;
  62288. _max *= 0.99;
  62289. if ( _current > _max ) _max = _current;
  62290. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62291. if ( alarm ) {
  62292. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62293. } else {
  62294. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62295. }
  62296. }
  62297. _init();
  62298. return {
  62299. draw: _draw
  62300. };
  62301. }
  62302. function StackGraph ( _dom, _num ) {
  62303. var _canvas = document.createElement( 'canvas' ),
  62304. _ctx = _canvas.getContext( '2d' );
  62305. function _init () {
  62306. _canvas.width = _elWidth;
  62307. _canvas.height = _elHeight * _num;
  62308. _canvas.style.width = _canvas.width + 'px';
  62309. _canvas.style.height = _canvas.height + 'px';
  62310. _canvas.className = 'rs-canvas';
  62311. _dom.appendChild( _canvas );
  62312. _ctx.fillStyle = '#444444';
  62313. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62314. }
  62315. function _draw ( v ) {
  62316. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62317. var th = 0;
  62318. iterateKeys( v, function ( j ) {
  62319. var h = v[ j ] * _canvas.height;
  62320. _ctx.fillStyle = _colours[ j ];
  62321. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  62322. th += h;
  62323. } );
  62324. }
  62325. _init();
  62326. return {
  62327. draw: _draw
  62328. };
  62329. }
  62330. function PerfCounter ( id, group ) {
  62331. var _id = id,
  62332. _time,
  62333. _value = 0,
  62334. _total = 0,
  62335. _averageValue = 0,
  62336. _accumValue = 0,
  62337. _accumStart = performance.now(),
  62338. _accumSamples = 0,
  62339. _dom = document.createElement( 'div' ),
  62340. _spanId = document.createElement( 'span' ),
  62341. _spanValue = document.createElement( 'div' ),
  62342. _spanValueText = document.createTextNode( '' ),
  62343. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  62344. _graph = new Graph( _dom, _id, _def ),
  62345. _started = false;
  62346. _spanId.className = 'rs-counter-id';
  62347. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  62348. _spanValue.className = 'rs-counter-value';
  62349. _spanValue.appendChild( _spanValueText );
  62350. _dom.appendChild( _spanId );
  62351. _dom.appendChild( _spanValue );
  62352. if ( group ) group.div.appendChild( _dom );
  62353. else _div.appendChild( _dom );
  62354. _time = performance.now();
  62355. function _average ( v ) {
  62356. if ( _def && _def.average ) {
  62357. _accumValue += v;
  62358. _accumSamples++;
  62359. var t = performance.now();
  62360. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  62361. _averageValue = _accumValue / _accumSamples;
  62362. _accumValue = 0;
  62363. _accumStart = t;
  62364. _accumSamples = 0;
  62365. }
  62366. }
  62367. }
  62368. function _start () {
  62369. _time = performance.now();
  62370. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  62371. _started = true;
  62372. }
  62373. function _end () {
  62374. _value = performance.now() - _time;
  62375. if( _settings.userTimingAPI ) {
  62376. performance.mark( _id + '-end' );
  62377. if( _started ) {
  62378. performance.measure( _id, _id + '-start', _id + '-end' );
  62379. }
  62380. }
  62381. _average( _value );
  62382. }
  62383. function _tick () {
  62384. _end();
  62385. _start();
  62386. }
  62387. function _draw () {
  62388. var v = ( _def && _def.average ) ? _averageValue : _value;
  62389. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  62390. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  62391. _graph.draw( _value, a );
  62392. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  62393. }
  62394. function _frame () {
  62395. var t = performance.now();
  62396. var e = t - _time;
  62397. _total++;
  62398. if ( e > 1000 ) {
  62399. if ( _def && _def.interpolate === false ) {
  62400. _value = _total;
  62401. } else {
  62402. _value = _total * 1000 / e;
  62403. }
  62404. _total = 0;
  62405. _time = t;
  62406. _average( _value );
  62407. }
  62408. }
  62409. function _set ( v ) {
  62410. _value = v;
  62411. _average( _value );
  62412. }
  62413. return {
  62414. set: _set,
  62415. start: _start,
  62416. tick: _tick,
  62417. end: _end,
  62418. frame: _frame,
  62419. value: function () {
  62420. return _value;
  62421. },
  62422. draw: _draw
  62423. };
  62424. }
  62425. function sample () {
  62426. var _value = 0;
  62427. function _set ( v ) {
  62428. _value = v;
  62429. }
  62430. return {
  62431. set: _set,
  62432. value: function () {
  62433. return _value;
  62434. }
  62435. };
  62436. }
  62437. function _perf ( idArg ) {
  62438. var id = idArg.toLowerCase();
  62439. if ( id === undefined ) id = 'default';
  62440. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  62441. var group = null;
  62442. if ( _settings && _settings.groups ) {
  62443. iterateKeys( _settings.groups, function ( j ) {
  62444. var g = _settings.groups[ parseInt( j, 10 ) ];
  62445. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  62446. group = g;
  62447. }
  62448. } );
  62449. }
  62450. var p = new PerfCounter( id, group );
  62451. _perfCounters[ id ] = p;
  62452. return p;
  62453. }
  62454. function _init () {
  62455. if ( _settings.plugins ) {
  62456. if ( !_settings.values ) _settings.values = {};
  62457. if ( !_settings.groups ) _settings.groups = [];
  62458. if ( !_settings.fractions ) _settings.fractions = [];
  62459. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  62460. _settings.plugins[ j ].attach( _perf );
  62461. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  62462. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  62463. } );
  62464. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  62465. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  62466. }
  62467. } else {
  62468. _settings.plugins = {};
  62469. }
  62470. _base = document.createElement( 'div' );
  62471. _base.className = 'rs-base';
  62472. _div = document.createElement( 'div' );
  62473. _div.className = 'rs-container';
  62474. _div.style.height = 'auto';
  62475. _base.appendChild( _div );
  62476. document.body.appendChild( _base );
  62477. if ( !_settings ) return;
  62478. if ( _settings.groups ) {
  62479. iterateKeys( _settings.groups, function ( j ) {
  62480. var g = _settings.groups[ parseInt( j, 10 ) ];
  62481. var div = document.createElement( 'div' );
  62482. div.className = 'rs-group';
  62483. g.div = div;
  62484. var h1 = document.createElement( 'h1' );
  62485. h1.textContent = g.caption;
  62486. h1.addEventListener( 'click', function ( e ) {
  62487. this.classList.toggle( 'hidden' );
  62488. e.preventDefault();
  62489. }.bind( div ) );
  62490. _div.appendChild( h1 );
  62491. _div.appendChild( div );
  62492. } );
  62493. }
  62494. if ( _settings.fractions ) {
  62495. iterateKeys( _settings.fractions, function ( j ) {
  62496. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62497. var div = document.createElement( 'div' );
  62498. div.className = 'rs-fraction';
  62499. var legend = document.createElement( 'div' );
  62500. legend.className = 'rs-legend';
  62501. var h = 0;
  62502. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62503. var p = document.createElement( 'p' );
  62504. p.textContent = _settings.fractions[ j ].steps[ k ];
  62505. p.style.color = _colours[ h ];
  62506. legend.appendChild( p );
  62507. h++;
  62508. } );
  62509. div.appendChild( legend );
  62510. div.style.height = h * _elHeight + 'px';
  62511. f.div = div;
  62512. var graph = new StackGraph( div, h );
  62513. f.graph = graph;
  62514. _div.appendChild( div );
  62515. } );
  62516. }
  62517. }
  62518. function _update () {
  62519. iterateKeys( _settings.plugins, function ( j ) {
  62520. _settings.plugins[ j ].update();
  62521. } );
  62522. iterateKeys( _perfCounters, function ( j ) {
  62523. _perfCounters[ j ].draw();
  62524. } );
  62525. if ( _settings && _settings.fractions ) {
  62526. iterateKeys( _settings.fractions, function ( j ) {
  62527. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62528. var v = [];
  62529. var base = _perfCounters[ f.base.toLowerCase() ];
  62530. if ( base ) {
  62531. base = base.value();
  62532. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62533. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  62534. var val = _perfCounters[ s ];
  62535. if ( val ) {
  62536. v.push( val.value() / base );
  62537. }
  62538. } );
  62539. }
  62540. f.graph.draw( v );
  62541. } );
  62542. }
  62543. /*if( _height != _div.clientHeight ) {
  62544. _height = _div.clientHeight;
  62545. _base.style.height = _height + 2 * _elHeight + 'px';
  62546. console.log( _base.clientHeight );
  62547. }*/
  62548. }
  62549. _init();
  62550. return function ( id ) {
  62551. if ( id ) return _perf( id );
  62552. return {
  62553. element: _base,
  62554. update: _update
  62555. };
  62556. };
  62557. }
  62558. if (typeof module === 'object') {
  62559. module.exports = window.rStats;
  62560. }
  62561. },{}],223:[function(require,module,exports){
  62562. // https://stackoverflow.com/a/36213464
  62563. if (!String.prototype.startsWith) {
  62564. String.prototype.startsWith = function(searchString, position){
  62565. position = position || 0;
  62566. return this.substr(position, searchString.length) === searchString;
  62567. };
  62568. }
  62569. },{}],224:[function(require,module,exports){
  62570. /*
  62571. * Copyright 2015 Google Inc. All Rights Reserved.
  62572. * Licensed under the Apache License, Version 2.0 (the "License");
  62573. * you may not use this file except in compliance with the License.
  62574. * You may obtain a copy of the License at
  62575. *
  62576. * http://www.apache.org/licenses/LICENSE-2.0
  62577. *
  62578. * Unless required by applicable law or agreed to in writing, software
  62579. * distributed under the License is distributed on an "AS IS" BASIS,
  62580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62581. * See the License for the specific language governing permissions and
  62582. * limitations under the License.
  62583. */
  62584. var Util = {};
  62585. Util.base64 = function(mimeType, base64) {
  62586. return 'data:' + mimeType + ';base64,' + base64;
  62587. };
  62588. Util.isMobile = function() {
  62589. var check = false;
  62590. (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);
  62591. return check;
  62592. };
  62593. Util.isIOS = function() {
  62594. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  62595. };
  62596. Util.isIFrame = function() {
  62597. try {
  62598. return window.self !== window.top;
  62599. } catch (e) {
  62600. return true;
  62601. }
  62602. };
  62603. Util.appendQueryParameter = function(url, key, value) {
  62604. // Determine delimiter based on if the URL already GET parameters in it.
  62605. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  62606. url += delimiter + key + '=' + value;
  62607. return url;
  62608. };
  62609. // From http://goo.gl/4WX3tg
  62610. Util.getQueryParameter = function(name) {
  62611. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  62612. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  62613. results = regex.exec(location.search);
  62614. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  62615. };
  62616. Util.isLandscapeMode = function() {
  62617. return (window.orientation == 90 || window.orientation == -90);
  62618. };
  62619. module.exports = Util;
  62620. },{}],225:[function(require,module,exports){
  62621. /*
  62622. * Copyright 2015 Google Inc. All Rights Reserved.
  62623. * Licensed under the Apache License, Version 2.0 (the "License");
  62624. * you may not use this file except in compliance with the License.
  62625. * You may obtain a copy of the License at
  62626. *
  62627. * http://www.apache.org/licenses/LICENSE-2.0
  62628. *
  62629. * Unless required by applicable law or agreed to in writing, software
  62630. * distributed under the License is distributed on an "AS IS" BASIS,
  62631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62632. * See the License for the specific language governing permissions and
  62633. * limitations under the License.
  62634. */
  62635. var Util = require('./util.js');
  62636. /**
  62637. * Android and iOS compatible wakelock implementation.
  62638. *
  62639. * Refactored thanks to dkovalev@.
  62640. */
  62641. function AndroidWakeLock() {
  62642. var video = document.createElement('video');
  62643. video.addEventListener('ended', function() {
  62644. video.play();
  62645. });
  62646. this.request = function() {
  62647. if (video.paused) {
  62648. // Base64 version of videos_src/no-sleep-60s.webm.
  62649. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  62650. video.play();
  62651. }
  62652. };
  62653. this.release = function() {
  62654. video.pause();
  62655. video.src = '';
  62656. };
  62657. }
  62658. function iOSWakeLock() {
  62659. var timer = null;
  62660. this.request = function() {
  62661. if (!timer) {
  62662. timer = setInterval(function() {
  62663. window.location.href = '/';
  62664. setTimeout(window.stop, 0);
  62665. }, 15000);
  62666. }
  62667. }
  62668. this.release = function() {
  62669. if (timer) {
  62670. clearInterval(timer);
  62671. timer = null;
  62672. }
  62673. }
  62674. }
  62675. function getWakeLock() {
  62676. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  62677. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  62678. return iOSWakeLock;
  62679. } else {
  62680. return AndroidWakeLock;
  62681. }
  62682. }
  62683. module.exports = getWakeLock();
  62684. },{"./util.js":224}]},{},[181])(181)
  62685. });
  62686. //# sourceMappingURL=aframe-master.js.map